@@ -59,6 +59,7 @@ import kotlinx.coroutines.withTimeoutOrNull
5959import java.io.IOException
6060import java.net.URISyntaxException
6161import java.nio.ByteBuffer
62+ import java.util.concurrent.atomic.AtomicLong
6263import javax.net.ssl.TrustManager
6364
6465/* *
@@ -109,6 +110,10 @@ class RtmpClient(private val connectChecker: ConnectChecker) {
109110 var socketType = SocketType .KTOR
110111 var socketTimeout = StreamSocket .DEFAULT_TIMEOUT
111112 var shouldFailOnRead = false
113+ var shouldSendPings = false
114+ var rtt = 0 // in micro
115+ private set
116+ private val pingTs = AtomicLong (0 )
112117
113118 /* *
114119 * Add certificates for TLS connection
@@ -145,6 +150,10 @@ class RtmpClient(private val connectChecker: ConnectChecker) {
145150 checkServerAlive = enabled
146151 }
147152
153+ fun shouldSendPings (enabled : Boolean ) {
154+ shouldSendPings = enabled
155+ }
156+
148157 /* *
149158 * Must be called before connect
150159 */
@@ -286,6 +295,7 @@ class RtmpClient(private val connectChecker: ConnectChecker) {
286295 // Handle all command received and send response for it.
287296 handleMessages()
288297 }
298+ if (shouldSendPings) commandsManager.sendPing(socket)
289299 // read packet because maybe server want send you something while streaming
290300 handleServerPackets()
291301 }.exceptionOrNull()
@@ -387,6 +397,19 @@ class RtmpClient(private val connectChecker: ConnectChecker) {
387397 Type .PING_REQUEST -> {
388398 commandsManager.sendPong(userControl.event, socket)
389399 }
400+ Type .PONG_REPLY -> {
401+ Log .i(TAG , " pong received: ${userControl.event.data} " )
402+ if (shouldSendPings) {
403+ rtt = (TimeUtils .getCurrentTimeMicro() - pingTs.get()).toInt()
404+ CoroutineScope (Dispatchers .IO ).launch {
405+ delay(1000 )
406+ if (isStreaming) {
407+ pingTs.set(TimeUtils .getCurrentTimeMicro())
408+ commandsManager.sendPing(socket)
409+ }
410+ }
411+ }
412+ }
390413 else -> {
391414 Log .i(TAG , " user control command $type ignored" )
392415 }
@@ -563,6 +586,7 @@ class RtmpClient(private val connectChecker: ConnectChecker) {
563586 scope = CoroutineScope (Dispatchers .IO )
564587 publishPermitted = false
565588 commandsManager.reset()
589+ rtt = 0
566590 }
567591
568592 fun sendVideo (videoBuffer : ByteBuffer , info : MediaCodec .BufferInfo ) {
0 commit comments