idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
6,500
private IoBuffer encodeClientBW ( ClientBW clientBW ) { final IoBuffer out = IoBuffer . allocate ( 5 ) ; out . putInt ( clientBW . getBandwidth ( ) ) ; out . put ( clientBW . getLimitType ( ) ) ; return out ; }
Encode client - side bandwidth event .
6,501
protected IoBuffer encodeCommand ( Notify invoke ) { IoBuffer out = IoBuffer . allocate ( 1024 ) ; out . setAutoExpand ( true ) ; encodeCommand ( out , invoke ) ; return out ; }
Encode notification event .
6,502
protected StatusObject generateErrorResult ( String code , Throwable error ) { String message = "" ; while ( error != null && error . getCause ( ) != null ) { error = error . getCause ( ) ; } if ( error != null && error . getMessage ( ) != null ) { message = error . getMessage ( ) ; } StatusObject status = new StatusObject ( code , "error" , message ) ; if ( error instanceof ClientDetailsException ) { status . setApplication ( ( ( ClientDetailsException ) error ) . getParameters ( ) ) ; if ( ( ( ClientDetailsException ) error ) . includeStacktrace ( ) ) { List < String > stack = new ArrayList < String > ( ) ; for ( StackTraceElement element : error . getStackTrace ( ) ) { stack . add ( element . toString ( ) ) ; } status . setAdditional ( "stacktrace" , stack ) ; } } else if ( error != null ) { status . setApplication ( error . getClass ( ) . getCanonicalName ( ) ) ; List < String > stack = new ArrayList < String > ( ) ; for ( StackTraceElement element : error . getStackTrace ( ) ) { stack . add ( element . toString ( ) ) ; } status . setAdditional ( "stacktrace" , stack ) ; } return status ; }
Generate error object to return for given exception .
6,503
public IoBuffer encodeFlexMessage ( FlexMessage msg ) { IoBuffer out = IoBuffer . allocate ( 1024 ) ; out . setAutoExpand ( true ) ; out . put ( ( byte ) 0 ) ; encodeCommand ( out , msg ) ; return out ; }
Encodes Flex message event .
6,504
public void resultReceived ( IPendingServiceCall call ) { if ( Call . STATUS_NOT_CONNECTED != call . getStatus ( ) ) { long now = System . nanoTime ( ) ; int received = packetsReceived . incrementAndGet ( ) ; log . debug ( "Call time stamps - write: {} read: {}" , call . getWriteTime ( ) , call . getReadTime ( ) ) ; timePassed = ( now - startTime ) / 1000000 ; log . debug ( "Received count: {} sent: {} timePassed: {} ms" , new Object [ ] { received , packetsSent . get ( ) , timePassed } ) ; switch ( received ) { case 1 : latency = Math . max ( Math . min ( timePassed , LATENCY_MAX ) , LATENCY_MIN ) ; log . debug ( "Receive latency: {}" , latency ) ; log . debug ( "Sending first payload at {} ns" , now ) ; callBWCheck ( payload ) ; break ; case 2 : log . debug ( "Sending second payload at {} ns" , now ) ; cumLatency ++ ; callBWCheck ( payload1 ) ; break ; default : log . debug ( "Doing calculations at {} ns" , now ) ; cumLatency ++ ; deltaDown = ( ( conn . getWrittenBytes ( ) - startBytesWritten ) * 8 ) / 1000d ; log . debug ( "Delta kbits: {}" , deltaDown ) ; deltaTime = ( timePassed - ( latency * cumLatency ) ) ; if ( deltaTime <= 0 ) { deltaTime = ( timePassed + latency ) ; } log . debug ( "Delta time: {} ms" , deltaTime ) ; kbitDown = Math . round ( deltaDown / ( deltaTime / 1000d ) ) ; log . debug ( "onBWDone: kbitDown: {} deltaDown: {} deltaTime: {} latency: {} " , new Object [ ] { kbitDown , deltaDown , deltaTime , latency } ) ; callBWDone ( ) ; } } else { log . debug ( "Pending call skipped due to being no longer connected" ) ; } }
Handle callback from service call .
6,505
public void setData ( IoBuffer buffer ) { if ( noCopy ) { log . trace ( "Using buffer reference" ) ; this . data = buffer ; } else { if ( buffer . hasArray ( ) ) { log . trace ( "Buffer has backing array, making a copy" ) ; byte [ ] copy = new byte [ buffer . limit ( ) ] ; buffer . mark ( ) ; buffer . get ( copy ) ; buffer . reset ( ) ; data = IoBuffer . wrap ( copy ) ; } else { log . trace ( "Buffer has no backing array, using ByteBuffer" ) ; data . put ( buffer . buf ( ) ) . flip ( ) ; } } }
Setter for data
6,506
public static byte toByte ( Type type ) { switch ( type ) { case SERVER_CONNECT : return 0x01 ; case SERVER_DISCONNECT : return 0x02 ; case SERVER_SET_ATTRIBUTE : return 0x03 ; case CLIENT_UPDATE_DATA : return 0x04 ; case CLIENT_UPDATE_ATTRIBUTE : return 0x05 ; case SERVER_SEND_MESSAGE : return 0x06 ; case CLIENT_SEND_MESSAGE : return 0x06 ; case CLIENT_STATUS : return 0x07 ; case CLIENT_CLEAR_DATA : return 0x08 ; case CLIENT_DELETE_DATA : return 0x09 ; case SERVER_DELETE_ATTRIBUTE : return 0x0A ; case CLIENT_INITIAL_DATA : return 0x0B ; default : log . error ( "Unknown type " + type ) ; return 0x00 ; } }
Convert SO event type to byte representation that RTMP uses
6,507
private void sendChunkSize ( ) { if ( chunkSizeSent . compareAndSet ( false , true ) ) { log . debug ( "Sending chunk size: {}" , chunkSize ) ; ChunkSize chunkSizeMsg = new ChunkSize ( chunkSize ) ; conn . getChannel ( ( byte ) 2 ) . write ( chunkSizeMsg ) ; } }
Send the chunk size
6,508
private void closeChannels ( ) { conn . closeChannel ( video . getId ( ) ) ; conn . closeChannel ( audio . getId ( ) ) ; conn . closeChannel ( data . getId ( ) ) ; }
Close all the channels
6,509
public static void copy ( HttpServletRequest req , OutputStream output ) throws IOException { InputStream input = req . getInputStream ( ) ; int availableBytes = req . getContentLength ( ) ; log . debug ( "copy - available: {}" , availableBytes ) ; if ( availableBytes > 0 ) { byte [ ] buf = new byte [ availableBytes ] ; int bytesRead = input . read ( buf ) ; while ( bytesRead != - 1 ) { output . write ( buf , 0 , bytesRead ) ; bytesRead = input . read ( buf ) ; log . trace ( "Bytes read: {}" , bytesRead ) ; } output . flush ( ) ; } else { log . debug ( "Nothing to available to copy" ) ; } }
Copies information from the http request to the output stream using the specified content length .
6,510
public static List < String > getRemoteAddresses ( HttpServletRequest request ) { List < String > addresses = new ArrayList < String > ( ) ; addresses . add ( request . getRemoteHost ( ) ) ; if ( ! request . getRemoteAddr ( ) . equals ( request . getRemoteHost ( ) ) ) { addresses . add ( request . getRemoteAddr ( ) ) ; } final String forwardedFor = request . getHeader ( "X-Forwarded-For" ) ; if ( forwardedFor != null ) { final String [ ] parts = forwardedFor . split ( "," ) ; for ( String part : parts ) { addresses . add ( part ) ; } } final String httpVia = request . getHeader ( "Via" ) ; if ( httpVia != null ) { final String [ ] parts = httpVia . split ( "," ) ; for ( String part : parts ) { addresses . add ( part ) ; } } return Collections . unmodifiableList ( addresses ) ; }
Return all remote addresses that were involved in the passed request .
6,511
public Invoke duplicate ( ) throws IOException , ClassNotFoundException { Invoke result = new Invoke ( ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( baos ) ; writeExternal ( oos ) ; oos . close ( ) ; byte [ ] buf = baos . toByteArray ( ) ; baos . close ( ) ; ByteArrayInputStream bais = new ByteArrayInputStream ( buf ) ; ObjectInputStream ois = new ObjectInputStream ( bais ) ; result . readExternal ( ois ) ; ois . close ( ) ; bais . close ( ) ; return result ; }
Duplicate this Invoke message to future injection . Serialize to memory and deserialize safe way .
6,512
public void addTask ( ReceivedMessageTask task ) { tasks . add ( task ) ; Packet packet = task . getPacket ( ) ; if ( packet . getExpirationTime ( ) > 0L ) { task . runDeadlockFuture ( new DeadlockGuard ( task ) ) ; } if ( listener != null ) { listener . onTaskAdded ( this ) ; } }
Adds new task to the end of the queue .
6,513
public void removeTask ( ReceivedMessageTask task ) { if ( tasks . remove ( task ) ) { task . cancelDeadlockFuture ( ) ; if ( listener != null ) { listener . onTaskRemoved ( this ) ; } } }
Removes the specified task from the queue .
6,514
public ReceivedMessageTask getTaskToProcess ( ) { ReceivedMessageTask task = tasks . peek ( ) ; if ( task != null && task . setProcessing ( ) ) { return task ; } return null ; }
Gets first task from queue if it can be processed . If first task is already in process it returns null .
6,515
public static SimplePlayItem build ( String name , long start , long length ) { SimplePlayItem playItem = new SimplePlayItem ( name , start , length ) ; return playItem ; }
Builder for SimplePlayItem
6,516
protected String getHostname ( String url ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "getHostname - url: {}" , url ) ; } String [ ] parts = url . split ( "/" ) ; if ( parts . length == 2 ) { return "" ; } else { String host = parts [ 2 ] ; if ( host . endsWith ( ":1935" ) ) { return host . substring ( 0 , host . length ( ) - 5 ) ; } return host ; } }
Return hostname for URL .
6,517
protected void handlePendingCallResult ( RTMPConnection conn , Invoke invoke ) { final IServiceCall call = invoke . getCall ( ) ; final IPendingServiceCall pendingCall = conn . retrievePendingCall ( invoke . getTransactionId ( ) ) ; if ( pendingCall != null ) { Object [ ] args = call . getArguments ( ) ; if ( args != null && args . length > 0 ) { pendingCall . setResult ( args [ 0 ] ) ; } Set < IPendingServiceCallback > callbacks = pendingCall . getCallbacks ( ) ; if ( ! callbacks . isEmpty ( ) ) { HashSet < IPendingServiceCallback > tmp = new HashSet < > ( ) ; tmp . addAll ( callbacks ) ; for ( IPendingServiceCallback callback : tmp ) { try { callback . resultReceived ( pendingCall ) ; } catch ( Exception e ) { log . error ( "Error while executing callback {}" , callback , e ) ; } } } } }
Handler for pending call result . Dispatches results to all pending call handlers .
6,518
protected void onStreamBytesRead ( RTMPConnection conn , Channel channel , Header source , BytesRead streamBytesRead ) { conn . receivedBytesRead ( streamBytesRead . getBytesRead ( ) ) ; }
Stream bytes read event handler .
6,519
public void close ( ) { if ( closed . compareAndSet ( false , true ) ) { if ( livePipe != null ) { livePipe . unsubscribe ( ( IProvider ) this ) ; } if ( recordingListener != null ) { sendRecordStopNotify ( ) ; notifyRecordingStop ( ) ; recordingListener . get ( ) . stop ( ) ; } sendPublishStopNotify ( ) ; if ( connMsgOut != null ) { connMsgOut . unsubscribe ( this ) ; } notifyBroadcastClose ( ) ; if ( recordingListener != null ) { recordingListener . clear ( ) ; } if ( ! listeners . isEmpty ( ) ) { listeners . clear ( ) ; } unregisterJMX ( ) ; setState ( StreamState . CLOSED ) ; } }
Closes stream unsubscribes provides sends stoppage notifications and broadcast close notification .
6,520
public void setPublishedName ( String name ) { if ( StringUtils . isNotEmpty ( name ) && ! "false" . equals ( name ) ) { this . publishedName = name ; registerJMX ( ) ; } }
Setter for stream published name
6,521
private void notifyBroadcastClose ( ) { final IStreamAwareScopeHandler handler = getStreamAwareHandler ( ) ; if ( handler != null ) { try { handler . streamBroadcastClose ( this ) ; } catch ( Throwable t ) { log . error ( "Error in notifyBroadcastClose" , t ) ; } } }
Notifies handler on stream broadcast close
6,522
private void notifyRecordingStop ( ) { IStreamAwareScopeHandler handler = getStreamAwareHandler ( ) ; if ( handler != null ) { try { handler . streamRecordStop ( this ) ; } catch ( Throwable t ) { log . error ( "Error in notifyRecordingStop" , t ) ; } } }
Notifies handler on stream recording stop
6,523
private void notifyBroadcastStart ( ) { IStreamAwareScopeHandler handler = getStreamAwareHandler ( ) ; if ( handler != null ) { try { handler . streamBroadcastStart ( this ) ; } catch ( Throwable t ) { log . error ( "Error in notifyBroadcastStart" , t ) ; } } IoBuffer buf = IoBuffer . allocate ( 256 ) ; buf . setAutoExpand ( true ) ; Output out = new Output ( buf ) ; out . writeString ( "onMetaData" ) ; Map < Object , Object > params = new HashMap < > ( ) ; Calendar cal = GregorianCalendar . getInstance ( ) ; cal . setTimeInMillis ( creationTime ) ; params . put ( "creationdate" , ZonedDateTime . ofInstant ( cal . toInstant ( ) , ZoneId . of ( "UTC" ) ) . format ( DateTimeFormatter . ISO_INSTANT ) ) ; cal . setTimeInMillis ( startTime ) ; params . put ( "startdate" , ZonedDateTime . ofInstant ( cal . toInstant ( ) , ZoneId . of ( "UTC" ) ) . format ( DateTimeFormatter . ISO_INSTANT ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Params: {}" , params ) ; } out . writeMap ( params ) ; buf . flip ( ) ; Notify notify = new Notify ( buf ) ; notify . setAction ( "onMetaData" ) ; notify . setHeader ( new Header ( ) ) ; notify . getHeader ( ) . setDataType ( Notify . TYPE_STREAM_METADATA ) ; notify . getHeader ( ) . setStreamId ( 0 ) ; notify . setTimestamp ( 0 ) ; dispatchEvent ( notify ) ; }
Notifies handler on stream broadcast start
6,524
private void notifyChunkSize ( ) { if ( chunkSize > 0 && livePipe != null ) { OOBControlMessage setChunkSize = new OOBControlMessage ( ) ; setChunkSize . setTarget ( "ConnectionConsumer" ) ; setChunkSize . setServiceName ( "chunkSize" ) ; if ( setChunkSize . getServiceParamMap ( ) == null ) { setChunkSize . setServiceParamMap ( new HashMap < String , Object > ( ) ) ; } setChunkSize . getServiceParamMap ( ) . put ( "chunkSize" , chunkSize ) ; livePipe . sendOOBControlMessage ( getProvider ( ) , setChunkSize ) ; } }
Send OOB control message with chunk size
6,525
public void onOOBControlMessage ( IMessageComponent source , IPipe pipe , OOBControlMessage oobCtrlMsg ) { String target = oobCtrlMsg . getTarget ( ) ; if ( "ClientBroadcastStream" . equals ( target ) ) { String serviceName = oobCtrlMsg . getServiceName ( ) ; if ( "chunkSize" . equals ( serviceName ) ) { chunkSize = ( Integer ) oobCtrlMsg . getServiceParamMap ( ) . get ( "chunkSize" ) ; notifyChunkSize ( ) ; } else { log . debug ( "Unhandled OOB control message for service: {}" , serviceName ) ; } } else { log . debug ( "Unhandled OOB control message to target: {}" , target ) ; } }
Out - of - band control message handler
6,526
public void saveAs ( String name , boolean isAppend ) throws IOException { IStreamCapableConnection conn = getConnection ( ) ; if ( conn == null ) { throw new IOException ( "Stream is no longer connected" ) ; } if ( recordingListener == null ) { IRecordingListener listener = new RecordingListener ( ) ; if ( listener . init ( conn , name , isAppend ) ) { IStreamCodecInfo codecInfo = getCodecInfo ( ) ; if ( codecInfo instanceof StreamCodecInfo ) { StreamCodecInfo info = ( StreamCodecInfo ) codecInfo ; IVideoStreamCodec videoCodec = info . getVideoCodec ( ) ; if ( videoCodec != null ) { IoBuffer config = videoCodec . getDecoderConfiguration ( ) ; if ( config != null ) { VideoData videoConf = new VideoData ( config . asReadOnlyBuffer ( ) ) ; try { listener . getFileConsumer ( ) . setVideoDecoderConfiguration ( videoConf ) ; } finally { videoConf . release ( ) ; } } } else { log . debug ( "Could not initialize stream output, videoCodec is null." ) ; } IAudioStreamCodec audioCodec = info . getAudioCodec ( ) ; if ( audioCodec != null ) { IoBuffer config = audioCodec . getDecoderConfiguration ( ) ; if ( config != null ) { AudioData audioConf = new AudioData ( config . asReadOnlyBuffer ( ) ) ; try { listener . getFileConsumer ( ) . setAudioDecoderConfiguration ( audioConf ) ; } finally { audioConf . release ( ) ; } } } else { log . debug ( "No decoder configuration available, audioCodec is null." ) ; } } recordingListener = new WeakReference < IRecordingListener > ( listener ) ; addStreamListener ( listener ) ; listener . start ( ) ; } else { log . warn ( "Recording listener failed to initialize for stream: {}" , name ) ; } } else { log . debug ( "Recording listener already exists for stream: {} auto record enabled: {}" , name , automaticRecording ) ; } }
Save broadcasted stream .
6,527
private void sendPublishStartNotify ( ) { Status publishStatus = new Status ( StatusCodes . NS_PUBLISH_START ) ; publishStatus . setClientid ( getStreamId ( ) ) ; publishStatus . setDetails ( getPublishedName ( ) ) ; StatusMessage startMsg = new StatusMessage ( ) ; startMsg . setBody ( publishStatus ) ; pushMessage ( startMsg ) ; setState ( StreamState . PUBLISHING ) ; }
Sends publish start notifications
6,528
private void sendPublishStopNotify ( ) { Status stopStatus = new Status ( StatusCodes . NS_UNPUBLISHED_SUCCESS ) ; stopStatus . setClientid ( getStreamId ( ) ) ; stopStatus . setDetails ( getPublishedName ( ) ) ; StatusMessage stopMsg = new StatusMessage ( ) ; stopMsg . setBody ( stopStatus ) ; pushMessage ( stopMsg ) ; setState ( StreamState . STOPPED ) ; }
Sends publish stop notifications
6,529
private void sendRecordFailedNotify ( String reason ) { Status failedStatus = new Status ( StatusCodes . NS_RECORD_FAILED ) ; failedStatus . setLevel ( Status . ERROR ) ; failedStatus . setClientid ( getStreamId ( ) ) ; failedStatus . setDetails ( getPublishedName ( ) ) ; failedStatus . setDesciption ( reason ) ; StatusMessage failedMsg = new StatusMessage ( ) ; failedMsg . setBody ( failedStatus ) ; pushMessage ( failedMsg ) ; }
Sends record failed notifications
6,530
private void sendRecordStartNotify ( ) { Status recordStatus = new Status ( StatusCodes . NS_RECORD_START ) ; recordStatus . setClientid ( getStreamId ( ) ) ; recordStatus . setDetails ( getPublishedName ( ) ) ; StatusMessage startMsg = new StatusMessage ( ) ; startMsg . setBody ( recordStatus ) ; pushMessage ( startMsg ) ; }
Sends record start notifications
6,531
private void sendRecordStopNotify ( ) { Status stopStatus = new Status ( StatusCodes . NS_RECORD_STOP ) ; stopStatus . setClientid ( getStreamId ( ) ) ; stopStatus . setDetails ( getPublishedName ( ) ) ; StatusMessage stopMsg = new StatusMessage ( ) ; stopMsg . setBody ( stopStatus ) ; pushMessage ( stopMsg ) ; }
Sends record stop notifications
6,532
protected void pushMessage ( StatusMessage msg ) { if ( connMsgOut != null ) { try { connMsgOut . pushMessage ( msg ) ; } catch ( IOException err ) { log . error ( "Error while pushing message: {}" , msg , err ) ; } } else { log . warn ( "Consumer message output is null" ) ; } }
Pushes a message out to a consumer .
6,533
public void start ( ) { checkVideoCodec = true ; checkAudioCodec = true ; firstPacketTime = - 1 ; latestTimeStamp = - 1 ; bytesReceived = 0 ; IConsumerService consumerManager = ( IConsumerService ) getScope ( ) . getContext ( ) . getBean ( IConsumerService . KEY ) ; connMsgOut = consumerManager . getConsumerOutput ( this ) ; if ( connMsgOut != null && connMsgOut . subscribe ( this , null ) ) { startTime = System . currentTimeMillis ( ) ; } else { log . warn ( "Subscribe failed" ) ; } setState ( StreamState . STARTED ) ; }
Starts stream creates pipes connects
6,534
public void stopRecording ( ) { IRecordingListener listener = null ; if ( recordingListener != null && ( listener = recordingListener . get ( ) ) . isRecording ( ) ) { sendRecordStopNotify ( ) ; notifyRecordingStop ( ) ; removeStreamListener ( listener ) ; listener . stop ( ) ; recordingListener . clear ( ) ; recordingListener = null ; } }
Stops any currently active recording .
6,535
private void processQueue ( ) { CachedEvent cachedEvent ; try { IRTMPEvent event = null ; RTMPMessage message = null ; cachedEvent = queue . poll ( ) ; if ( cachedEvent != null ) { final byte dataType = cachedEvent . getDataType ( ) ; IoBuffer buffer = cachedEvent . getData ( ) ; int bufferLimit = buffer . limit ( ) ; if ( bufferLimit > 0 ) { switch ( dataType ) { case Constants . TYPE_AGGREGATE : event = new Aggregate ( buffer ) ; event . setTimestamp ( cachedEvent . getTimestamp ( ) ) ; message = RTMPMessage . build ( event ) ; break ; case Constants . TYPE_AUDIO_DATA : event = new AudioData ( buffer ) ; event . setTimestamp ( cachedEvent . getTimestamp ( ) ) ; message = RTMPMessage . build ( event ) ; break ; case Constants . TYPE_VIDEO_DATA : event = new VideoData ( buffer ) ; event . setTimestamp ( cachedEvent . getTimestamp ( ) ) ; message = RTMPMessage . build ( event ) ; break ; default : event = new Notify ( buffer ) ; event . setTimestamp ( cachedEvent . getTimestamp ( ) ) ; message = RTMPMessage . build ( event ) ; break ; } recordingConsumer . pushMessage ( null , message ) ; } else if ( bufferLimit == 0 && dataType == Constants . TYPE_AUDIO_DATA ) { log . debug ( "Stream data size was 0, sending empty audio message" ) ; event = new AudioData ( IoBuffer . allocate ( 0 ) ) ; event . setTimestamp ( cachedEvent . getTimestamp ( ) ) ; message = RTMPMessage . build ( event ) ; recordingConsumer . pushMessage ( null , message ) ; } else { log . debug ( "Stream data size was 0, recording pipe will not be notified" ) ; } } } catch ( Exception e ) { log . warn ( "Exception while pushing to consumer" , e ) ; } }
Process the queued items .
6,536
protected String getKey ( String hostName , String contextPath ) { return String . format ( "%s/%s" , ( hostName == null ? EMPTY : hostName ) , ( contextPath == null ? EMPTY : contextPath ) ) ; }
Return scope key . Scope key consists of host name concatenated with context path by slash symbol
6,537
public IGlobalScope lookupGlobal ( String hostName , String contextPath ) { log . trace ( "{}" , this ) ; log . debug ( "Lookup global scope - host name: {} context path: {}" , hostName , contextPath ) ; String key = getKey ( hostName , contextPath ) ; while ( contextPath . indexOf ( SLASH ) != - 1 ) { key = getKey ( hostName , contextPath ) ; log . trace ( "Check: {}" , key ) ; String globalName = mapping . get ( key ) ; if ( globalName != null ) { return getGlobal ( globalName ) ; } final int slashIndex = contextPath . lastIndexOf ( SLASH ) ; contextPath = contextPath . substring ( 0 , slashIndex ) ; } key = getKey ( hostName , contextPath ) ; log . trace ( "Check host and path: {}" , key ) ; String globalName = mapping . get ( key ) ; if ( globalName != null ) { return getGlobal ( globalName ) ; } key = getKey ( EMPTY , contextPath ) ; log . trace ( "Check wildcard host with path: {}" , key ) ; globalName = mapping . get ( key ) ; if ( globalName != null ) { return getGlobal ( globalName ) ; } key = getKey ( hostName , EMPTY ) ; log . trace ( "Check host with no path: {}" , key ) ; globalName = mapping . get ( key ) ; if ( globalName != null ) { return getGlobal ( globalName ) ; } key = getKey ( EMPTY , EMPTY ) ; log . trace ( "Check default host, default path: {}" , key ) ; return getGlobal ( mapping . get ( key ) ) ; }
Does global scope lookup for host name and context path
6,538
public IGlobalScope getGlobal ( String name ) { if ( name == null ) { return null ; } return globals . get ( name ) ; }
Return global scope by name
6,539
public void registerGlobal ( IGlobalScope scope ) { log . trace ( "Registering global scope: {}" , scope . getName ( ) , scope ) ; globals . put ( scope . getName ( ) , scope ) ; }
Register global scope
6,540
public boolean removeMapping ( String hostName , String contextPath ) { log . info ( "Remove mapping host: {} context: {}" , hostName , contextPath ) ; final String key = getKey ( hostName , contextPath ) ; log . debug ( "Remove mapping: {}" , key ) ; return ( mapping . remove ( key ) != null ) ; }
Remove mapping with given key
6,541
public void connect ( IConnection conn ) { if ( conn instanceof RTMPConnection ) { if ( ! isConnected ( ) ) { source = conn ; SharedObjectMessage msg = new SharedObjectMessage ( name , 0 , isPersistent ( ) ) ; msg . addEvent ( new SharedObjectEvent ( Type . SERVER_CONNECT , null , null ) ) ; Channel c = ( ( RTMPConnection ) conn ) . getChannel ( 3 ) ; c . write ( msg ) ; } else { throw new UnsupportedOperationException ( "Already connected" ) ; } } else { throw new UnsupportedOperationException ( "Only RTMP connections are supported" ) ; } }
Connect the shared object using the passed connection .
6,542
protected void notifyUpdate ( String key , Object value ) { for ( ISharedObjectListener listener : listeners ) { listener . onSharedObjectUpdate ( this , key , value ) ; } }
Notify listeners on update
6,543
protected void notifyUpdate ( String key , Map < String , Object > value ) { if ( value . size ( ) == 1 ) { Map . Entry < String , Object > entry = value . entrySet ( ) . iterator ( ) . next ( ) ; notifyUpdate ( entry . getKey ( ) , entry . getValue ( ) ) ; return ; } for ( ISharedObjectListener listener : listeners ) { listener . onSharedObjectUpdate ( this , key , value ) ; } }
Notify listeners on map attribute update
6,544
protected void notifySendMessage ( String method , List < ? > params ) { for ( ISharedObjectListener listener : listeners ) { listener . onSharedObjectSend ( this , method , params ) ; } }
Broadcast send event to listeners
6,545
private Object getServiceHandler ( IScope scope , String serviceName ) { Object service = scope . getHandler ( ) ; if ( serviceName == null || serviceName . equals ( "" ) ) { log . trace ( "No service requested, return application scope handler: {}" , service ) ; return service ; } for ( IServiceResolver resolver : serviceResolvers ) { service = resolver . resolveService ( scope , serviceName ) ; if ( service != null ) { return service ; } } return null ; }
Lookup a handler for the passed service name in the given scope .
6,546
private void sendSOCreationFailed ( RTMPConnection conn , SharedObjectMessage message ) { log . debug ( "sendSOCreationFailed - message: {} conn: {}" , message , conn ) ; message . reset ( ) ; message . addEvent ( new SharedObjectEvent ( ISharedObjectEvent . Type . CLIENT_STATUS , "error" , SO_CREATION_FAILED ) ) ; if ( conn . isChannelUsed ( 3 ) ) { conn . getChannel ( 3 ) . write ( message ) ; } else { log . warn ( "Channel is not in-use and cannot handle SO event: {}" , message , new Exception ( "SO event handling failure" ) ) ; conn . getChannel ( 3 ) . write ( message ) ; } }
Create and send SO message stating that a SO could not be created .
6,547
public void setResult ( Object result ) { if ( resultSent ) { throw new RuntimeException ( "You can only set the result once." ) ; } this . resultSent = true ; Channel channel = this . channel . get ( ) ; if ( channel == null ) { log . warn ( "The client is no longer connected." ) ; return ; } call . setResult ( result ) ; Invoke reply = new Invoke ( ) ; reply . setCall ( call ) ; reply . setTransactionId ( transactionId ) ; channel . write ( reply ) ; channel . getConnection ( ) . unregisterDeferredResult ( this ) ; }
Set the result of a method call and send to the caller .
6,548
public void pushMessage ( IMessage message ) throws IOException { if ( log . isDebugEnabled ( ) ) { log . debug ( "pushMessage: {} to {} consumers" , message , consumers . size ( ) ) ; } for ( IConsumer consumer : consumers ) { try { ( ( IPushableConsumer ) consumer ) . pushMessage ( this , message ) ; } catch ( Throwable t ) { if ( t instanceof IOException ) { throw ( IOException ) t ; } log . error ( "Exception pushing message to consumer" , t ) ; } } }
Pushes a message out to all the PushableConsumers .
6,549
public boolean subscribe ( IConsumer consumer , Map < String , Object > paramMap ) { boolean success = consumers . addIfAbsent ( consumer ) ; if ( success && consumer instanceof IPipeConnectionListener ) { listeners . addIfAbsent ( ( IPipeConnectionListener ) consumer ) ; } return success ; }
Connect consumer to this pipe . Doesn t allow to connect one consumer twice . Does register event listeners if instance of IPipeConnectionListener is given .
6,550
public boolean subscribe ( IProvider provider , Map < String , Object > paramMap ) { boolean success = providers . addIfAbsent ( provider ) ; if ( success && provider instanceof IPipeConnectionListener ) { listeners . addIfAbsent ( ( IPipeConnectionListener ) provider ) ; } return success ; }
Connect provider to this pipe . Doesn t allow to connect one provider twice . Does register event listeners if instance of IPipeConnectionListener is given .
6,551
@ SuppressWarnings ( "unlikely-arg-type" ) public boolean unsubscribe ( IProvider provider ) { if ( providers . remove ( provider ) ) { fireProviderConnectionEvent ( provider , PipeConnectionEvent . EventType . PROVIDER_DISCONNECT , null ) ; listeners . remove ( provider ) ; return true ; } return false ; }
Disconnects provider from this pipe . Fires pipe connection event .
6,552
@ SuppressWarnings ( "unlikely-arg-type" ) public boolean unsubscribe ( IConsumer consumer ) { if ( consumers . remove ( consumer ) ) { fireConsumerConnectionEvent ( consumer , PipeConnectionEvent . EventType . CONSUMER_DISCONNECT , null ) ; listeners . remove ( consumer ) ; return true ; } return false ; }
Disconnects consumer from this pipe . Fires pipe connection event .
6,553
protected void fireConsumerConnectionEvent ( IConsumer consumer , PipeConnectionEvent . EventType type , Map < String , Object > paramMap ) { firePipeConnectionEvent ( PipeConnectionEvent . build ( this , type , consumer , paramMap ) ) ; }
Broadcast consumer connection event
6,554
protected void fireProviderConnectionEvent ( IProvider provider , PipeConnectionEvent . EventType type , Map < String , Object > paramMap ) { firePipeConnectionEvent ( PipeConnectionEvent . build ( this , type , provider , paramMap ) ) ; }
Broadcast provider connection event
6,555
protected void firePipeConnectionEvent ( PipeConnectionEvent event ) { for ( IPipeConnectionListener element : listeners ) { try { element . onPipeConnectionEvent ( event ) ; } catch ( Throwable t ) { log . error ( "Exception when handling pipe connection event" , t ) ; } } if ( taskExecutor == null ) { taskExecutor = Executors . newCachedThreadPool ( new CustomizableThreadFactory ( "Pipe-" ) ) ; } for ( Runnable task : event . getTaskList ( ) ) { try { taskExecutor . execute ( task ) ; } catch ( Throwable t ) { log . warn ( "Exception executing pipe task {}" , t ) ; } } event . getTaskList ( ) . clear ( ) ; }
Fire any pipe connection event and run all it s tasks
6,556
public void close ( ) { if ( consumers != null ) { consumers . clear ( ) ; consumers = null ; } if ( providers != null ) { providers . clear ( ) ; providers = null ; } if ( listeners != null ) { listeners . clear ( ) ; listeners = null ; } }
Close the pipe
6,557
public static IAudioStreamCodec getAudioCodec ( IoBuffer data ) { IAudioStreamCodec result = null ; try { int codecId = ( data . get ( ) & 0xf0 ) >> 4 ; switch ( codecId ) { case 10 : result = ( IAudioStreamCodec ) Class . forName ( "org.red5.codec.AACAudio" ) . newInstance ( ) ; break ; case 11 : result = ( IAudioStreamCodec ) Class . forName ( "org.red5.codec.SpeexAudio" ) . newInstance ( ) ; break ; case 2 : case 14 : result = ( IAudioStreamCodec ) Class . forName ( "org.red5.codec.MP3Audio" ) . newInstance ( ) ; break ; } data . rewind ( ) ; } catch ( Exception ex ) { log . error ( "Error creating codec instance" , ex ) ; } if ( result == null ) { for ( IAudioStreamCodec storedCodec : codecs ) { IAudioStreamCodec codec ; try { codec = storedCodec . getClass ( ) . newInstance ( ) ; } catch ( Exception e ) { log . error ( "Could not create audio codec instance" , e ) ; continue ; } if ( codec . canHandleData ( data ) ) { result = codec ; break ; } } } return result ; }
Create and return new audio codec applicable for byte buffer data
6,558
public static void setConnectionLocal ( IConnection connection ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Set connection: {} with thread: {}" , ( connection != null ? connection . getSessionId ( ) : null ) , Thread . currentThread ( ) . getName ( ) ) ; try { StackTraceElement [ ] stackTraceElements = Thread . currentThread ( ) . getStackTrace ( ) ; StackTraceElement stackTraceElement = stackTraceElements [ 2 ] ; log . debug ( "Caller: {}.{} #{}" , stackTraceElement . getClassName ( ) , stackTraceElement . getMethodName ( ) , stackTraceElement . getLineNumber ( ) ) ; } catch ( Exception e ) { } } if ( connection != null ) { connThreadLocal . set ( new WeakReference < IConnection > ( connection ) ) ; IScope scope = connection . getScope ( ) ; if ( scope != null ) { Thread . currentThread ( ) . setContextClassLoader ( scope . getClassLoader ( ) ) ; } } else { connThreadLocal . remove ( ) ; } }
Setter for connection
6,559
public static IConnection getConnectionLocal ( ) { WeakReference < IConnection > ref = connThreadLocal . get ( ) ; if ( ref != null ) { IConnection connection = ref . get ( ) ; log . debug ( "Get connection: {} on thread: {}" , ( connection != null ? connection . getSessionId ( ) : null ) , Thread . currentThread ( ) . getName ( ) ) ; return connection ; } else { return null ; } }
Get the connection associated with the current thread . This method allows you to get connection object local to current thread . When you need to get a connection associated with event handler and so forth this method provides you with it .
6,560
protected String getObjectName ( String id ) { String result = id . substring ( id . lastIndexOf ( '/' ) + 1 ) ; if ( result . equals ( PERSISTENCE_NO_NAME ) ) { result = null ; } return result ; }
Get resource name from path . The format of the object id is
6,561
protected String getObjectPath ( String id , String name ) { id = id . substring ( id . indexOf ( '/' ) + 1 ) ; if ( id . charAt ( 0 ) == '/' ) { id = id . substring ( 1 ) ; } if ( id . lastIndexOf ( name ) <= 0 ) { return id ; } return id . substring ( 0 , id . lastIndexOf ( name ) - 1 ) ; }
Get object path for given id and name . The format of the object id is
6,562
protected String getObjectId ( IPersistable object ) { String result = object . getType ( ) ; if ( object . getPath ( ) . charAt ( 0 ) != '/' ) { result += '/' ; } result += object . getPath ( ) ; if ( ! result . endsWith ( "/" ) ) { result += '/' ; } String name = object . getName ( ) ; if ( name == null ) { name = PERSISTENCE_NO_NAME ; } if ( name . charAt ( 0 ) == '/' ) { name = name . substring ( 1 ) ; } return result + name ; }
Get object id
6,563
public boolean connect ( IScope newScope , Object [ ] params ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Connect Params: {}" , params ) ; if ( params != null ) { for ( Object e : params ) { log . debug ( "Param: {}" , e ) ; } } } scope = ( Scope ) newScope ; return scope . connect ( this , params ) ; }
Connect to another scope on server with given parameters
6,564
public void unregisterBasicScope ( IBasicScope basicScope ) { if ( basicScope instanceof IBroadcastScope || basicScope instanceof SharedObjectScope ) { basicScopes . remove ( basicScope ) ; basicScope . removeEventListener ( this ) ; } }
Unregister basic scope
6,565
public boolean isValid ( ) { return ( type != null && ! type . equals ( ScopeType . UNDEFINED ) && ( name != null && ! ( "" ) . equals ( name ) ) ) ; }
Validates a scope based on its name and type
6,566
public boolean addEventListener ( IEventListener listener ) { log . debug ( "addEventListener - scope: {} {}" , getName ( ) , listener ) ; return listeners . add ( listener ) ; }
Add event listener to list of notified objects
6,567
public boolean removeEventListener ( IEventListener listener ) { log . debug ( "removeEventListener - scope: {} {}" , getName ( ) , listener ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Listeners - check #1: {}" , listeners ) ; } boolean removed = listeners . remove ( listener ) ; if ( ! keepOnDisconnect ) { if ( removed && keepAliveJobName == null ) { if ( ScopeUtils . isRoom ( this ) && listeners . isEmpty ( ) ) { ISchedulingService schedulingService = ( ISchedulingService ) parent . getContext ( ) . getBean ( ISchedulingService . BEAN_NAME ) ; keepAliveJobName = schedulingService . addScheduledOnceJob ( ( keepDelay > 0 ? keepDelay * 1000 : 100 ) , new KeepAliveJob ( this ) ) ; } } } else { log . trace ( "Scope: {} is exempt from removal when empty" , getName ( ) ) ; } if ( log . isTraceEnabled ( ) ) { log . trace ( "Listeners - check #2: {}" , listeners ) ; } return removed ; }
Remove event listener from list of listeners
6,568
public void checkBandwidth ( Object o ) { IClient client = Red5 . getConnectionLocal ( ) . getClient ( ) ; if ( client != null ) { client . checkBandwidth ( ) ; } }
Calls the checkBandwidth method on the current client .
6,569
public Map < String , Object > checkBandwidthUp ( Object [ ] params ) { IClient client = Red5 . getConnectionLocal ( ) . getClient ( ) ; if ( client != null ) { return client . checkBandwidthUp ( params ) ; } return null ; }
Calls the checkBandwidthUp method on the current client .
6,570
public boolean createChildScope ( String name ) { if ( ! scope . hasChildScope ( name ) ) { return scope . createChildScope ( name ) ; } return false ; }
Creates child scope
6,571
public Notify duplicate ( ) throws IOException , ClassNotFoundException { Notify result = new Notify ( ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( baos ) ; writeExternal ( oos ) ; oos . close ( ) ; byte [ ] buf = baos . toByteArray ( ) ; baos . close ( ) ; ByteArrayInputStream bais = new ByteArrayInputStream ( buf ) ; ObjectInputStream ois = new ObjectInputStream ( bais ) ; result . readExternal ( ois ) ; ois . close ( ) ; bais . close ( ) ; result . setAction ( getAction ( ) ) ; result . setSourceType ( sourceType ) ; result . setSource ( source ) ; result . setTimestamp ( timestamp ) ; return result ; }
Duplicate this Notify message to future injection Serialize to memory and deserialize safe way .
6,572
private final void connectToProvider ( String itemName ) { log . debug ( "Attempting connection to {}" , itemName ) ; IMessageInput in = msgInReference . get ( ) ; if ( in == null ) { in = providerService . getLiveProviderInput ( subscriberStream . getScope ( ) , itemName , true ) ; msgInReference . set ( in ) ; } if ( in != null ) { log . debug ( "Provider: {}" , msgInReference . get ( ) ) ; if ( in . subscribe ( this , null ) ) { log . debug ( "Subscribed to {} provider" , itemName ) ; try { playLive ( ) ; } catch ( IOException e ) { log . warn ( "Could not play live stream: {}" , itemName , e ) ; } } else { log . warn ( "Subscribe to {} provider failed" , itemName ) ; } } else { log . warn ( "Provider was not found for {}" , itemName ) ; StreamService . sendNetStreamStatus ( subscriberStream . getConnection ( ) , StatusCodes . NS_PLAY_STREAMNOTFOUND , "Stream was not found" , itemName , Status . ERROR , streamId ) ; } }
Connects to the data provider .
6,573
public void pause ( int position ) throws IllegalStateException { switch ( subscriberStream . getState ( ) ) { case PLAYING : case STOPPED : subscriberStream . setState ( StreamState . PAUSED ) ; clearWaitJobs ( ) ; sendPauseStatus ( currentItem . get ( ) ) ; sendClearPing ( ) ; subscriberStream . onChange ( StreamState . PAUSED , currentItem . get ( ) , position ) ; break ; default : throw new IllegalStateException ( "Cannot pause in current state" ) ; } }
Pause at position
6,574
public void seek ( int position ) throws IllegalStateException , OperationNotSupportedException { pendingOperations . add ( new SeekRunnable ( position ) ) ; cancelDeferredStop ( ) ; ensurePullAndPushRunning ( ) ; }
Seek to a given position
6,575
private boolean okayToSendMessage ( IRTMPEvent message ) { if ( message instanceof IStreamData ) { final long now = System . currentTimeMillis ( ) ; if ( isClientBufferFull ( now ) ) { return false ; } long pending = pendingMessages ( ) ; if ( bufferCheckInterval > 0 && now >= nextCheckBufferUnderrun ) { if ( pending > underrunTrigger ) { sendInsufficientBandwidthStatus ( currentItem . get ( ) ) ; } nextCheckBufferUnderrun = now + bufferCheckInterval ; } if ( pending > underrunTrigger ) { return false ; } return true ; } else { String itemName = "Undefined" ; if ( currentItem . get ( ) != null ) { itemName = currentItem . get ( ) . getName ( ) ; } Object [ ] errorItems = new Object [ ] { message . getClass ( ) , message . getDataType ( ) , itemName } ; throw new RuntimeException ( String . format ( "Expected IStreamData but got %s (type %s) for %s" , errorItems ) ) ; } }
Check if it s okay to send the client more data . This takes the configured bandwidth as well as the requested client buffer into account .
6,576
private boolean isClientBufferFull ( final long now ) { if ( lastMessageTs > 0 ) { final long delta = now - playbackStart ; final long buffer = subscriberStream . getClientBufferDuration ( ) ; final long buffered = lastMessageTs - delta ; log . trace ( "isClientBufferFull: timestamp {} delta {} buffered {} buffer duration {}" , new Object [ ] { lastMessageTs , delta , buffered , buffer } ) ; if ( buffer > 0 && buffered > ( buffer * 2 ) ) { return true ; } } return false ; }
Estimate client buffer fill .
6,577
private void ensurePullAndPushRunning ( ) { log . trace ( "State should be PLAYING to running this task: {}" , subscriberStream . getState ( ) ) ; if ( pullMode && pullAndPush == null && subscriberStream . getState ( ) == StreamState . PLAYING ) { pullAndPush = subscriberStream . scheduleWithFixedDelay ( new PullAndPushRunnable ( ) , 10 ) ; } }
Make sure the pull and push processing is running .
6,578
private void clearWaitJobs ( ) { log . debug ( "Clear wait jobs" ) ; if ( pullAndPush != null ) { subscriberStream . cancelJob ( pullAndPush ) ; releasePendingMessage ( ) ; pullAndPush = null ; } if ( waitLiveJob != null ) { schedulingService . removeScheduledJob ( waitLiveJob ) ; waitLiveJob = null ; } }
Clear all scheduled waiting jobs
6,579
private void doPushMessage ( Status status ) { StatusMessage message = new StatusMessage ( ) ; message . setBody ( status ) ; doPushMessage ( message ) ; }
Sends a status message .
6,580
private void doPushMessage ( AbstractMessage message ) { if ( log . isTraceEnabled ( ) ) { String msgType = message . getMessageType ( ) ; log . trace ( "doPushMessage: {}" , msgType ) ; } IMessageOutput out = msgOutReference . get ( ) ; if ( out != null ) { try { out . pushMessage ( message ) ; if ( message instanceof RTMPMessage ) { IRTMPEvent body = ( ( RTMPMessage ) message ) . getBody ( ) ; lastMessageTs = body . getTimestamp ( ) ; IoBuffer streamData = null ; if ( body instanceof IStreamData && ( streamData = ( ( IStreamData < ? > ) body ) . getData ( ) ) != null ) { bytesSent . addAndGet ( streamData . limit ( ) ) ; } } } catch ( IOException err ) { log . warn ( "Error while pushing message" , err ) ; } } else { log . warn ( "Push message failed due to null output pipe" ) ; } }
Send message to output stream and handle exceptions .
6,581
private void sendMessage ( RTMPMessage messageIn ) { IRTMPEvent eventIn = messageIn . getBody ( ) ; IRTMPEvent event ; switch ( eventIn . getDataType ( ) ) { case Constants . TYPE_AGGREGATE : event = new Aggregate ( ( ( Aggregate ) eventIn ) . getData ( ) ) ; break ; case Constants . TYPE_AUDIO_DATA : event = new AudioData ( ( ( AudioData ) eventIn ) . getData ( ) ) ; break ; case Constants . TYPE_VIDEO_DATA : event = new VideoData ( ( ( VideoData ) eventIn ) . getData ( ) ) ; break ; default : event = new Notify ( ( ( Notify ) eventIn ) . getData ( ) ) ; break ; } int eventTime = eventIn . getTimestamp ( ) ; event . setSourceType ( eventIn . getSourceType ( ) ) ; RTMPMessage messageOut = RTMPMessage . build ( event , eventTime ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Source type - in: {} out: {}" , eventIn . getSourceType ( ) , messageOut . getBody ( ) . getSourceType ( ) ) ; long delta = System . currentTimeMillis ( ) - playbackStart ; log . trace ( "sendMessage: streamStartTS {}, length {}, streamOffset {}, timestamp {} last timestamp {} delta {} buffered {}" , new Object [ ] { streamStartTS . get ( ) , currentItem . get ( ) . getLength ( ) , streamOffset , eventTime , lastMessageTs , delta , lastMessageTs - delta } ) ; } if ( playDecision == 1 ) { if ( eventTime > 0 && streamStartTS . compareAndSet ( - 1 , eventTime ) ) { log . debug ( "sendMessage: set streamStartTS" ) ; messageOut . getBody ( ) . setTimestamp ( 0 ) ; } long length = currentItem . get ( ) . getLength ( ) ; if ( length >= 0 ) { int duration = eventTime - streamStartTS . get ( ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "sendMessage duration={} length={}" , duration , length ) ; } if ( duration - streamOffset >= length ) { stop ( ) ; return ; } } } else { if ( eventTime > 0 && streamStartTS . compareAndSet ( - 1 , eventTime ) ) { log . debug ( "sendMessage: set streamStartTS" ) ; } int startTs = streamStartTS . get ( ) ; if ( startTs > 0 ) { eventTime -= startTs ; messageOut . getBody ( ) . setTimestamp ( eventTime ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "sendMessage (updated): streamStartTS={}, length={}, streamOffset={}, timestamp={}" , new Object [ ] { startTs , currentItem . get ( ) . getLength ( ) , streamOffset , eventTime } ) ; } } } doPushMessage ( messageOut ) ; }
Send an RTMP message
6,582
private void sendClearPing ( ) { Ping eof = new Ping ( ) ; eof . setEventType ( Ping . STREAM_PLAYBUFFER_CLEAR ) ; eof . setValue2 ( streamId ) ; RTMPMessage eofMsg = RTMPMessage . build ( eof ) ; doPushMessage ( eofMsg ) ; }
Send clear ping . Lets client know that stream has no more data to send .
6,583
private void sendReset ( ) { if ( pullMode ) { Ping recorded = new Ping ( ) ; recorded . setEventType ( Ping . RECORDED_STREAM ) ; recorded . setValue2 ( streamId ) ; RTMPMessage recordedMsg = RTMPMessage . build ( recorded ) ; doPushMessage ( recordedMsg ) ; } Ping begin = new Ping ( ) ; begin . setEventType ( Ping . STREAM_BEGIN ) ; begin . setValue2 ( streamId ) ; RTMPMessage beginMsg = RTMPMessage . build ( begin ) ; doPushMessage ( beginMsg ) ; ResetMessage reset = new ResetMessage ( ) ; doPushMessage ( reset ) ; }
Send reset message
6,584
private void sendResetStatus ( IPlayItem item ) { Status reset = new Status ( StatusCodes . NS_PLAY_RESET ) ; reset . setClientid ( streamId ) ; reset . setDetails ( item . getName ( ) ) ; reset . setDesciption ( String . format ( "Playing and resetting %s." , item . getName ( ) ) ) ; doPushMessage ( reset ) ; }
Send reset status for item
6,585
private void sendStartStatus ( IPlayItem item ) { Status start = new Status ( StatusCodes . NS_PLAY_START ) ; start . setClientid ( streamId ) ; start . setDetails ( item . getName ( ) ) ; start . setDesciption ( String . format ( "Started playing %s." , item . getName ( ) ) ) ; doPushMessage ( start ) ; }
Send playback start status notification
6,586
private void sendStopStatus ( IPlayItem item ) { Status stop = new Status ( StatusCodes . NS_PLAY_STOP ) ; stop . setClientid ( streamId ) ; stop . setDesciption ( String . format ( "Stopped playing %s." , item . getName ( ) ) ) ; stop . setDetails ( item . getName ( ) ) ; doPushMessage ( stop ) ; }
Send playback stoppage status notification
6,587
private void sendOnPlayStatus ( String code , int duration , long bytes ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Sending onPlayStatus - code: {} duration: {} bytes: {}" , code , duration , bytes ) ; } IoBuffer buf = IoBuffer . allocate ( 102 ) ; buf . setAutoExpand ( true ) ; Output out = new Output ( buf ) ; out . writeString ( "onPlayStatus" ) ; ObjectMap < Object , Object > args = new ObjectMap < > ( ) ; args . put ( "code" , code ) ; args . put ( "level" , Status . STATUS ) ; args . put ( "duration" , duration ) ; args . put ( "bytes" , bytes ) ; String name = currentItem . get ( ) . getName ( ) ; if ( StatusCodes . NS_PLAY_TRANSITION_COMPLETE . equals ( code ) ) { args . put ( "clientId" , streamId ) ; args . put ( "details" , name ) ; args . put ( "description" , String . format ( "Transitioned to %s" , name ) ) ; args . put ( "isFastPlay" , false ) ; } out . writeObject ( args ) ; buf . flip ( ) ; Notify event = new Notify ( buf , "onPlayStatus" ) ; if ( lastMessageTs > 0 ) { event . setTimestamp ( lastMessageTs ) ; } else { event . setTimestamp ( 0 ) ; } RTMPMessage msg = RTMPMessage . build ( event ) ; doPushMessage ( msg ) ; }
Sends an onPlayStatus message .
6,588
private void sendCompleteStatus ( ) { int duration = ( lastMessageTs > 0 ) ? Math . max ( 0 , lastMessageTs - streamStartTS . get ( ) ) : 0 ; if ( log . isDebugEnabled ( ) ) { log . debug ( "sendCompleteStatus - duration: {} bytes sent: {}" , duration , bytesSent . get ( ) ) ; } sendOnPlayStatus ( StatusCodes . NS_PLAY_COMPLETE , duration , bytesSent . get ( ) ) ; }
Send playlist complete status notification
6,589
private void sendSeekStatus ( IPlayItem item , int position ) { Status seek = new Status ( StatusCodes . NS_SEEK_NOTIFY ) ; seek . setClientid ( streamId ) ; seek . setDetails ( item . getName ( ) ) ; seek . setDesciption ( String . format ( "Seeking %d (stream ID: %d)." , position , streamId ) ) ; doPushMessage ( seek ) ; }
Send seek status notification
6,590
private void sendPauseStatus ( IPlayItem item ) { Status pause = new Status ( StatusCodes . NS_PAUSE_NOTIFY ) ; pause . setClientid ( streamId ) ; pause . setDetails ( item . getName ( ) ) ; doPushMessage ( pause ) ; }
Send pause status notification
6,591
private void sendResumeStatus ( IPlayItem item ) { Status resume = new Status ( StatusCodes . NS_UNPAUSE_NOTIFY ) ; resume . setClientid ( streamId ) ; resume . setDetails ( item . getName ( ) ) ; doPushMessage ( resume ) ; }
Send resume status notification
6,592
private void sendPublishedStatus ( IPlayItem item ) { Status published = new Status ( StatusCodes . NS_PLAY_PUBLISHNOTIFY ) ; published . setClientid ( streamId ) ; published . setDetails ( item . getName ( ) ) ; doPushMessage ( published ) ; }
Send published status notification
6,593
private void sendUnpublishedStatus ( IPlayItem item ) { Status unpublished = new Status ( StatusCodes . NS_PLAY_UNPUBLISHNOTIFY ) ; unpublished . setClientid ( streamId ) ; unpublished . setDetails ( item . getName ( ) ) ; doPushMessage ( unpublished ) ; }
Send unpublished status notification
6,594
private void sendStreamNotFoundStatus ( IPlayItem item ) { Status notFound = new Status ( StatusCodes . NS_PLAY_STREAMNOTFOUND ) ; notFound . setClientid ( streamId ) ; notFound . setLevel ( Status . ERROR ) ; notFound . setDetails ( item . getName ( ) ) ; doPushMessage ( notFound ) ; }
Stream not found status notification
6,595
private void sendInsufficientBandwidthStatus ( IPlayItem item ) { Status insufficientBW = new Status ( StatusCodes . NS_PLAY_INSUFFICIENT_BW ) ; insufficientBW . setClientid ( streamId ) ; insufficientBW . setLevel ( Status . WARNING ) ; insufficientBW . setDetails ( item . getName ( ) ) ; insufficientBW . setDesciption ( "Data is playing behind the normal speed." ) ; doPushMessage ( insufficientBW ) ; }
Insufficient bandwidth notification
6,596
private void sendVODInitCM ( IPlayItem item ) { OOBControlMessage oobCtrlMsg = new OOBControlMessage ( ) ; oobCtrlMsg . setTarget ( IPassive . KEY ) ; oobCtrlMsg . setServiceName ( "init" ) ; Map < String , Object > paramMap = new HashMap < String , Object > ( 1 ) ; paramMap . put ( "startTS" , ( int ) item . getStart ( ) ) ; oobCtrlMsg . setServiceParamMap ( paramMap ) ; msgInReference . get ( ) . sendOOBControlMessage ( this , oobCtrlMsg ) ; }
Send VOD init control message
6,597
private int sendVODSeekCM ( int position ) { OOBControlMessage oobCtrlMsg = new OOBControlMessage ( ) ; oobCtrlMsg . setTarget ( ISeekableProvider . KEY ) ; oobCtrlMsg . setServiceName ( "seek" ) ; Map < String , Object > paramMap = new HashMap < String , Object > ( 1 ) ; paramMap . put ( "position" , position ) ; oobCtrlMsg . setServiceParamMap ( paramMap ) ; msgInReference . get ( ) . sendOOBControlMessage ( this , oobCtrlMsg ) ; if ( oobCtrlMsg . getResult ( ) instanceof Integer ) { return ( Integer ) oobCtrlMsg . getResult ( ) ; } else { return - 1 ; } }
Send VOD seek control message
6,598
private boolean sendCheckVideoCM ( ) { OOBControlMessage oobCtrlMsg = new OOBControlMessage ( ) ; oobCtrlMsg . setTarget ( IStreamTypeAwareProvider . KEY ) ; oobCtrlMsg . setServiceName ( "hasVideo" ) ; msgInReference . get ( ) . sendOOBControlMessage ( this , oobCtrlMsg ) ; if ( oobCtrlMsg . getResult ( ) instanceof Boolean ) { return ( Boolean ) oobCtrlMsg . getResult ( ) ; } else { return false ; } }
Send VOD check video control message
6,599
private long pendingVideoMessages ( ) { IMessageOutput out = msgOutReference . get ( ) ; if ( out != null ) { OOBControlMessage pendingRequest = new OOBControlMessage ( ) ; pendingRequest . setTarget ( "ConnectionConsumer" ) ; pendingRequest . setServiceName ( "pendingVideoCount" ) ; out . sendOOBControlMessage ( this , pendingRequest ) ; if ( pendingRequest . getResult ( ) != null ) { return ( Long ) pendingRequest . getResult ( ) ; } } return 0 ; }
Get number of pending video messages