idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
6,400 | private void addClient ( String id , IClient client ) { if ( ! hasClient ( id ) ) { clients . put ( id , client ) ; } else { log . debug ( "Client id: {} already registered" , id ) ; } } | Add the client to the registry |
6,401 | public ClientList < Client > getClientList ( ) { ClientList < Client > list = new ClientList < Client > ( ) ; for ( IClient c : clients . values ( ) ) { list . add ( ( Client ) c ) ; } return list ; } | Returns a list of Clients . |
6,402 | @ SuppressWarnings ( "unchecked" ) protected Collection < IClient > getClients ( ) { if ( ! hasClients ( ) ) { return Collections . EMPTY_SET ; } return Collections . unmodifiableCollection ( clients . values ( ) ) ; } | Return collection of clients |
6,403 | public IClient newClient ( Object [ ] params ) throws ClientNotFoundException , ClientRejectedException { String id = nextId ( ) ; IClient client = new Client ( id , this ) ; addClient ( id , client ) ; return client ; } | Return client from next id with given params |
6,404 | public String nextId ( ) { String id = "-1" ; do { if ( nextId . get ( ) == Integer . MAX_VALUE ) { nextId . set ( 0 ) ; } id = String . format ( "%d" , nextId . getAndIncrement ( ) ) ; } while ( hasClient ( id ) ) ; return id ; } | Return next client id |
6,405 | private IPersistenceStore getStore ( IScope scope , boolean persistent ) { IPersistenceStore store ; if ( ! persistent ) { if ( ! scope . hasAttribute ( SO_TRANSIENT_STORE ) ) { store = new RamPersistence ( scope ) ; scope . setAttribute ( SO_TRANSIENT_STORE , store ) ; return store ; } return ( IPersistenceStore ) scope . getAttribute ( SO_TRANSIENT_STORE ) ; } if ( ! scope . hasAttribute ( SO_PERSISTENCE_STORE ) ) { try { store = PersistenceUtils . getPersistenceStore ( scope , persistenceClassName ) ; log . info ( "Created persistence store {} for shared objects" , store ) ; } catch ( Exception err ) { log . warn ( "Could not create persistence store ({}) for shared objects, falling back to Ram persistence" , persistenceClassName , err ) ; store = new RamPersistence ( scope ) ; } scope . setAttribute ( SO_PERSISTENCE_STORE , store ) ; return store ; } return ( IPersistenceStore ) scope . getAttribute ( SO_PERSISTENCE_STORE ) ; } | Return scope store |
6,406 | private static Constructor < ? > getPersistenceStoreConstructor ( Class < ? > theClass , Class < ? > [ ] interfaces ) throws Exception { Constructor < ? > constructor = null ; for ( Class < ? > interfaceClass : interfaces ) { try { constructor = theClass . getConstructor ( new Class [ ] { interfaceClass } ) ; } catch ( NoSuchMethodException err ) { } if ( constructor != null ) { break ; } constructor = getPersistenceStoreConstructor ( theClass , interfaceClass . getInterfaces ( ) ) ; if ( constructor != null ) { break ; } } return constructor ; } | Returns persistence store object class constructor |
6,407 | public static ChunkHeader read ( IoBuffer in ) { int remaining = in . remaining ( ) ; if ( remaining > 0 ) { byte headerByte = in . get ( ) ; ChunkHeader h = new ChunkHeader ( ) ; h . format = ( byte ) ( ( 0b11000000 & headerByte ) >> 6 ) ; int fmt = headerByte & 0x3f ; switch ( fmt ) { case 0 : h . size = 2 ; if ( remaining < 2 ) { throw new ProtocolException ( "Bad chunk header, at least 2 bytes are expected" ) ; } h . channelId = 64 + ( in . get ( ) & 0xff ) ; break ; case 1 : h . size = 3 ; if ( remaining < 3 ) { throw new ProtocolException ( "Bad chunk header, at least 3 bytes are expected" ) ; } byte b1 = in . get ( ) ; byte b2 = in . get ( ) ; h . channelId = 64 + ( ( b2 & 0xff ) << 8 | ( b1 & 0xff ) ) ; break ; default : h . size = 1 ; h . channelId = 0x3f & headerByte ; break ; } if ( h . channelId < 0 ) { throw new ProtocolException ( "Bad channel id: " + h . channelId ) ; } log . trace ( "CHUNK header byte {}, count {}, header {}, channel {}" , String . format ( "%02x" , headerByte ) , h . size , 0 , h . channelId ) ; return h ; } else { throw new ProtocolException ( "Bad chunk header, at least 1 byte is expected" ) ; } } | Read chunk header from the buffer . |
6,408 | private boolean acquireWriteFuture ( int sliceLength ) { if ( sliceLength > 0 ) { Object writeResult = null ; int timeout = sliceLength * 500 ; if ( writerFuture != null ) { try { writeResult = writerFuture . get ( timeout , TimeUnit . MILLISECONDS ) ; } catch ( Exception e ) { log . warn ( "Exception waiting for write result. Timeout: {}ms" , timeout , e ) ; return false ; } } log . debug ( "Write future result (expect null): {}" , writeResult ) ; return true ; } return false ; } | Get the WriteFuture with a timeout based on the length of the slice to write . |
6,409 | public void uninit ( ) { if ( initialized . get ( ) ) { log . debug ( "Uninit" ) ; if ( writer != null ) { if ( writerFuture != null ) { try { writerFuture . get ( ) ; } catch ( Exception e ) { log . warn ( "Exception waiting for write result on uninit" , e ) ; } if ( writerFuture . cancel ( false ) ) { log . debug ( "Future completed" ) ; } } writerFuture = null ; doWrites ( ) ; queue . clear ( ) ; queue = null ; writer . close ( ) ; writer = null ; } path = null ; } } | Reset or uninitialize |
6,410 | public final void doWrites ( ) { QueuedMediaData [ ] slice = null ; writeLock . lock ( ) ; try { slice = queue . toArray ( new QueuedMediaData [ 0 ] ) ; if ( queue . removeAll ( Arrays . asList ( slice ) ) ) { log . debug ( "Queued writes transfered, count: {}" , slice . length ) ; } } finally { writeLock . unlock ( ) ; } Arrays . sort ( slice ) ; doWrites ( slice ) ; } | Write all the queued items to the writer . |
6,411 | public final void doWrites ( QueuedMediaData [ ] slice ) { for ( QueuedMediaData queued : slice ) { int tmpTs = queued . getTimestamp ( ) ; if ( lastWrittenTs <= tmpTs ) { if ( queued . hasData ( ) ) { write ( queued ) ; lastWrittenTs = tmpTs ; queued . dispose ( ) ; } else { if ( log . isTraceEnabled ( ) ) { log . trace ( "Queued data was not available" ) ; } } } else { queued . dispose ( ) ; } } slice = null ; } | Write a slice of the queued items to the writer . |
6,412 | public void setupOutputPath ( String name ) { IStreamFilenameGenerator generator = ( IStreamFilenameGenerator ) ScopeUtils . getScopeService ( scope , IStreamFilenameGenerator . class , DefaultStreamFilenameGenerator . class ) ; String filePath = generator . generateFilename ( scope , name , ".flv" , GenerationType . RECORD ) ; this . path = generator . resolvesToAbsolutePath ( ) ? Paths . get ( filePath ) : Paths . get ( System . getProperty ( "red5.root" ) , "webapps" , scope . getContextPath ( ) , filePath ) ; File appendee = getFile ( ) ; if ( IClientStream . MODE_APPEND . equals ( mode ) && ! appendee . exists ( ) ) { try { if ( appendee . createNewFile ( ) ) { log . debug ( "New file created for appending" ) ; } else { log . debug ( "Failure to create new file for appending" ) ; } } catch ( IOException e ) { log . warn ( "Exception creating replacement file for append" , e ) ; } } } | Sets up the output file path for writing . |
6,413 | public void setVideoDecoderConfiguration ( IRTMPEvent decoderConfig ) { if ( decoderConfig instanceof IStreamData ) { IoBuffer data = ( ( IStreamData < ? > ) decoderConfig ) . getData ( ) . asReadOnlyBuffer ( ) ; videoConfigurationTag = ImmutableTag . build ( decoderConfig . getDataType ( ) , 0 , data , 0 ) ; } } | Sets a video decoder configuration ; some codecs require this such as AVC . |
6,414 | public void setAudioDecoderConfiguration ( IRTMPEvent decoderConfig ) { if ( decoderConfig instanceof IStreamData ) { IoBuffer data = ( ( IStreamData < ? > ) decoderConfig ) . getData ( ) . asReadOnlyBuffer ( ) ; audioConfigurationTag = ImmutableTag . build ( decoderConfig . getDataType ( ) , 0 , data , 0 ) ; } } | Sets a audio decoder configuration ; some codecs require this such as AAC . |
6,415 | public void disconnect ( ) { if ( disconnected . compareAndSet ( false , true ) ) { log . debug ( "Disconnect - id: {}" , id ) ; if ( connections != null && ! connections . isEmpty ( ) ) { log . debug ( "Closing {} scope connections" , connections . size ( ) ) ; for ( IConnection con : getConnections ( ) ) { try { con . close ( ) ; } catch ( Exception e ) { log . error ( "Unexpected exception closing connection {}" , e ) ; } } } else { log . debug ( "Connection map is empty or null" ) ; } removeInstance ( ) ; } } | Disconnects client from Red5 application |
6,416 | public Set < IConnection > getConnections ( IScope scope ) { if ( scope == null ) { return getConnections ( ) ; } Set < IClient > scopeClients = scope . getClients ( ) ; if ( scopeClients . contains ( this ) ) { for ( IClient cli : scopeClients ) { if ( this . equals ( cli ) ) { return cli . getConnections ( ) ; } } } return Collections . emptySet ( ) ; } | Return client connections to given scope |
6,417 | public List < String > iterateScopeNameList ( ) { log . debug ( "iterateScopeNameList called" ) ; Collection < IScope > scopes = getScopes ( ) ; log . debug ( "Scopes: {}" , scopes . size ( ) ) ; List < String > scopeNames = new ArrayList < String > ( scopes . size ( ) ) ; for ( IScope scope : scopes ) { log . debug ( "Client scope: {}" , scope ) ; scopeNames . add ( scope . getName ( ) ) ; if ( log . isDebugEnabled ( ) ) { for ( Map . Entry < String , Object > entry : scope . getAttributes ( ) . entrySet ( ) ) { log . debug ( "Client scope attr: {} = {}" , entry . getKey ( ) , entry . getValue ( ) ) ; } } } return scopeNames ; } | Iterate through the scopes and their attributes . Used by JMX |
6,418 | protected void register ( IConnection conn ) { if ( log . isDebugEnabled ( ) ) { if ( conn == null ) { log . debug ( "Register null connection, client id: {}" , id ) ; } else { log . debug ( "Register connection ({}:{}) client id: {}" , conn . getRemoteAddress ( ) , conn . getRemotePort ( ) , id ) ; } } if ( conn != null ) { IScope scope = conn . getScope ( ) ; if ( scope != null ) { log . debug ( "Registering for scope: {}" , scope ) ; connections . add ( conn ) ; } else { log . warn ( "Clients scope is null. Id: {}" , id ) ; } } else { log . warn ( "Clients connection is null. Id: {}" , id ) ; } } | Associate connection with client |
6,419 | protected void unregister ( IConnection conn , boolean deleteIfNoConns ) { log . debug ( "Unregister connection ({}:{}) client id: {}" , conn . getRemoteAddress ( ) , conn . getRemotePort ( ) , id ) ; connections . remove ( conn ) ; if ( deleteIfNoConns && connections . isEmpty ( ) ) { removeInstance ( ) ; } } | Removes client - connection association for given connection |
6,420 | private void removeInstance ( ) { ClientRegistry ref = registry . get ( ) ; if ( ref != null ) { ref . removeClient ( this ) ; } else { log . warn ( "Client registry reference was not accessable, removal failed" ) ; } } | Removes this instance from the client registry . |
6,421 | public boolean addChildScope ( IBasicScope scope ) { log . debug ( "Add child: {}" , scope ) ; boolean added = false ; if ( scope . isValid ( ) ) { try { if ( ! children . containsKey ( scope ) ) { log . debug ( "Adding child scope: {} to {}" , scope , this ) ; added = children . add ( scope ) ; } else { log . warn ( "Child scope already exists" ) ; } } catch ( Exception e ) { log . warn ( "Exception on add subscope" , e ) ; } } else { log . warn ( "Invalid scope rejected: {}" , scope ) ; } if ( added && scope . getStore ( ) == null ) { try { if ( scope instanceof Scope ) { ( ( Scope ) scope ) . setPersistenceClass ( persistenceClass ) ; } } catch ( Exception error ) { log . error ( "Could not set persistence class" , error ) ; } } return added ; } | Add child scope to this scope |
6,422 | public boolean connect ( IConnection conn , Object [ ] params ) { log . debug ( "Connect - scope: {} connection: {}" , this , conn ) ; if ( enabled ) { if ( hasParent ( ) && ! parent . connect ( conn , params ) ) { log . debug ( "Connection to parent failed" ) ; return false ; } if ( hasHandler ( ) && ! getHandler ( ) . connect ( conn , this , params ) ) { log . debug ( "Connection to handler failed" ) ; return false ; } if ( ! conn . isConnected ( ) ) { log . debug ( "Connection is not connected" ) ; return false ; } final IClient client = conn . getClient ( ) ; if ( hasHandler ( ) && ! getHandler ( ) . join ( client , this ) ) { return false ; } if ( ! conn . isConnected ( ) ) { return false ; } if ( clients . add ( client ) && addEventListener ( conn ) ) { log . debug ( "Added client" ) ; connectionStats . increment ( ) ; IScope connScope = conn . getScope ( ) ; log . trace ( "Connection scope: {}" , connScope ) ; if ( this . equals ( connScope ) ) { final IServer server = getServer ( ) ; if ( server instanceof Server ) { ( ( Server ) server ) . notifyConnected ( conn ) ; } } return true ; } } else { log . debug ( "Connection failed, scope is disabled" ) ; } return false ; } | Connect to scope with parameters . To successfully connect to scope it must have handler that will accept this connection with given set of parameters . Client associated with connection is added to scope clients set connection is registered as scope event listener . |
6,423 | public boolean createChildScope ( String name ) { log . debug ( "createChildScope: {}" , name ) ; if ( children . hasName ( name ) ) { log . debug ( "Scope: {} already exists, children: {}" , name , children . getNames ( ) ) ; } else { return addChildScope ( new Builder ( this , ScopeType . ROOM , name , false ) . build ( ) ) ; } return false ; } | Create child scope of room type with the given name . |
6,424 | public void disconnect ( IConnection conn ) { log . debug ( "Disconnect: {}" , conn ) ; final IClient client = conn . getClient ( ) ; if ( client == null ) { removeEventListener ( conn ) ; connectionStats . decrement ( ) ; if ( hasParent ( ) ) { parent . disconnect ( conn ) ; } return ; } if ( clients . remove ( client ) ) { IScopeHandler handler = getHandler ( ) ; if ( handler != null ) { try { handler . disconnect ( conn , this ) ; } catch ( Exception e ) { log . error ( "Error while executing \"disconnect\" for connection {} on handler {}. {}" , new Object [ ] { conn , handler , e } ) ; } try { handler . leave ( client , this ) ; } catch ( Exception e ) { log . error ( "Error while executing \"leave\" for client {} on handler {}. {}" , new Object [ ] { conn , handler , e } ) ; } } removeEventListener ( conn ) ; connectionStats . decrement ( ) ; if ( this . equals ( conn . getScope ( ) ) ) { final IServer server = getServer ( ) ; if ( server instanceof Server ) { ( ( Server ) server ) . notifyDisconnected ( conn ) ; } } } if ( hasParent ( ) ) { parent . disconnect ( conn ) ; } } | Disconnect connection from scope |
6,425 | public IBroadcastScope getBroadcastScope ( String name ) { return ( IBroadcastScope ) children . getBasicScope ( ScopeType . BROADCAST , name ) ; } | Return the broadcast scope for a given name |
6,426 | public IBasicScope getBasicScope ( ScopeType type , String name ) { return children . getBasicScope ( type , name ) ; } | Return base scope of given type with given name |
6,427 | public Set < String > getBasicScopeNames ( ScopeType type ) { if ( type != null ) { Set < String > names = new HashSet < String > ( ) ; for ( IBasicScope child : children . keySet ( ) ) { if ( child . getType ( ) . equals ( type ) ) { names . add ( child . getName ( ) ) ; } } return names ; } return getScopeNames ( ) ; } | Return basic scope names matching given type |
6,428 | public int getDepth ( ) { if ( depth == UNSET ) { if ( hasParent ( ) ) { depth = parent . getDepth ( ) + 1 ; } else { depth = 0 ; } } return depth ; } | return scope depth |
6,429 | public IScopeHandler getHandler ( ) { log . trace ( "getHandler from {}" , name ) ; if ( handler != null ) { return handler ; } else if ( hasParent ( ) ) { return getParent ( ) . getHandler ( ) ; } else { return null ; } } | Return scope handler or parent s scope handler if this scope doesn t have one . |
6,430 | public Resource getResource ( String path ) { if ( hasContext ( ) ) { return context . getResource ( path ) ; } return getContext ( ) . getResource ( getContextPath ( ) + '/' + path ) ; } | Return resource located at given path |
6,431 | public Resource [ ] getResources ( String path ) throws IOException { if ( hasContext ( ) ) { return context . getResources ( path ) ; } return getContext ( ) . getResources ( getContextPath ( ) + '/' + path ) ; } | Return array of resources from path string usually used with pattern path |
6,432 | public IScope getScope ( String name ) { IBasicScope child = children . getBasicScope ( ScopeType . UNDEFINED , name ) ; log . debug ( "Child of {}: {}" , this . name , child ) ; if ( child != null ) { if ( child instanceof IScope ) { return ( IScope ) child ; } log . warn ( "Requested scope: {} is not of IScope type: {}" , name , child . getClass ( ) . getName ( ) ) ; } return null ; } | Return child scope by name |
6,433 | public Object getServiceHandler ( String name ) { Map < String , Object > serviceHandlers = getServiceHandlers ( false ) ; if ( serviceHandlers == null ) { return null ; } return serviceHandlers . get ( name ) ; } | Return service handler by name |
6,434 | @ SuppressWarnings ( "unchecked" ) public Set < String > getServiceHandlerNames ( ) { Map < String , Object > serviceHandlers = getServiceHandlers ( false ) ; if ( serviceHandlers == null ) { return Collections . EMPTY_SET ; } return serviceHandlers . keySet ( ) ; } | Return set of service handler names . Removing entries from the set unregisters the corresponding service handler . |
6,435 | protected Map < String , Object > getServiceHandlers ( boolean allowCreate ) { if ( serviceHandlers == null ) { if ( allowCreate ) { serviceHandlers = new ConcurrentHashMap < String , Object > ( 3 , 0.9f , 1 ) ; } } return serviceHandlers ; } | Return map of service handlers and optionally created it if it doesn t exist . |
6,436 | public boolean hasChildScope ( ScopeType type , String name ) { log . debug ( "Has child scope? {} in {}" , name , this ) ; return children . getBasicScope ( type , name ) != null ; } | Check whether scope has child scope with given name and type |
6,437 | public void init ( ) { log . debug ( "Init scope: {} parent: {}" , name , parent ) ; if ( hasParent ( ) ) { if ( ! parent . hasChildScope ( name ) ) { if ( parent . addChildScope ( this ) ) { log . debug ( "Scope added to parent" ) ; } else { log . warn ( "Scope not added to parent" ) ; return ; } } else { throw new ScopeException ( "Scope already exists in parent" ) ; } } else { log . debug ( "Scope has no parent" ) ; } if ( autoStart ) { start ( ) ; } } | Initialization actions start if autostart is set to true . |
6,438 | public void uninit ( ) { log . debug ( "Un-init scope" ) ; for ( IBasicScope child : children . keySet ( ) ) { if ( child instanceof Scope ) { ( ( Scope ) child ) . uninit ( ) ; } } stop ( ) ; setEnabled ( false ) ; if ( hasParent ( ) ) { if ( parent . hasChildScope ( name ) ) { parent . removeChildScope ( this ) ; } } } | Uninitialize scope and unregister from parent . |
6,439 | public void registerServiceHandler ( String name , Object handler ) { Map < String , Object > serviceHandlers = getServiceHandlers ( ) ; serviceHandlers . put ( name , handler ) ; } | Register service handler by name |
6,440 | public void removeChildScope ( IBasicScope scope ) { log . debug ( "removeChildScope: {}" , scope ) ; if ( children . containsKey ( scope ) ) { children . remove ( scope ) ; if ( scope instanceof Scope ) { unregisterJMX ( ) ; } } } | Removes child scope |
6,441 | public void removeChildren ( ) { log . trace ( "removeChildren of {}" , name ) ; for ( IBasicScope child : children . keySet ( ) ) { removeChildScope ( child ) ; } } | Removes all the child scopes |
6,442 | public void setHandler ( IScopeHandler handler ) { log . debug ( "setHandler: {} on {}" , handler , name ) ; this . handler = handler ; if ( handler instanceof IScopeAware ) { ( ( IScopeAware ) handler ) . setScope ( this ) ; } } | Setter for scope event handler |
6,443 | public final void setName ( String name ) { log . debug ( "Set name: {}" , name ) ; if ( this . name == null && StringUtils . isNotBlank ( name ) ) { this . name = name ; if ( oName != null ) { unregisterJMX ( ) ; } registerJMX ( ) ; } else { log . info ( "Scope {} name reset to: {} disallowed" , this . name , name ) ; } } | Setter for scope name |
6,444 | public void setPersistenceClass ( String persistenceClass ) throws Exception { this . persistenceClass = persistenceClass ; if ( persistenceClass != null ) { store = PersistenceUtils . getPersistenceStore ( this , persistenceClass ) ; } } | Set scope persistence class |
6,445 | public void unregisterServiceHandler ( String name ) { Map < String , Object > serviceHandlers = getServiceHandlers ( false ) ; if ( serviceHandlers != null ) { serviceHandlers . remove ( name ) ; } } | Unregisters service handler by name |
6,446 | public IServer getServer ( ) { if ( hasParent ( ) ) { final IScope parent = getParent ( ) ; if ( parent instanceof Scope ) { return ( ( Scope ) parent ) . getServer ( ) ; } else if ( parent instanceof IGlobalScope ) { return ( ( IGlobalScope ) parent ) . getServer ( ) ; } } return null ; } | Return the server instance connected to this scope . |
6,447 | public void setParamMap ( Map < String , Object > paramMap ) { if ( paramMap != null && ! paramMap . isEmpty ( ) ) { this . paramMap . putAll ( paramMap ) ; } } | Setter for event parameters map |
6,448 | public final static PipeConnectionEvent build ( AbstractPipe source , EventType type , IConsumer consumer , Map < String , Object > paramMap ) { return new PipeConnectionEvent ( source , type , consumer , paramMap ) ; } | Builds a PipeConnectionEvent with a source pipe and consumer . |
6,449 | public final static PipeConnectionEvent build ( AbstractPipe source , EventType type , IProvider provider , Map < String , Object > paramMap ) { return new PipeConnectionEvent ( source , type , provider , paramMap ) ; } | Builds a PipeConnectionEvent with a source pipe and provider . |
6,450 | public void setCredentials ( String userid , String password ) { Map < String , String > data = new HashMap < String , String > ( ) ; data . put ( "userid" , userid ) ; data . put ( "password" , password ) ; RemotingHeader header = new RemotingHeader ( RemotingHeader . CREDENTIALS , true , data ) ; headers . put ( RemotingHeader . CREDENTIALS , header ) ; } | Send authentication data with each remoting request . |
6,451 | public void addHeader ( String name , boolean required , Object value ) { RemotingHeader header = new RemotingHeader ( name , required , value ) ; headers . put ( name , header ) ; } | Send an additional header to the server . |
6,452 | public Object invokeMethod ( String method , Object [ ] params ) { log . debug ( "invokeMethod url: {}" , ( url + appendToUrl ) ) ; IoBuffer resultBuffer = null ; IoBuffer data = encodeInvoke ( method , params ) ; HttpPost post = null ; try { post = new HttpPost ( url + appendToUrl ) ; post . addHeader ( "Content-Type" , CONTENT_TYPE ) ; post . setEntity ( new InputStreamEntity ( data . asInputStream ( ) , data . limit ( ) ) ) ; HttpResponse response = client . execute ( post ) ; int code = response . getStatusLine ( ) . getStatusCode ( ) ; log . debug ( "HTTP response code: {}" , code ) ; if ( code / 100 != 2 ) { throw new RuntimeException ( "Didn't receive success from remoting server" ) ; } else { HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { int contentLength = ( int ) entity . getContentLength ( ) ; if ( contentLength < 1 ) { contentLength = 16 ; } byte [ ] bytes = EntityUtils . toByteArray ( entity ) ; resultBuffer = IoBuffer . wrap ( bytes ) ; Object result = decodeResult ( resultBuffer ) ; if ( result instanceof RecordSet ) { ( ( RecordSet ) result ) . setRemotingClient ( this ) ; } return result ; } } } catch ( Exception ex ) { log . error ( "Error while invoking remoting method: {}" , method , ex ) ; post . abort ( ) ; } finally { if ( resultBuffer != null ) { resultBuffer . free ( ) ; resultBuffer = null ; } data . free ( ) ; data = null ; } return null ; } | Invoke a method synchronously on the remoting server . |
6,453 | public void invokeMethod ( String method , Object [ ] methodParams , IRemotingCallback callback ) { try { RemotingWorker worker = new RemotingWorker ( this , method , methodParams , callback ) ; executor . execute ( worker ) ; } catch ( Exception err ) { log . warn ( "Exception invoking method: {}" , method , err ) ; } } | Invoke a method asynchronously on the remoting server . |
6,454 | public List < Object > decodeBuffer ( RTMPConnection conn , IoBuffer buffer ) { final int position = buffer . position ( ) ; List < Object > result = null ; if ( conn != null ) { try { result = new LinkedList < > ( ) ; RTMPDecodeState state = conn . getDecoderState ( ) ; if ( ! conn . getSessionId ( ) . equals ( state . getSessionId ( ) ) ) { log . warn ( "Session decode overlap: {} != {}" , conn . getSessionId ( ) , state . getSessionId ( ) ) ; } int remaining ; while ( ( remaining = buffer . remaining ( ) ) > 0 ) { if ( state . canStartDecoding ( remaining ) ) { state . startDecoding ( ) ; } else { log . trace ( "Cannot start decoding" ) ; break ; } final Object decodedObject = decode ( conn , state , buffer ) ; if ( state . hasDecodedObject ( ) ) { if ( decodedObject != null ) { result . add ( decodedObject ) ; } } else if ( state . canContinueDecoding ( ) ) { continue ; } else { log . trace ( "Cannot continue decoding" ) ; break ; } } } catch ( Exception ex ) { log . warn ( "Failed to decodeBuffer: pos {}, limit {}, chunk size {}, buffer {}" , position , buffer . limit ( ) , conn . getState ( ) . getReadChunkSize ( ) , Hex . encodeHexString ( Arrays . copyOfRange ( buffer . array ( ) , position , buffer . limit ( ) ) ) ) ; log . warn ( "Closing connection because decoding failed: {}" , conn , ex ) ; buffer . clear ( ) ; conn . close ( ) ; } finally { buffer . compact ( ) ; } } else { log . error ( "Decoding buffer failed, no current connection!?" ) ; } return result ; } | Decode all available objects in buffer . |
6,455 | public Object decode ( RTMPConnection conn , RTMPDecodeState state , IoBuffer in ) throws ProtocolException { try { final byte connectionState = conn . getStateCode ( ) ; switch ( connectionState ) { case RTMP . STATE_CONNECTED : return decodePacket ( conn , state , in ) ; case RTMP . STATE_ERROR : case RTMP . STATE_DISCONNECTING : case RTMP . STATE_DISCONNECTED : in . clear ( ) ; return null ; default : throw new IllegalStateException ( "Invalid RTMP state: " + connectionState ) ; } } catch ( ProtocolException pe ) { throw pe ; } catch ( RuntimeException e ) { throw new ProtocolException ( "Error during decoding" , e ) ; } finally { } } | Decodes the buffer data . |
6,456 | public IRTMPEvent decodeMessage ( RTMPConnection conn , Header header , IoBuffer in ) { IRTMPEvent message ; byte dataType = header . getDataType ( ) ; switch ( dataType ) { case TYPE_AUDIO_DATA : message = decodeAudioData ( in ) ; message . setSourceType ( Constants . SOURCE_TYPE_LIVE ) ; break ; case TYPE_VIDEO_DATA : message = decodeVideoData ( in ) ; message . setSourceType ( Constants . SOURCE_TYPE_LIVE ) ; break ; case TYPE_AGGREGATE : message = decodeAggregate ( in ) ; break ; case TYPE_FLEX_SHARED_OBJECT : message = decodeFlexSharedObject ( in ) ; break ; case TYPE_SHARED_OBJECT : message = decodeSharedObject ( in ) ; break ; case TYPE_FLEX_MESSAGE : message = decodeFlexMessage ( in ) ; break ; case TYPE_INVOKE : message = decodeAction ( conn . getEncoding ( ) , in , header ) ; break ; case TYPE_FLEX_STREAM_SEND : if ( log . isTraceEnabled ( ) ) { log . trace ( "Decoding flex stream send on stream id: {}" , header . getStreamId ( ) ) ; } in . get ( ) ; message = decodeStreamData ( in . slice ( ) ) ; break ; case TYPE_NOTIFY : if ( log . isTraceEnabled ( ) ) { log . trace ( "Decoding notify on stream id: {}" , header . getStreamId ( ) ) ; } if ( header . getStreamId ( ) . doubleValue ( ) != 0.0d ) { message = decodeStreamData ( in ) ; } else { message = decodeAction ( conn . getEncoding ( ) , in , header ) ; } break ; case TYPE_PING : message = decodePing ( in ) ; break ; case TYPE_BYTES_READ : message = decodeBytesRead ( in ) ; break ; case TYPE_CHUNK_SIZE : message = decodeChunkSize ( in ) ; break ; case TYPE_SERVER_BANDWIDTH : message = decodeServerBW ( in ) ; break ; case TYPE_CLIENT_BANDWIDTH : message = decodeClientBW ( in ) ; break ; case TYPE_ABORT : message = decodeAbort ( in ) ; break ; default : log . warn ( "Unknown object type: {}" , dataType ) ; message = decodeUnknown ( dataType , in ) ; break ; } message . setHeader ( header ) ; return message ; } | Decodes RTMP message event . |
6,457 | protected void doDecodeSharedObject ( SharedObjectMessage so , IoBuffer in , Input input ) { Input amf3Input = new org . red5 . io . amf3 . Input ( in ) ; while ( in . hasRemaining ( ) ) { final ISharedObjectEvent . Type type = SharedObjectTypeMapping . toType ( in . get ( ) ) ; if ( type == null ) { in . skip ( in . remaining ( ) ) ; return ; } String key = null ; Object value = null ; final int length = in . getInt ( ) ; if ( type == ISharedObjectEvent . Type . CLIENT_STATUS ) { key = input . getString ( ) ; value = input . getString ( ) ; } else if ( type == ISharedObjectEvent . Type . CLIENT_UPDATE_DATA ) { key = null ; final Map < String , Object > map = new HashMap < String , Object > ( ) ; final int start = in . position ( ) ; while ( in . position ( ) - start < length ) { String tmp = input . getString ( ) ; map . put ( tmp , Deserializer . deserialize ( input , Object . class ) ) ; } value = map ; } else if ( type != ISharedObjectEvent . Type . SERVER_SEND_MESSAGE && type != ISharedObjectEvent . Type . CLIENT_SEND_MESSAGE ) { if ( length > 0 ) { key = input . getString ( ) ; if ( length > key . length ( ) + 2 ) { byte objType = in . get ( ) ; in . position ( in . position ( ) - 1 ) ; Input propertyInput ; if ( objType == AMF . TYPE_AMF3_OBJECT && ! ( input instanceof org . red5 . io . amf3 . Input ) ) { propertyInput = amf3Input ; } else { propertyInput = input ; } value = Deserializer . deserialize ( propertyInput , Object . class ) ; } } } else { final int start = in . position ( ) ; key = Deserializer . deserialize ( input , String . class ) ; final List < Object > list = new LinkedList < Object > ( ) ; while ( in . position ( ) - start < length ) { byte objType = in . get ( ) ; in . position ( in . position ( ) - 1 ) ; Input propertyInput ; if ( objType == AMF . TYPE_AMF3_OBJECT && ! ( input instanceof org . red5 . io . amf3 . Input ) ) { propertyInput = amf3Input ; } else { propertyInput = input ; } Object tmp = Deserializer . deserialize ( propertyInput , Object . class ) ; list . add ( tmp ) ; } value = list ; } so . addEvent ( type , key , value ) ; } } | Perform the actual decoding of the shared object contents . |
6,458 | private Invoke decodeAction ( Encoding encoding , IoBuffer in , Header header ) { in . mark ( ) ; byte tmp = in . get ( ) ; in . reset ( ) ; Input input ; if ( encoding == Encoding . AMF3 && tmp == AMF . TYPE_AMF3_OBJECT ) { input = new org . red5 . io . amf3 . Input ( in ) ; ( ( org . red5 . io . amf3 . Input ) input ) . enforceAMF3 ( ) ; } else { input = new org . red5 . io . amf . Input ( in ) ; } String action = Deserializer . deserialize ( input , String . class ) ; if ( action == null ) { throw new RuntimeException ( "Action was null" ) ; } if ( log . isTraceEnabled ( ) ) { log . trace ( "Action: {}" , action ) ; } Invoke invoke = new Invoke ( ) ; invoke . setTransactionId ( readTransactionId ( input ) ) ; input . reset ( ) ; Object [ ] params = in . hasRemaining ( ) ? handleParameters ( in , invoke , input ) : new Object [ 0 ] ; final int dotIndex = action . lastIndexOf ( '.' ) ; String serviceName = ( dotIndex == - 1 ) ? null : action . substring ( 0 , dotIndex ) ; if ( serviceName != null && ( serviceName . startsWith ( "@" ) || serviceName . startsWith ( "|" ) ) ) { serviceName = serviceName . substring ( 1 ) ; } String serviceMethod = ( dotIndex == - 1 ) ? action : action . substring ( dotIndex + 1 , action . length ( ) ) ; if ( serviceMethod . startsWith ( "@" ) || serviceMethod . startsWith ( "|" ) ) { serviceMethod = serviceMethod . substring ( 1 ) ; } PendingCall call = new PendingCall ( serviceName , serviceMethod , params ) ; invoke . setCall ( call ) ; return invoke ; } | Decode the action for a supplied an Invoke . |
6,459 | public Ping decodePing ( IoBuffer in ) { Ping ping = null ; if ( log . isTraceEnabled ( ) ) { String hexDump = in . getHexDump ( ) ; log . trace ( "Ping dump: {}" , hexDump ) ; } short type = in . getShort ( ) ; switch ( type ) { case Ping . CLIENT_BUFFER : ping = new SetBuffer ( in . getInt ( ) , in . getInt ( ) ) ; break ; case Ping . PING_SWF_VERIFY : ping = new Ping ( type ) ; break ; case Ping . PONG_SWF_VERIFY : byte [ ] bytes = new byte [ 42 ] ; in . get ( bytes ) ; ping = new SWFResponse ( bytes ) ; break ; default : ping = new Ping ( type , in . getInt ( ) ) ; break ; } return ping ; } | Decodes ping event . |
6,460 | @ SuppressWarnings ( "unused" ) private boolean isStreamCommand ( String action ) { switch ( StreamAction . getEnum ( action ) ) { case CREATE_STREAM : case DELETE_STREAM : case RELEASE_STREAM : case PUBLISH : case PLAY : case PLAY2 : case SEEK : case PAUSE : case PAUSE_RAW : case CLOSE_STREAM : case RECEIVE_VIDEO : case RECEIVE_AUDIO : return true ; default : log . debug ( "Stream action {} is not a recognized command" , action ) ; return false ; } } | Checks if the passed action is a reserved stream method . |
6,461 | public void write ( IRTMPEvent event ) { if ( ! connection . isClosed ( ) ) { final IClientStream stream = connection . getStreamByChannelId ( id ) ; if ( id > 3 && stream == null ) { log . warn ( "Non-existant stream for channel id: {}, session: {} discarding: {}" , id , connection . getSessionId ( ) , event ) ; } final Number streamId = ( stream == null ) ? 0 : stream . getStreamId ( ) ; write ( event , streamId ) ; } else { log . debug ( "Connection {} is closed, cannot write to channel: {}" , connection . getSessionId ( ) , id ) ; } } | Writes packet from event data to RTMP connection . |
6,462 | private void write ( IRTMPEvent event , Number streamId ) { log . trace ( "write to stream id: {} channel: {}" , streamId , id ) ; final Header header = new Header ( ) ; final Packet packet = new Packet ( header , event ) ; header . setChannelId ( id ) ; int ts = event . getTimestamp ( ) ; if ( ts != 0 ) { header . setTimer ( event . getTimestamp ( ) ) ; } header . setStreamId ( streamId ) ; header . setDataType ( event . getDataType ( ) ) ; connection . write ( packet ) ; } | Writes packet from event data to RTMP connection and stream id . |
6,463 | @ SuppressWarnings ( "unused" ) private void discard ( IRTMPEvent event ) { if ( event instanceof IStreamData < ? > ) { log . debug ( "Discarding: {}" , ( ( IStreamData < ? > ) event ) . toString ( ) ) ; IoBuffer data = ( ( IStreamData < ? > ) event ) . getData ( ) ; if ( data != null ) { log . trace ( "Freeing discarded event data" ) ; data . free ( ) ; data = null ; } } event . setHeader ( null ) ; } | Discard an event routed to this channel . |
6,464 | public void sendStatus ( Status status ) { if ( connection != null ) { final boolean andReturn = ! status . getCode ( ) . equals ( StatusCodes . NS_DATA_START ) ; final Invoke event = new Invoke ( ) ; if ( andReturn ) { final PendingCall call = new PendingCall ( null , CALL_ON_STATUS , new Object [ ] { status } ) ; if ( status . getCode ( ) . equals ( StatusCodes . NS_PLAY_START ) ) { IScope scope = connection . getScope ( ) ; if ( scope . getContext ( ) . getApplicationContext ( ) . containsBean ( IRtmpSampleAccess . BEAN_NAME ) ) { IRtmpSampleAccess sampleAccess = ( IRtmpSampleAccess ) scope . getContext ( ) . getApplicationContext ( ) . getBean ( IRtmpSampleAccess . BEAN_NAME ) ; boolean videoAccess = sampleAccess . isVideoAllowed ( scope ) ; boolean audioAccess = sampleAccess . isAudioAllowed ( scope ) ; if ( videoAccess || audioAccess ) { final Call call2 = new Call ( null , "|RtmpSampleAccess" , null ) ; Notify notify = new Notify ( ) ; notify . setCall ( call2 ) ; notify . setData ( IoBuffer . wrap ( new byte [ ] { 0x01 , ( byte ) ( audioAccess ? 0x01 : 0x00 ) , 0x01 , ( byte ) ( videoAccess ? 0x01 : 0x00 ) } ) ) ; write ( notify , connection . getStreamIdForChannelId ( id ) ) ; } } } event . setCall ( call ) ; } else { final Call call = new Call ( null , CALL_ON_STATUS , new Object [ ] { status } ) ; event . setCall ( call ) ; } write ( event , connection . getStreamIdForChannelId ( id ) ) ; } } | Sends status notification . |
6,465 | public void pause ( Boolean pausePlayback , int position ) { IConnection conn = Red5 . getConnectionLocal ( ) ; if ( conn instanceof IStreamCapableConnection ) { IStreamCapableConnection streamConn = ( IStreamCapableConnection ) conn ; Number streamId = conn . getStreamId ( ) ; IClientStream stream = streamConn . getStreamById ( streamId ) ; if ( stream != null && stream instanceof ISubscriberStream ) { ISubscriberStream subscriberStream = ( ISubscriberStream ) stream ; if ( pausePlayback == null ) { pausePlayback = ! subscriberStream . isPaused ( ) ; } if ( pausePlayback ) { subscriberStream . pause ( position ) ; } else { subscriberStream . resume ( position ) ; } } } } | Pause at given position . Required as pausePlayback can be null if no flag is passed by the client |
6,466 | public void play ( String name , int start , int length , Object reset ) { if ( reset instanceof Boolean ) { play ( name , start , length , ( ( Boolean ) reset ) . booleanValue ( ) ) ; } else { if ( reset instanceof Integer ) { int value = ( Integer ) reset ; switch ( value ) { case 0 : IStreamCapableConnection streamConn = ( IStreamCapableConnection ) Red5 . getConnectionLocal ( ) ; IPlaylistSubscriberStream playlistStream = ( IPlaylistSubscriberStream ) streamConn . getStreamById ( streamConn . getStreamId ( ) ) ; IPlayItem item = SimplePlayItem . build ( name ) ; playlistStream . addItem ( item ) ; play ( name , start , length , false ) ; break ; case 2 : break ; case 3 : break ; default : play ( name , start , length , true ) ; } } else { play ( name , start , length ) ; } } } | Plays back a stream based on the supplied name from the specified position for the given length of time . |
6,467 | private void sendNSFailed ( IConnection conn , String errorCode , String description , String name , Number streamId ) { StreamService . sendNetStreamStatus ( conn , errorCode , description , name , Status . ERROR , streamId ) ; } | Send NetStream . Play . Failed to the client . |
6,468 | protected void initRC4Encryption ( byte [ ] sharedSecret ) { log . debug ( "Shared secret: {}" , Hex . encodeHexString ( sharedSecret ) ) ; log . debug ( "Outgoing public key [{}]: {}" , outgoingPublicKey . length , Hex . encodeHexString ( outgoingPublicKey ) ) ; byte [ ] rc4keyOut = new byte [ 32 ] ; calculateHMAC_SHA256 ( outgoingPublicKey , 0 , outgoingPublicKey . length , sharedSecret , KEY_LENGTH , rc4keyOut , 0 ) ; log . debug ( "RC4 Out Key: {}" , Hex . encodeHexString ( Arrays . copyOfRange ( rc4keyOut , 0 , 16 ) ) ) ; try { cipherOut = Cipher . getInstance ( "RC4" ) ; cipherOut . init ( Cipher . ENCRYPT_MODE , new SecretKeySpec ( rc4keyOut , 0 , 16 , "RC4" ) ) ; } catch ( Exception e ) { log . warn ( "Encryption cipher creation failed" , e ) ; } log . debug ( "Incoming public key [{}]: {}" , incomingPublicKey . length , Hex . encodeHexString ( incomingPublicKey ) ) ; byte [ ] rc4keyIn = new byte [ 32 ] ; calculateHMAC_SHA256 ( incomingPublicKey , 0 , incomingPublicKey . length , sharedSecret , KEY_LENGTH , rc4keyIn , 0 ) ; log . debug ( "RC4 In Key: {}" , Hex . encodeHexString ( Arrays . copyOfRange ( rc4keyIn , 0 , 16 ) ) ) ; try { cipherIn = Cipher . getInstance ( "RC4" ) ; cipherIn . init ( Cipher . DECRYPT_MODE , new SecretKeySpec ( rc4keyIn , 0 , 16 , "RC4" ) ) ; } catch ( Exception e ) { log . warn ( "Decryption cipher creation failed" , e ) ; } } | Prepare the ciphers . |
6,469 | protected KeyPair generateKeyPair ( ) { KeyPair keyPair = null ; DHParameterSpec keySpec = new DHParameterSpec ( DH_MODULUS , DH_BASE ) ; try { KeyPairGenerator keyGen = KeyPairGenerator . getInstance ( "DH" ) ; keyGen . initialize ( keySpec ) ; keyPair = keyGen . generateKeyPair ( ) ; keyAgreement = KeyAgreement . getInstance ( "DH" ) ; keyAgreement . init ( keyPair . getPrivate ( ) ) ; } catch ( Exception e ) { log . error ( "Error generating keypair" , e ) ; } return keyPair ; } | Creates a Diffie - Hellman key pair . |
6,470 | protected byte [ ] getPublicKey ( KeyPair keyPair ) { DHPublicKey incomingPublicKey = ( DHPublicKey ) keyPair . getPublic ( ) ; BigInteger dhY = incomingPublicKey . getY ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Public key: {}" , Hex . encodeHexString ( BigIntegers . asUnsignedByteArray ( dhY ) ) ) ; } return Arrays . copyOfRange ( BigIntegers . asUnsignedByteArray ( dhY ) , 0 , KEY_LENGTH ) ; } | Returns the public key for a given key pair . |
6,471 | public void calculateDigest ( int digestPos , byte [ ] handshakeMessage , int handshakeOffset , byte [ ] key , int keyLen , byte [ ] digest , int digestOffset ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "calculateDigest - digestPos: {} handshakeOffset: {} keyLen: {} digestOffset: {}" , digestPos , handshakeOffset , keyLen , digestOffset ) ; } int messageLen = Constants . HANDSHAKE_SIZE - DIGEST_LENGTH ; byte [ ] message = new byte [ messageLen ] ; System . arraycopy ( handshakeMessage , handshakeOffset , message , 0 , digestPos ) ; System . arraycopy ( handshakeMessage , handshakeOffset + digestPos + DIGEST_LENGTH , message , digestPos , messageLen - digestPos ) ; calculateHMAC_SHA256 ( message , 0 , messageLen , key , keyLen , digest , digestOffset ) ; } | Calculates the digest given the its offset in the handshake data . |
6,472 | public boolean verifyDigest ( int digestPos , byte [ ] handshakeMessage , byte [ ] key , int keyLen ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "verifyDigest - digestPos: {} keyLen: {} handshake size: {} " , digestPos , keyLen , handshakeMessage . length ) ; } byte [ ] calcDigest = new byte [ DIGEST_LENGTH ] ; calculateDigest ( digestPos , handshakeMessage , 0 , key , keyLen , calcDigest , 0 ) ; if ( ! Arrays . equals ( Arrays . copyOfRange ( handshakeMessage , digestPos , ( digestPos + DIGEST_LENGTH ) ) , calcDigest ) ) { return false ; } return true ; } | Verifies the digest . |
6,473 | public void calculateHMAC_SHA256 ( byte [ ] message , int messageOffset , int messageLen , byte [ ] key , int keyLen , byte [ ] digest , int digestOffset ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "calculateHMAC_SHA256 - messageOffset: {} messageLen: {}" , messageOffset , messageLen ) ; log . trace ( "calculateHMAC_SHA256 - message: {}" , Hex . encodeHexString ( Arrays . copyOfRange ( message , messageOffset , messageOffset + messageLen ) ) ) ; log . trace ( "calculateHMAC_SHA256 - keyLen: {} key: {}" , keyLen , Hex . encodeHexString ( Arrays . copyOf ( key , keyLen ) ) ) ; } byte [ ] calcDigest ; try { Mac hmac = Mac . getInstance ( "Hmac-SHA256" , BouncyCastleProvider . PROVIDER_NAME ) ; hmac . init ( new SecretKeySpec ( Arrays . copyOf ( key , keyLen ) , "HmacSHA256" ) ) ; byte [ ] actualMessage = Arrays . copyOfRange ( message , messageOffset , messageOffset + messageLen ) ; calcDigest = hmac . doFinal ( actualMessage ) ; System . arraycopy ( calcDigest , 0 , digest , digestOffset , DIGEST_LENGTH ) ; } catch ( InvalidKeyException e ) { log . error ( "Invalid key" , e ) ; } catch ( Exception e ) { log . error ( "Hash calculation failed" , e ) ; } } | Calculates an HMAC SHA256 hash into the digest at the given offset . |
6,474 | public void calculateSwfVerification ( byte [ ] handshakeMessage , byte [ ] swfHash , int swfSize ) { byte [ ] swfHashKey = new byte [ DIGEST_LENGTH ] ; System . arraycopy ( handshakeMessage , Constants . HANDSHAKE_SIZE - DIGEST_LENGTH , swfHashKey , 0 , DIGEST_LENGTH ) ; byte [ ] bytesFromServerHash = new byte [ DIGEST_LENGTH ] ; calculateHMAC_SHA256 ( swfHash , 0 , swfHash . length , swfHashKey , DIGEST_LENGTH , bytesFromServerHash , 0 ) ; ByteBuffer swfv = ByteBuffer . allocate ( 42 ) ; swfv . put ( ( byte ) 0x01 ) ; swfv . put ( ( byte ) 0x01 ) ; swfv . putInt ( swfSize ) ; swfv . putInt ( swfSize ) ; swfv . put ( bytesFromServerHash ) ; swfv . flip ( ) ; swfVerificationBytes = new byte [ 42 ] ; swfv . get ( swfVerificationBytes ) ; log . debug ( "initialized swf verification response from swfSize: {} swfHash:\n{}\n{}" , swfSize , Hex . encodeHexString ( swfHash ) , Hex . encodeHexString ( swfVerificationBytes ) ) ; } | Calculates the swf verification token . |
6,475 | public int getDHOffset ( int algorithm , byte [ ] handshake , int bufferOffset ) { switch ( algorithm ) { case 1 : return getDHOffset2 ( handshake , bufferOffset ) ; default : case 0 : return getDHOffset1 ( handshake , bufferOffset ) ; } } | Returns the DH offset from an array of bytes . |
6,476 | public int getDigestOffset ( int algorithm , byte [ ] handshake , int bufferOffset ) { switch ( algorithm ) { case 1 : return getDigestOffset2 ( handshake , bufferOffset ) ; default : case 0 : return getDigestOffset1 ( handshake , bufferOffset ) ; } } | Returns the digest offset using current validation scheme . |
6,477 | public final static boolean validHandshakeType ( byte handshakeType ) { switch ( handshakeType ) { case RTMPConnection . RTMP_NON_ENCRYPTED : case RTMPConnection . RTMP_ENCRYPTED : case RTMPConnection . RTMP_ENCRYPTED_XTEA : case RTMPConnection . RTMP_ENCRYPTED_BLOWFISH : case RTMPConnection . RTMP_ENCRYPTED_UNK : return true ; } return false ; } | Returns whether or not a given handshake type is valid . |
6,478 | public boolean useEncryption ( ) { switch ( handshakeType ) { case RTMPConnection . RTMP_ENCRYPTED : case RTMPConnection . RTMP_ENCRYPTED_XTEA : case RTMPConnection . RTMP_ENCRYPTED_BLOWFISH : return true ; } return false ; } | Whether or not encryptions is in use . |
6,479 | public void setHandshakeType ( byte handshakeType ) { if ( log . isTraceEnabled ( ) ) { if ( handshakeType < HANDSHAKE_TYPES . length ) { log . trace ( "Setting handshake type: {}" , HANDSHAKE_TYPES [ handshakeType ] ) ; } else { log . trace ( "Invalid handshake type: {}" , handshakeType ) ; } } this . handshakeType = handshakeType ; } | Sets the handshake type . Currently only two types are supported plain and encrypted . |
6,480 | public void addBuffer ( IoBuffer in ) { byte [ ] tmp = new byte [ in . remaining ( ) ] ; in . get ( tmp ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "addBuffer - pos: {} limit: {} remain: {}" , buffer . position ( ) , buffer . limit ( ) , buffer . remaining ( ) ) ; } if ( buffer . remaining ( ) == 0 ) { buffer . clear ( ) ; } buffer . put ( tmp ) ; } | Add a IoBuffer to the buffer . |
6,481 | public byte [ ] getBuffer ( ) { buffer . flip ( ) ; byte [ ] tmp = new byte [ buffer . remaining ( ) ] ; buffer . get ( tmp ) ; buffer . clear ( ) ; return tmp ; } | Returns buffered byte array . |
6,482 | private void moveToNext ( ) { if ( controller != null ) { currentItemIndex = controller . nextItem ( this , currentItemIndex ) ; } else { currentItemIndex = defaultController . nextItem ( this , currentItemIndex ) ; } } | Move the current item to the next in list . |
6,483 | private void moveToPrevious ( ) { if ( controller != null ) { currentItemIndex = controller . previousItem ( this , currentItemIndex ) ; } else { currentItemIndex = defaultController . previousItem ( this , currentItemIndex ) ; } } | Move the current item to the previous in list . |
6,484 | public static IVideoStreamCodec getVideoCodec ( IoBuffer data ) { IVideoStreamCodec result = null ; int codecId = data . get ( ) & 0x0f ; try { switch ( codecId ) { case 2 : result = ( IVideoStreamCodec ) Class . forName ( "org.red5.codec.SorensonVideo" ) . newInstance ( ) ; break ; case 3 : result = ( IVideoStreamCodec ) Class . forName ( "org.red5.codec.ScreenVideo" ) . newInstance ( ) ; break ; case 6 : result = ( IVideoStreamCodec ) Class . forName ( "org.red5.codec.ScreenVideo2" ) . newInstance ( ) ; break ; case 7 : result = ( IVideoStreamCodec ) Class . forName ( "org.red5.codec.AVCVideo" ) . newInstance ( ) ; break ; } } catch ( Exception ex ) { log . error ( "Error creating codec instance" , ex ) ; } data . rewind ( ) ; if ( result == null ) { for ( IVideoStreamCodec storedCodec : codecs ) { IVideoStreamCodec codec ; try { codec = storedCodec . getClass ( ) . newInstance ( ) ; } catch ( Exception e ) { log . error ( "Could not create video codec instance" , e ) ; continue ; } if ( codec . canHandleData ( data ) ) { result = codec ; break ; } } } return result ; } | Create and return new video codec applicable for byte buffer data |
6,485 | private String getStreamDirectory ( IScope scope ) { final StringBuilder result = new StringBuilder ( ) ; final IScope app = ScopeUtils . findApplication ( scope ) ; final String prefix = "streams/" ; while ( scope != null && scope != app ) { result . insert ( 0 , scope . getName ( ) + "/" ) ; scope = scope . getParent ( ) ; } if ( result . length ( ) == 0 ) { return prefix ; } else { result . insert ( 0 , prefix ) . append ( '/' ) ; return result . toString ( ) ; } } | Generate stream directory based on relative scope path . The base directory is |
6,486 | public void cacheStatusObjects ( ) { cachedStatusObjects = new HashMap < String , byte [ ] > ( ) ; String statusCode ; IoBuffer out = IoBuffer . allocate ( 256 ) ; out . setAutoExpand ( true ) ; for ( String s : statusObjects . keySet ( ) ) { statusCode = s ; StatusObject statusObject = statusObjects . get ( statusCode ) ; if ( statusObject instanceof RuntimeStatusObject ) { continue ; } serializeStatusObject ( out , statusObject ) ; out . flip ( ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( HexDump . formatHexDump ( out . getHexDump ( ) ) ) ; } byte [ ] cachedBytes = new byte [ out . limit ( ) ] ; out . get ( cachedBytes ) ; out . clear ( ) ; cachedStatusObjects . put ( statusCode , cachedBytes ) ; } out . free ( ) ; out = null ; } | Cache status objects |
6,487 | public void serializeStatusObject ( IoBuffer out , StatusObject statusObject ) { Map < ? , ? > statusMap = new BeanMap ( statusObject ) ; Output output = new Output ( out ) ; Serializer . serialize ( output , statusMap ) ; } | Serializes status object |
6,488 | @ SuppressWarnings ( "unchecked" ) public void runDeadlockFuture ( Runnable deadlockGuardTask ) { if ( deadlockFuture == null ) { ThreadPoolTaskScheduler deadlockGuard = conn . getDeadlockGuardScheduler ( ) ; if ( deadlockGuard != null ) { try { deadlockFuture = ( ScheduledFuture < Runnable > ) deadlockGuard . schedule ( deadlockGuardTask , new Date ( packet . getExpirationTime ( ) ) ) ; } catch ( TaskRejectedException e ) { log . warn ( "DeadlockGuard task is rejected for {}" , sessionId , e ) ; } } else { log . debug ( "Deadlock guard is null for {}" , sessionId ) ; } } else { log . warn ( "Deadlock future is already create for {}" , sessionId ) ; } } | Runs deadlock guard task |
6,489 | public static DynamicPlayItem build ( String name , long start , long length ) { DynamicPlayItem playItem = new DynamicPlayItem ( name , start , length ) ; return playItem ; } | Builder for DynamicPlayItem |
6,490 | public Notify getMetaData ( ) { Notify md = metaData . get ( ) ; if ( md != null ) { try { return md . duplicate ( ) ; } catch ( Exception e ) { } } return md ; } | Returns a copy of the metadata for the associated stream if it exists . |
6,491 | public void setState ( StreamState newState ) { StreamState oldState = state . get ( ) ; if ( ! oldState . equals ( newState ) && state . compareAndSet ( oldState , newState ) ) { fireStateChange ( oldState , newState ) ; } } | Sets the stream state . |
6,492 | protected IStreamAwareScopeHandler getStreamAwareHandler ( ) { if ( scope != null ) { IScopeHandler handler = scope . getHandler ( ) ; if ( handler instanceof IStreamAwareScopeHandler ) { return ( IStreamAwareScopeHandler ) handler ; } } return null ; } | Return stream aware scope handler or null if scope is null . |
6,493 | public IoBuffer encode ( Object message ) throws Exception { if ( message != null ) { try { return encodePacket ( ( Packet ) message ) ; } catch ( Exception e ) { log . error ( "Error encoding" , e ) ; } } else if ( log . isDebugEnabled ( ) ) { try { String callingMethod = Thread . currentThread ( ) . getStackTrace ( ) [ 4 ] . getMethodName ( ) ; log . debug ( "Message is null at encode, expecting a Packet from: {}" , callingMethod ) ; } catch ( Throwable t ) { log . warn ( "Problem getting current calling method from stacktrace" , t ) ; } } return null ; } | Encodes object with given protocol state to byte buffer |
6,494 | public IoBuffer encodePacket ( Packet packet ) { IoBuffer out = null ; Header header = packet . getHeader ( ) ; int channelId = header . getChannelId ( ) ; IRTMPEvent message = packet . getMessage ( ) ; if ( message instanceof ChunkSize ) { ChunkSize chunkSizeMsg = ( ChunkSize ) message ; ( ( RTMPConnection ) Red5 . getConnectionLocal ( ) ) . getState ( ) . setWriteChunkSize ( chunkSizeMsg . getSize ( ) ) ; } if ( ! dropMessage ( channelId , message ) ) { IoBuffer data = encodeMessage ( header , message ) ; if ( data != null ) { RTMP rtmp = ( ( RTMPConnection ) Red5 . getConnectionLocal ( ) ) . getState ( ) ; rtmp . setLastWritePacket ( channelId , packet ) ; if ( data . position ( ) != 0 ) { data . flip ( ) ; } else { data . rewind ( ) ; } int dataLen = data . limit ( ) ; header . setSize ( dataLen ) ; int chunkSize = rtmp . getWriteChunkSize ( ) ; int numChunks = ( int ) Math . ceil ( dataLen / ( float ) chunkSize ) ; Header lastHeader = rtmp . getLastWriteHeader ( channelId ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Channel id: {} chunkSize: {}" , channelId , chunkSize ) ; } int bufSize = dataLen + 18 + ( numChunks * 2 ) ; out = IoBuffer . allocate ( bufSize , false ) ; out . setAutoExpand ( true ) ; do { encodeHeader ( header , lastHeader , out ) ; byte [ ] buf = new byte [ Math . min ( chunkSize , data . remaining ( ) ) ] ; data . get ( buf ) ; out . put ( buf ) ; lastHeader = header . clone ( ) ; } while ( data . hasRemaining ( ) ) ; lastHeader . setTimerBase ( lastHeader . getTimer ( ) ) ; lastHeader . setTimerDelta ( 0 ) ; rtmp . setLastWriteHeader ( channelId , lastHeader ) ; data . free ( ) ; out . flip ( ) ; data = null ; } } message . release ( ) ; return out ; } | Encode packet . |
6,495 | private byte getHeaderType ( final Header header , final Header lastHeader ) { if ( lastHeader == null || header . getStreamId ( ) != lastHeader . getStreamId ( ) || header . getTimer ( ) < lastHeader . getTimer ( ) ) { return HEADER_NEW ; } else if ( header . getSize ( ) != lastHeader . getSize ( ) || header . getDataType ( ) != lastHeader . getDataType ( ) ) { return HEADER_SAME_SOURCE ; } else if ( header . getTimer ( ) != lastHeader . getTimer ( ) ) { return HEADER_TIMER_CHANGE ; } return HEADER_CONTINUE ; } | Determine type of header to use . |
6,496 | private int calculateHeaderSize ( final Header header , final Header lastHeader ) { final byte headerType = getHeaderType ( header , lastHeader ) ; int channelIdAdd = 0 ; int channelId = header . getChannelId ( ) ; if ( channelId > 320 ) { channelIdAdd = 2 ; } else if ( channelId > 63 ) { channelIdAdd = 1 ; } return RTMPUtils . getHeaderLength ( headerType ) + channelIdAdd ; } | Calculate number of bytes necessary to encode the header . |
6,497 | public IoBuffer encodeHeader ( Header header , Header lastHeader ) { final IoBuffer result = IoBuffer . allocate ( calculateHeaderSize ( header , lastHeader ) ) ; encodeHeader ( header , lastHeader , result ) ; return result ; } | Encode RTMP header . |
6,498 | public void encodeHeader ( Header header , Header lastHeader , IoBuffer buf ) { byte headerType = getHeaderType ( header , lastHeader ) ; RTMPUtils . encodeHeaderByte ( buf , headerType , header . getChannelId ( ) ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "{} lastHeader: {}" , Header . HeaderType . values ( ) [ headerType ] , lastHeader ) ; } int timeBase = 0 , timeDelta = 0 ; int headerSize = header . getSize ( ) ; switch ( headerType ) { case HEADER_NEW : timeBase = header . getTimerBase ( ) ; RTMPUtils . writeMediumInt ( buf , Math . min ( timeBase , MEDIUM_INT_MAX ) ) ; RTMPUtils . writeMediumInt ( buf , headerSize ) ; buf . put ( header . getDataType ( ) ) ; RTMPUtils . writeReverseInt ( buf , header . getStreamId ( ) . intValue ( ) ) ; header . setTimerDelta ( timeDelta ) ; if ( timeBase >= MEDIUM_INT_MAX ) { buf . putInt ( timeBase ) ; header . setExtended ( true ) ; } RTMPConnection conn = ( RTMPConnection ) Red5 . getConnectionLocal ( ) ; if ( conn != null ) { conn . getState ( ) . setLastFullTimestampWritten ( header . getChannelId ( ) , timeBase ) ; } break ; case HEADER_SAME_SOURCE : timeDelta = ( int ) RTMPUtils . diffTimestamps ( header . getTimer ( ) , lastHeader . getTimer ( ) ) ; header . setTimerDelta ( timeDelta ) ; RTMPUtils . writeMediumInt ( buf , Math . min ( timeDelta , MEDIUM_INT_MAX ) ) ; RTMPUtils . writeMediumInt ( buf , headerSize ) ; buf . put ( header . getDataType ( ) ) ; if ( timeDelta >= MEDIUM_INT_MAX ) { buf . putInt ( timeDelta ) ; header . setExtended ( true ) ; } timeBase = header . getTimerBase ( ) - timeDelta ; header . setTimerBase ( timeBase ) ; break ; case HEADER_TIMER_CHANGE : timeDelta = ( int ) RTMPUtils . diffTimestamps ( header . getTimer ( ) , lastHeader . getTimer ( ) ) ; header . setTimerDelta ( timeDelta ) ; RTMPUtils . writeMediumInt ( buf , Math . min ( timeDelta , MEDIUM_INT_MAX ) ) ; if ( timeDelta >= MEDIUM_INT_MAX ) { buf . putInt ( timeDelta ) ; header . setExtended ( true ) ; } timeBase = header . getTimerBase ( ) - timeDelta ; header . setTimerBase ( timeBase ) ; break ; case HEADER_CONTINUE : timeBase = header . getTimerBase ( ) - timeDelta ; if ( lastHeader . isExtended ( ) ) { buf . putInt ( timeBase ) ; } break ; default : break ; } log . trace ( "Encoded chunk {} {}" , Header . HeaderType . values ( ) [ headerType ] , header ) ; } | Encode RTMP header into given IoBuffer . |
6,499 | private IoBuffer encodeServerBW ( ServerBW serverBW ) { final IoBuffer out = IoBuffer . allocate ( 4 ) ; out . putInt ( serverBW . getBandwidth ( ) ) ; return out ; } | Encode server - side bandwidth event . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.