repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Red5/red5-server-common | src/main/java/org/red5/server/stream/consumer/SlicedFileConsumer.java | SlicedFileConsumer.doWrites | 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();
}
// sort
Arrays.sort(slice);
// write
doWrites(slice);
} | java | 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();
}
// sort
Arrays.sort(slice);
// write
doWrites(slice);
} | [
"public",
"final",
"void",
"doWrites",
"(",
")",
"{",
"QueuedMediaData",
"[",
"]",
"slice",
"=",
"null",
";",
"writeLock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"slice",
"=",
"queue",
".",
"toArray",
"(",
"new",
"QueuedMediaData",
"[",
"0",
"]",
")... | Write all the queued items to the writer. | [
"Write",
"all",
"the",
"queued",
"items",
"to",
"the",
"writer",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/consumer/SlicedFileConsumer.java#L531-L546 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/consumer/SlicedFileConsumer.java | SlicedFileConsumer.doWrites | public final void doWrites(QueuedMediaData[] slice) {
// empty the queue
for (QueuedMediaData queued : slice) {
int tmpTs = queued.getTimestamp();
if (lastWrittenTs <= tmpTs) {
if (queued.hasData()) {
// write the data
write(queued);
lastWrittenTs = tmpTs;
// clear the data, because we're done with it
queued.dispose();
} else {
if (log.isTraceEnabled()) {
log.trace("Queued data was not available");
}
}
} else {
// clear the data, since its too old
queued.dispose();
}
}
// clear and null-out
slice = null;
} | java | public final void doWrites(QueuedMediaData[] slice) {
// empty the queue
for (QueuedMediaData queued : slice) {
int tmpTs = queued.getTimestamp();
if (lastWrittenTs <= tmpTs) {
if (queued.hasData()) {
// write the data
write(queued);
lastWrittenTs = tmpTs;
// clear the data, because we're done with it
queued.dispose();
} else {
if (log.isTraceEnabled()) {
log.trace("Queued data was not available");
}
}
} else {
// clear the data, since its too old
queued.dispose();
}
}
// clear and null-out
slice = null;
} | [
"public",
"final",
"void",
"doWrites",
"(",
"QueuedMediaData",
"[",
"]",
"slice",
")",
"{",
"// empty the queue\r",
"for",
"(",
"QueuedMediaData",
"queued",
":",
"slice",
")",
"{",
"int",
"tmpTs",
"=",
"queued",
".",
"getTimestamp",
"(",
")",
";",
"if",
"(... | Write a slice of the queued items to the writer.
@param slice
set of queued data | [
"Write",
"a",
"slice",
"of",
"the",
"queued",
"items",
"to",
"the",
"writer",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/consumer/SlicedFileConsumer.java#L554-L577 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/consumer/SlicedFileConsumer.java | SlicedFileConsumer.setupOutputPath | public void setupOutputPath(String name) {
// get stream filename generator
IStreamFilenameGenerator generator = (IStreamFilenameGenerator) ScopeUtils.getScopeService(scope, IStreamFilenameGenerator.class, DefaultStreamFilenameGenerator.class);
// generate file path
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);
// if append was requested, ensure the file we want to append exists (append==record)
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);
}
}
} | java | public void setupOutputPath(String name) {
// get stream filename generator
IStreamFilenameGenerator generator = (IStreamFilenameGenerator) ScopeUtils.getScopeService(scope, IStreamFilenameGenerator.class, DefaultStreamFilenameGenerator.class);
// generate file path
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);
// if append was requested, ensure the file we want to append exists (append==record)
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);
}
}
} | [
"public",
"void",
"setupOutputPath",
"(",
"String",
"name",
")",
"{",
"// get stream filename generator\r",
"IStreamFilenameGenerator",
"generator",
"=",
"(",
"IStreamFilenameGenerator",
")",
"ScopeUtils",
".",
"getScopeService",
"(",
"scope",
",",
"IStreamFilenameGenerator... | Sets up the output file path for writing.
@param name output filename to use | [
"Sets",
"up",
"the",
"output",
"file",
"path",
"for",
"writing",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/consumer/SlicedFileConsumer.java#L682-L701 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/consumer/SlicedFileConsumer.java | SlicedFileConsumer.setVideoDecoderConfiguration | public void setVideoDecoderConfiguration(IRTMPEvent decoderConfig) {
if (decoderConfig instanceof IStreamData) {
IoBuffer data = ((IStreamData<?>) decoderConfig).getData().asReadOnlyBuffer();
videoConfigurationTag = ImmutableTag.build(decoderConfig.getDataType(), 0, data, 0);
}
} | java | public void setVideoDecoderConfiguration(IRTMPEvent decoderConfig) {
if (decoderConfig instanceof IStreamData) {
IoBuffer data = ((IStreamData<?>) decoderConfig).getData().asReadOnlyBuffer();
videoConfigurationTag = ImmutableTag.build(decoderConfig.getDataType(), 0, data, 0);
}
} | [
"public",
"void",
"setVideoDecoderConfiguration",
"(",
"IRTMPEvent",
"decoderConfig",
")",
"{",
"if",
"(",
"decoderConfig",
"instanceof",
"IStreamData",
")",
"{",
"IoBuffer",
"data",
"=",
"(",
"(",
"IStreamData",
"<",
"?",
">",
")",
"decoderConfig",
")",
".",
... | Sets a video decoder configuration; some codecs require this, such as AVC.
@param decoderConfig
video codec configuration | [
"Sets",
"a",
"video",
"decoder",
"configuration",
";",
"some",
"codecs",
"require",
"this",
"such",
"as",
"AVC",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/consumer/SlicedFileConsumer.java#L709-L714 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/consumer/SlicedFileConsumer.java | SlicedFileConsumer.setAudioDecoderConfiguration | public void setAudioDecoderConfiguration(IRTMPEvent decoderConfig) {
if (decoderConfig instanceof IStreamData) {
IoBuffer data = ((IStreamData<?>) decoderConfig).getData().asReadOnlyBuffer();
audioConfigurationTag = ImmutableTag.build(decoderConfig.getDataType(), 0, data, 0);
}
} | java | public void setAudioDecoderConfiguration(IRTMPEvent decoderConfig) {
if (decoderConfig instanceof IStreamData) {
IoBuffer data = ((IStreamData<?>) decoderConfig).getData().asReadOnlyBuffer();
audioConfigurationTag = ImmutableTag.build(decoderConfig.getDataType(), 0, data, 0);
}
} | [
"public",
"void",
"setAudioDecoderConfiguration",
"(",
"IRTMPEvent",
"decoderConfig",
")",
"{",
"if",
"(",
"decoderConfig",
"instanceof",
"IStreamData",
")",
"{",
"IoBuffer",
"data",
"=",
"(",
"(",
"IStreamData",
"<",
"?",
">",
")",
"decoderConfig",
")",
".",
... | Sets a audio decoder configuration; some codecs require this, such as AAC.
@param decoderConfig
audio codec configuration | [
"Sets",
"a",
"audio",
"decoder",
"configuration",
";",
"some",
"codecs",
"require",
"this",
"such",
"as",
"AAC",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/consumer/SlicedFileConsumer.java#L722-L727 | train |
Red5/red5-server-common | src/main/java/org/red5/server/Client.java | Client.disconnect | 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());
// close all connections held to Red5 by client
for (IConnection con : getConnections()) {
try {
con.close();
} catch (Exception e) {
// closing a connection calls into application code, so exception possible
log.error("Unexpected exception closing connection {}", e);
}
}
} else {
log.debug("Connection map is empty or null");
}
// unregister client
removeInstance();
}
} | java | 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());
// close all connections held to Red5 by client
for (IConnection con : getConnections()) {
try {
con.close();
} catch (Exception e) {
// closing a connection calls into application code, so exception possible
log.error("Unexpected exception closing connection {}", e);
}
}
} else {
log.debug("Connection map is empty or null");
}
// unregister client
removeInstance();
}
} | [
"public",
"void",
"disconnect",
"(",
")",
"{",
"if",
"(",
"disconnected",
".",
"compareAndSet",
"(",
"false",
",",
"true",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Disconnect - id: {}\"",
",",
"id",
")",
";",
"if",
"(",
"connections",
"!=",
"null",
... | Disconnects client from Red5 application | [
"Disconnects",
"client",
"from",
"Red5",
"application"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/Client.java#L139-L159 | train |
Red5/red5-server-common | src/main/java/org/red5/server/Client.java | Client.getConnections | 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();
} | java | 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();
} | [
"public",
"Set",
"<",
"IConnection",
">",
"getConnections",
"(",
"IScope",
"scope",
")",
"{",
"if",
"(",
"scope",
"==",
"null",
")",
"{",
"return",
"getConnections",
"(",
")",
";",
"}",
"Set",
"<",
"IClient",
">",
"scopeClients",
"=",
"scope",
".",
"ge... | Return client connections to given scope
@param scope
Scope
@return Set of connections for that scope | [
"Return",
"client",
"connections",
"to",
"given",
"scope"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/Client.java#L177-L190 | train |
Red5/red5-server-common | src/main/java/org/red5/server/Client.java | Client.iterateScopeNameList | 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;
} | java | 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;
} | [
"public",
"List",
"<",
"String",
">",
"iterateScopeNameList",
"(",
")",
"{",
"log",
".",
"debug",
"(",
"\"iterateScopeNameList called\"",
")",
";",
"Collection",
"<",
"IScope",
">",
"scopes",
"=",
"getScopes",
"(",
")",
";",
"log",
".",
"debug",
"(",
"\"Sc... | Iterate through the scopes and their attributes. Used by JMX
@return list of scope attributes | [
"Iterate",
"through",
"the",
"scopes",
"and",
"their",
"attributes",
".",
"Used",
"by",
"JMX"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/Client.java#L227-L242 | train |
Red5/red5-server-common | src/main/java/org/red5/server/Client.java | Client.register | 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);
}
} | java | 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);
}
} | [
"protected",
"void",
"register",
"(",
"IConnection",
"conn",
")",
"{",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"if",
"(",
"conn",
"==",
"null",
")",
"{",
"log",
".",
"debug",
"(",
"\"Register null connection, client id: {}\"",
",",
"id... | Associate connection with client
@param conn
Connection object | [
"Associate",
"connection",
"with",
"client"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/Client.java#L261-L280 | train |
Red5/red5-server-common | src/main/java/org/red5/server/Client.java | Client.unregister | protected void unregister(IConnection conn, boolean deleteIfNoConns) {
log.debug("Unregister connection ({}:{}) client id: {}", conn.getRemoteAddress(), conn.getRemotePort(), id);
// remove connection from connected scopes list
connections.remove(conn);
// If client is not connected to any scope any longer then remove
if (deleteIfNoConns && connections.isEmpty()) {
// TODO DW dangerous the way this is called from BaseConnection.initialize(). Could we unexpectedly pop a Client out of the registry?
removeInstance();
}
} | java | protected void unregister(IConnection conn, boolean deleteIfNoConns) {
log.debug("Unregister connection ({}:{}) client id: {}", conn.getRemoteAddress(), conn.getRemotePort(), id);
// remove connection from connected scopes list
connections.remove(conn);
// If client is not connected to any scope any longer then remove
if (deleteIfNoConns && connections.isEmpty()) {
// TODO DW dangerous the way this is called from BaseConnection.initialize(). Could we unexpectedly pop a Client out of the registry?
removeInstance();
}
} | [
"protected",
"void",
"unregister",
"(",
"IConnection",
"conn",
",",
"boolean",
"deleteIfNoConns",
")",
"{",
"log",
".",
"debug",
"(",
"\"Unregister connection ({}:{}) client id: {}\"",
",",
"conn",
".",
"getRemoteAddress",
"(",
")",
",",
"conn",
".",
"getRemotePort"... | Removes client-connection association for given connection
@param conn
Connection object
@param deleteIfNoConns
Whether to delete this client if it no longer has any connections | [
"Removes",
"client",
"-",
"connection",
"association",
"for",
"given",
"connection"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/Client.java#L300-L309 | train |
Red5/red5-server-common | src/main/java/org/red5/server/Client.java | Client.removeInstance | private void removeInstance() {
// unregister client
ClientRegistry ref = registry.get();
if (ref != null) {
ref.removeClient(this);
} else {
log.warn("Client registry reference was not accessable, removal failed");
// TODO: attempt to lookup the registry via the global.clientRegistry
}
} | java | private void removeInstance() {
// unregister client
ClientRegistry ref = registry.get();
if (ref != null) {
ref.removeClient(this);
} else {
log.warn("Client registry reference was not accessable, removal failed");
// TODO: attempt to lookup the registry via the global.clientRegistry
}
} | [
"private",
"void",
"removeInstance",
"(",
")",
"{",
"// unregister client\r",
"ClientRegistry",
"ref",
"=",
"registry",
".",
"get",
"(",
")",
";",
"if",
"(",
"ref",
"!=",
"null",
")",
"{",
"ref",
".",
"removeClient",
"(",
"this",
")",
";",
"}",
"else",
... | Removes this instance from the client registry. | [
"Removes",
"this",
"instance",
"from",
"the",
"client",
"registry",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/Client.java#L386-L395 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.addChildScope | 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) {
// if child scope has no persistence store, use same class as parent
try {
if (scope instanceof Scope) {
((Scope) scope).setPersistenceClass(persistenceClass);
}
} catch (Exception error) {
log.error("Could not set persistence class", error);
}
}
return added;
} | java | 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) {
// if child scope has no persistence store, use same class as parent
try {
if (scope instanceof Scope) {
((Scope) scope).setPersistenceClass(persistenceClass);
}
} catch (Exception error) {
log.error("Could not set persistence class", error);
}
}
return added;
} | [
"public",
"boolean",
"addChildScope",
"(",
"IBasicScope",
"scope",
")",
"{",
"log",
".",
"debug",
"(",
"\"Add child: {}\"",
",",
"scope",
")",
";",
"boolean",
"added",
"=",
"false",
";",
"if",
"(",
"scope",
".",
"isValid",
"(",
")",
")",
"{",
"try",
"{... | Add child scope to this scope
@param scope Child scope
@return true on success (if scope has handler and it accepts child scope addition), false otherwise | [
"Add",
"child",
"scope",
"to",
"this",
"scope"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L194-L222 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.connect | 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");
// timeout while connecting client
return false;
}
final IClient client = conn.getClient();
// we would not get this far if there is no handler
if (hasHandler() && !getHandler().join(client, this)) {
return false;
}
// checking the connection again? why?
if (!conn.isConnected()) {
// timeout while connecting client
return false;
}
// add the client and event listener
if (clients.add(client) && addEventListener(conn)) {
log.debug("Added client");
// increment conn stats
connectionStats.increment();
// get connected scope
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;
} | java | 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");
// timeout while connecting client
return false;
}
final IClient client = conn.getClient();
// we would not get this far if there is no handler
if (hasHandler() && !getHandler().join(client, this)) {
return false;
}
// checking the connection again? why?
if (!conn.isConnected()) {
// timeout while connecting client
return false;
}
// add the client and event listener
if (clients.add(client) && addEventListener(conn)) {
log.debug("Added client");
// increment conn stats
connectionStats.increment();
// get connected scope
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;
} | [
"public",
"boolean",
"connect",
"(",
"IConnection",
"conn",
",",
"Object",
"[",
"]",
"params",
")",
"{",
"log",
".",
"debug",
"(",
"\"Connect - scope: {} connection: {}\"",
",",
"this",
",",
"conn",
")",
";",
"if",
"(",
"enabled",
")",
"{",
"if",
"(",
"h... | 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.
@param conn Connection object
@param params Parameters passed with connection
@return true on success, false otherwise | [
"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... | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L241-L287 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.createChildScope | public boolean createChildScope(String name) {
// quick lookup by 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;
} | java | public boolean createChildScope(String name) {
// quick lookup by 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;
} | [
"public",
"boolean",
"createChildScope",
"(",
"String",
"name",
")",
"{",
"// quick lookup by name\r",
"log",
".",
"debug",
"(",
"\"createChildScope: {}\"",
",",
"name",
")",
";",
"if",
"(",
"children",
".",
"hasName",
"(",
"name",
")",
")",
"{",
"log",
".",... | Create child scope of room type, with the given name.
@param name child scope name
@return true on success, false otherwise | [
"Create",
"child",
"scope",
"of",
"room",
"type",
"with",
"the",
"given",
"name",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L295-L304 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.disconnect | public void disconnect(IConnection conn) {
log.debug("Disconnect: {}", conn);
// call disconnect handlers in reverse order of connection. ie. roomDisconnect is called before appDisconnect.
final IClient client = conn.getClient();
if (client == null) {
// early bail out
removeEventListener(conn);
connectionStats.decrement();
if (hasParent()) {
parent.disconnect(conn);
}
return;
}
// remove it if it exists
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 {
// there may be a timeout here ?
handler.leave(client, this);
} catch (Exception e) {
log.error("Error while executing \"leave\" for client {} on handler {}. {}", new Object[] { conn, handler, e });
}
}
// remove listener
removeEventListener(conn);
// decrement if there was a set of connections
connectionStats.decrement();
if (this.equals(conn.getScope())) {
final IServer server = getServer();
if (server instanceof Server) {
((Server) server).notifyDisconnected(conn);
}
}
}
if (hasParent()) {
parent.disconnect(conn);
}
} | java | public void disconnect(IConnection conn) {
log.debug("Disconnect: {}", conn);
// call disconnect handlers in reverse order of connection. ie. roomDisconnect is called before appDisconnect.
final IClient client = conn.getClient();
if (client == null) {
// early bail out
removeEventListener(conn);
connectionStats.decrement();
if (hasParent()) {
parent.disconnect(conn);
}
return;
}
// remove it if it exists
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 {
// there may be a timeout here ?
handler.leave(client, this);
} catch (Exception e) {
log.error("Error while executing \"leave\" for client {} on handler {}. {}", new Object[] { conn, handler, e });
}
}
// remove listener
removeEventListener(conn);
// decrement if there was a set of connections
connectionStats.decrement();
if (this.equals(conn.getScope())) {
final IServer server = getServer();
if (server instanceof Server) {
((Server) server).notifyDisconnected(conn);
}
}
}
if (hasParent()) {
parent.disconnect(conn);
}
} | [
"public",
"void",
"disconnect",
"(",
"IConnection",
"conn",
")",
"{",
"log",
".",
"debug",
"(",
"\"Disconnect: {}\"",
",",
"conn",
")",
";",
"// call disconnect handlers in reverse order of connection. ie. roomDisconnect is called before appDisconnect.\r",
"final",
"IClient",
... | Disconnect connection from scope
@param conn Connection object | [
"Disconnect",
"connection",
"from",
"scope"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L334-L377 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getBroadcastScope | public IBroadcastScope getBroadcastScope(String name) {
return (IBroadcastScope) children.getBasicScope(ScopeType.BROADCAST, name);
} | java | public IBroadcastScope getBroadcastScope(String name) {
return (IBroadcastScope) children.getBasicScope(ScopeType.BROADCAST, name);
} | [
"public",
"IBroadcastScope",
"getBroadcastScope",
"(",
"String",
"name",
")",
"{",
"return",
"(",
"IBroadcastScope",
")",
"children",
".",
"getBasicScope",
"(",
"ScopeType",
".",
"BROADCAST",
",",
"name",
")",
";",
"}"
] | Return the broadcast scope for a given name
@param name
name
@return broadcast scope or null if not found | [
"Return",
"the",
"broadcast",
"scope",
"for",
"a",
"given",
"name"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L444-L446 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getBasicScope | public IBasicScope getBasicScope(ScopeType type, String name) {
return children.getBasicScope(type, name);
} | java | public IBasicScope getBasicScope(ScopeType type, String name) {
return children.getBasicScope(type, name);
} | [
"public",
"IBasicScope",
"getBasicScope",
"(",
"ScopeType",
"type",
",",
"String",
"name",
")",
"{",
"return",
"children",
".",
"getBasicScope",
"(",
"type",
",",
"name",
")",
";",
"}"
] | Return base scope of given type with given name
@param type Scope type
@param name Scope name
@return Basic scope object | [
"Return",
"base",
"scope",
"of",
"given",
"type",
"with",
"given",
"name"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L455-L457 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getBasicScopeNames | 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();
} | java | 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();
} | [
"public",
"Set",
"<",
"String",
">",
"getBasicScopeNames",
"(",
"ScopeType",
"type",
")",
"{",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"Set",
"<",
"String",
">",
"names",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"for",
"(",
"IBa... | Return basic scope names matching given type
@param type Scope type
@return set of scope names | [
"Return",
"basic",
"scope",
"names",
"matching",
"given",
"type"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L465-L476 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getDepth | @Override
public int getDepth() {
if (depth == UNSET) {
if (hasParent()) {
depth = parent.getDepth() + 1;
} else {
depth = 0;
}
}
return depth;
} | java | @Override
public int getDepth() {
if (depth == UNSET) {
if (hasParent()) {
depth = parent.getDepth() + 1;
} else {
depth = 0;
}
}
return depth;
} | [
"@",
"Override",
"public",
"int",
"getDepth",
"(",
")",
"{",
"if",
"(",
"depth",
"==",
"UNSET",
")",
"{",
"if",
"(",
"hasParent",
"(",
")",
")",
"{",
"depth",
"=",
"parent",
".",
"getDepth",
"(",
")",
"+",
"1",
";",
"}",
"else",
"{",
"depth",
"... | return scope depth
@return Scope depth | [
"return",
"scope",
"depth"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L594-L604 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getHandler | public IScopeHandler getHandler() {
log.trace("getHandler from {}", name);
if (handler != null) {
return handler;
} else if (hasParent()) {
return getParent().getHandler();
} else {
return null;
}
} | java | public IScopeHandler getHandler() {
log.trace("getHandler from {}", name);
if (handler != null) {
return handler;
} else if (hasParent()) {
return getParent().getHandler();
} else {
return null;
}
} | [
"public",
"IScopeHandler",
"getHandler",
"(",
")",
"{",
"log",
".",
"trace",
"(",
"\"getHandler from {}\"",
",",
"name",
")",
";",
"if",
"(",
"handler",
"!=",
"null",
")",
"{",
"return",
"handler",
";",
"}",
"else",
"if",
"(",
"hasParent",
"(",
")",
")... | Return scope handler or parent's scope handler if this scope doesn't have one.
@return Scope handler (or parent's one) | [
"Return",
"scope",
"handler",
"or",
"parent",
"s",
"scope",
"handler",
"if",
"this",
"scope",
"doesn",
"t",
"have",
"one",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L611-L620 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getResource | public Resource getResource(String path) {
if (hasContext()) {
return context.getResource(path);
}
return getContext().getResource(getContextPath() + '/' + path);
} | java | public Resource getResource(String path) {
if (hasContext()) {
return context.getResource(path);
}
return getContext().getResource(getContextPath() + '/' + path);
} | [
"public",
"Resource",
"getResource",
"(",
"String",
"path",
")",
"{",
"if",
"(",
"hasContext",
"(",
")",
")",
"{",
"return",
"context",
".",
"getResource",
"(",
"path",
")",
";",
"}",
"return",
"getContext",
"(",
")",
".",
"getResource",
"(",
"getContext... | Return resource located at given path
@param path Resource path
@return Resource | [
"Return",
"resource",
"located",
"at",
"given",
"path"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L667-L672 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getResources | public Resource[] getResources(String path) throws IOException {
if (hasContext()) {
return context.getResources(path);
}
return getContext().getResources(getContextPath() + '/' + path);
} | java | public Resource[] getResources(String path) throws IOException {
if (hasContext()) {
return context.getResources(path);
}
return getContext().getResources(getContextPath() + '/' + path);
} | [
"public",
"Resource",
"[",
"]",
"getResources",
"(",
"String",
"path",
")",
"throws",
"IOException",
"{",
"if",
"(",
"hasContext",
"(",
")",
")",
"{",
"return",
"context",
".",
"getResources",
"(",
"path",
")",
";",
"}",
"return",
"getContext",
"(",
")",... | Return array of resources from path string, usually used with pattern path
@param path Resources path
@return Resources
@throws IOException I/O exception | [
"Return",
"array",
"of",
"resources",
"from",
"path",
"string",
"usually",
"used",
"with",
"pattern",
"path"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L681-L686 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getScope | 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;
} | java | 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;
} | [
"public",
"IScope",
"getScope",
"(",
"String",
"name",
")",
"{",
"IBasicScope",
"child",
"=",
"children",
".",
"getBasicScope",
"(",
"ScopeType",
".",
"UNDEFINED",
",",
"name",
")",
";",
"log",
".",
"debug",
"(",
"\"Child of {}: {}\"",
",",
"this",
".",
"n... | Return child scope by name
@param name Scope name
@return Child scope with given name | [
"Return",
"child",
"scope",
"by",
"name"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L694-L704 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getServiceHandler | public Object getServiceHandler(String name) {
Map<String, Object> serviceHandlers = getServiceHandlers(false);
if (serviceHandlers == null) {
return null;
}
return serviceHandlers.get(name);
} | java | public Object getServiceHandler(String name) {
Map<String, Object> serviceHandlers = getServiceHandlers(false);
if (serviceHandlers == null) {
return null;
}
return serviceHandlers.get(name);
} | [
"public",
"Object",
"getServiceHandler",
"(",
"String",
"name",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"serviceHandlers",
"=",
"getServiceHandlers",
"(",
"false",
")",
";",
"if",
"(",
"serviceHandlers",
"==",
"null",
")",
"{",
"return",
"null",
... | Return service handler by name
@param name Handler name
@return Service handler with given name | [
"Return",
"service",
"handler",
"by",
"name"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L722-L728 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getServiceHandlerNames | @SuppressWarnings("unchecked")
public Set<String> getServiceHandlerNames() {
Map<String, Object> serviceHandlers = getServiceHandlers(false);
if (serviceHandlers == null) {
return Collections.EMPTY_SET;
}
return serviceHandlers.keySet();
} | java | @SuppressWarnings("unchecked")
public Set<String> getServiceHandlerNames() {
Map<String, Object> serviceHandlers = getServiceHandlers(false);
if (serviceHandlers == null) {
return Collections.EMPTY_SET;
}
return serviceHandlers.keySet();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"Set",
"<",
"String",
">",
"getServiceHandlerNames",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"serviceHandlers",
"=",
"getServiceHandlers",
"(",
"false",
")",
";",
"if",
"(",
"serv... | Return set of service handler names. Removing entries from the set unregisters the corresponding service handler.
@return Set of service handler names | [
"Return",
"set",
"of",
"service",
"handler",
"names",
".",
"Removing",
"entries",
"from",
"the",
"set",
"unregisters",
"the",
"corresponding",
"service",
"handler",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L735-L742 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getServiceHandlers | protected Map<String, Object> getServiceHandlers(boolean allowCreate) {
if (serviceHandlers == null) {
if (allowCreate) {
serviceHandlers = new ConcurrentHashMap<String, Object>(3, 0.9f, 1);
}
}
return serviceHandlers;
} | java | protected Map<String, Object> getServiceHandlers(boolean allowCreate) {
if (serviceHandlers == null) {
if (allowCreate) {
serviceHandlers = new ConcurrentHashMap<String, Object>(3, 0.9f, 1);
}
}
return serviceHandlers;
} | [
"protected",
"Map",
"<",
"String",
",",
"Object",
">",
"getServiceHandlers",
"(",
"boolean",
"allowCreate",
")",
"{",
"if",
"(",
"serviceHandlers",
"==",
"null",
")",
"{",
"if",
"(",
"allowCreate",
")",
"{",
"serviceHandlers",
"=",
"new",
"ConcurrentHashMap",
... | Return map of service handlers and optionally created it if it doesn't exist.
@param allowCreate Should the map be created if it doesn't exist?
@return Map of service handlers | [
"Return",
"map",
"of",
"service",
"handlers",
"and",
"optionally",
"created",
"it",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L759-L766 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.hasChildScope | public boolean hasChildScope(ScopeType type, String name) {
log.debug("Has child scope? {} in {}", name, this);
return children.getBasicScope(type, name) != null;
} | java | public boolean hasChildScope(ScopeType type, String name) {
log.debug("Has child scope? {} in {}", name, this);
return children.getBasicScope(type, name) != null;
} | [
"public",
"boolean",
"hasChildScope",
"(",
"ScopeType",
"type",
",",
"String",
"name",
")",
"{",
"log",
".",
"debug",
"(",
"\"Has child scope? {} in {}\"",
",",
"name",
",",
"this",
")",
";",
"return",
"children",
".",
"getBasicScope",
"(",
"type",
",",
"nam... | Check whether scope has child scope with given name and type
@param type Child scope type
@param name Child scope name
@return true if scope has child node with given name and type, false otherwise | [
"Check",
"whether",
"scope",
"has",
"child",
"scope",
"with",
"given",
"name",
"and",
"type"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L818-L821 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.init | 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");
//throw new ScopeException("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();
}
} | java | 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");
//throw new ScopeException("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();
}
} | [
"public",
"void",
"init",
"(",
")",
"{",
"log",
".",
"debug",
"(",
"\"Init scope: {} parent: {}\"",
",",
"name",
",",
"parent",
")",
";",
"if",
"(",
"hasParent",
"(",
")",
")",
"{",
"if",
"(",
"!",
"parent",
".",
"hasChildScope",
"(",
"name",
")",
")... | Initialization actions, start if autostart is set to true. | [
"Initialization",
"actions",
"start",
"if",
"autostart",
"is",
"set",
"to",
"true",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L854-L874 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.uninit | 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);
}
}
} | java | 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);
}
}
} | [
"public",
"void",
"uninit",
"(",
")",
"{",
"log",
".",
"debug",
"(",
"\"Un-init scope\"",
")",
";",
"for",
"(",
"IBasicScope",
"child",
":",
"children",
".",
"keySet",
"(",
")",
")",
"{",
"if",
"(",
"child",
"instanceof",
"Scope",
")",
"{",
"(",
"(",... | Uninitialize scope and unregister from parent. | [
"Uninitialize",
"scope",
"and",
"unregister",
"from",
"parent",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L879-L893 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.registerServiceHandler | public void registerServiceHandler(String name, Object handler) {
Map<String, Object> serviceHandlers = getServiceHandlers();
serviceHandlers.put(name, handler);
} | java | public void registerServiceHandler(String name, Object handler) {
Map<String, Object> serviceHandlers = getServiceHandlers();
serviceHandlers.put(name, handler);
} | [
"public",
"void",
"registerServiceHandler",
"(",
"String",
"name",
",",
"Object",
"handler",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"serviceHandlers",
"=",
"getServiceHandlers",
"(",
")",
";",
"serviceHandlers",
".",
"put",
"(",
"name",
",",
"ha... | Register service handler by name
@param name Service handler name
@param handler Service handler | [
"Register",
"service",
"handler",
"by",
"name"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L933-L936 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.removeChildScope | public void removeChildScope(IBasicScope scope) {
log.debug("removeChildScope: {}", scope);
if (children.containsKey(scope)) {
// remove from parent
children.remove(scope);
if (scope instanceof Scope) {
unregisterJMX();
}
}
} | java | public void removeChildScope(IBasicScope scope) {
log.debug("removeChildScope: {}", scope);
if (children.containsKey(scope)) {
// remove from parent
children.remove(scope);
if (scope instanceof Scope) {
unregisterJMX();
}
}
} | [
"public",
"void",
"removeChildScope",
"(",
"IBasicScope",
"scope",
")",
"{",
"log",
".",
"debug",
"(",
"\"removeChildScope: {}\"",
",",
"scope",
")",
";",
"if",
"(",
"children",
".",
"containsKey",
"(",
"scope",
")",
")",
"{",
"// remove from parent\r",
"child... | Removes child scope
@param scope Child scope to remove | [
"Removes",
"child",
"scope"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L943-L952 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.removeChildren | public void removeChildren() {
log.trace("removeChildren of {}", name);
for (IBasicScope child : children.keySet()) {
removeChildScope(child);
}
} | java | public void removeChildren() {
log.trace("removeChildren of {}", name);
for (IBasicScope child : children.keySet()) {
removeChildScope(child);
}
} | [
"public",
"void",
"removeChildren",
"(",
")",
"{",
"log",
".",
"trace",
"(",
"\"removeChildren of {}\"",
",",
"name",
")",
";",
"for",
"(",
"IBasicScope",
"child",
":",
"children",
".",
"keySet",
"(",
")",
")",
"{",
"removeChildScope",
"(",
"child",
")",
... | Removes all the child scopes | [
"Removes",
"all",
"the",
"child",
"scopes"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L957-L962 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.setHandler | public void setHandler(IScopeHandler handler) {
log.debug("setHandler: {} on {}", handler, name);
this.handler = handler;
if (handler instanceof IScopeAware) {
((IScopeAware) handler).setScope(this);
}
} | java | public void setHandler(IScopeHandler handler) {
log.debug("setHandler: {} on {}", handler, name);
this.handler = handler;
if (handler instanceof IScopeAware) {
((IScopeAware) handler).setScope(this);
}
} | [
"public",
"void",
"setHandler",
"(",
"IScopeHandler",
"handler",
")",
"{",
"log",
".",
"debug",
"(",
"\"setHandler: {} on {}\"",
",",
"handler",
",",
"name",
")",
";",
"this",
".",
"handler",
"=",
"handler",
";",
"if",
"(",
"handler",
"instanceof",
"IScopeAw... | Setter for scope event handler
@param handler
Event handler | [
"Setter",
"for",
"scope",
"event",
"handler"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L1016-L1022 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.setName | @Override
public final void setName(String name) {
log.debug("Set name: {}", name);
if (this.name == null && StringUtils.isNotBlank(name)) {
// reset of the name is no longer allowed
this.name = name;
// unregister from jmx
if (oName != null) {
unregisterJMX();
}
// register
registerJMX();
} else {
log.info("Scope {} name reset to: {} disallowed", this.name, name);
}
} | java | @Override
public final void setName(String name) {
log.debug("Set name: {}", name);
if (this.name == null && StringUtils.isNotBlank(name)) {
// reset of the name is no longer allowed
this.name = name;
// unregister from jmx
if (oName != null) {
unregisterJMX();
}
// register
registerJMX();
} else {
log.info("Scope {} name reset to: {} disallowed", this.name, name);
}
} | [
"@",
"Override",
"public",
"final",
"void",
"setName",
"(",
"String",
"name",
")",
"{",
"log",
".",
"debug",
"(",
"\"Set name: {}\"",
",",
"name",
")",
";",
"if",
"(",
"this",
".",
"name",
"==",
"null",
"&&",
"StringUtils",
".",
"isNotBlank",
"(",
"nam... | Setter for scope name
@param name
Scope name | [
"Setter",
"for",
"scope",
"name"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L1030-L1045 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.setPersistenceClass | public void setPersistenceClass(String persistenceClass) throws Exception {
this.persistenceClass = persistenceClass;
if (persistenceClass != null) {
store = PersistenceUtils.getPersistenceStore(this, persistenceClass);
}
} | java | public void setPersistenceClass(String persistenceClass) throws Exception {
this.persistenceClass = persistenceClass;
if (persistenceClass != null) {
store = PersistenceUtils.getPersistenceStore(this, persistenceClass);
}
} | [
"public",
"void",
"setPersistenceClass",
"(",
"String",
"persistenceClass",
")",
"throws",
"Exception",
"{",
"this",
".",
"persistenceClass",
"=",
"persistenceClass",
";",
"if",
"(",
"persistenceClass",
"!=",
"null",
")",
"{",
"store",
"=",
"PersistenceUtils",
"."... | Set scope persistence class
@param persistenceClass
Scope's persistence class
@throws Exception
Exception | [
"Set",
"scope",
"persistence",
"class"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L1066-L1071 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.unregisterServiceHandler | public void unregisterServiceHandler(String name) {
Map<String, Object> serviceHandlers = getServiceHandlers(false);
if (serviceHandlers != null) {
serviceHandlers.remove(name);
}
} | java | public void unregisterServiceHandler(String name) {
Map<String, Object> serviceHandlers = getServiceHandlers(false);
if (serviceHandlers != null) {
serviceHandlers.remove(name);
}
} | [
"public",
"void",
"unregisterServiceHandler",
"(",
"String",
"name",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"serviceHandlers",
"=",
"getServiceHandlers",
"(",
"false",
")",
";",
"if",
"(",
"serviceHandlers",
"!=",
"null",
")",
"{",
"serviceHandler... | Unregisters service handler by name
@param name
Service handler name | [
"Unregisters",
"service",
"handler",
"by",
"name"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L1144-L1149 | train |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getServer | 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;
} | java | 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;
} | [
"public",
"IServer",
"getServer",
"(",
")",
"{",
"if",
"(",
"hasParent",
"(",
")",
")",
"{",
"final",
"IScope",
"parent",
"=",
"getParent",
"(",
")",
";",
"if",
"(",
"parent",
"instanceof",
"Scope",
")",
"{",
"return",
"(",
"(",
"Scope",
")",
"parent... | Return the server instance connected to this scope.
@return the server instance | [
"Return",
"the",
"server",
"instance",
"connected",
"to",
"this",
"scope",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L1156-L1166 | train |
Red5/red5-server-common | src/main/java/org/red5/server/messaging/PipeConnectionEvent.java | PipeConnectionEvent.setParamMap | public void setParamMap(Map<String, Object> paramMap) {
if (paramMap != null && !paramMap.isEmpty()) {
this.paramMap.putAll(paramMap);
}
} | java | public void setParamMap(Map<String, Object> paramMap) {
if (paramMap != null && !paramMap.isEmpty()) {
this.paramMap.putAll(paramMap);
}
} | [
"public",
"void",
"setParamMap",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"paramMap",
")",
"{",
"if",
"(",
"paramMap",
"!=",
"null",
"&&",
"!",
"paramMap",
".",
"isEmpty",
"(",
")",
")",
"{",
"this",
".",
"paramMap",
".",
"putAll",
"(",
"paramM... | Setter for event parameters map
@param paramMap
Event parameters as Map | [
"Setter",
"for",
"event",
"parameters",
"map"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/messaging/PipeConnectionEvent.java#L155-L159 | train |
Red5/red5-server-common | src/main/java/org/red5/server/messaging/PipeConnectionEvent.java | PipeConnectionEvent.build | public final static PipeConnectionEvent build(AbstractPipe source, EventType type, IConsumer consumer, Map<String, Object> paramMap) {
return new PipeConnectionEvent(source, type, consumer, paramMap);
} | java | public final static PipeConnectionEvent build(AbstractPipe source, EventType type, IConsumer consumer, Map<String, Object> paramMap) {
return new PipeConnectionEvent(source, type, consumer, paramMap);
} | [
"public",
"final",
"static",
"PipeConnectionEvent",
"build",
"(",
"AbstractPipe",
"source",
",",
"EventType",
"type",
",",
"IConsumer",
"consumer",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"paramMap",
")",
"{",
"return",
"new",
"PipeConnectionEvent",
"(",
... | Builds a PipeConnectionEvent with a source pipe and consumer.
@param source pipe that triggers this event
@param type event type
@param consumer the consumer
@param paramMap parameters map
@return event | [
"Builds",
"a",
"PipeConnectionEvent",
"with",
"a",
"source",
"pipe",
"and",
"consumer",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/messaging/PipeConnectionEvent.java#L189-L191 | train |
Red5/red5-server-common | src/main/java/org/red5/server/messaging/PipeConnectionEvent.java | PipeConnectionEvent.build | public final static PipeConnectionEvent build(AbstractPipe source, EventType type, IProvider provider, Map<String, Object> paramMap) {
return new PipeConnectionEvent(source, type, provider, paramMap);
} | java | public final static PipeConnectionEvent build(AbstractPipe source, EventType type, IProvider provider, Map<String, Object> paramMap) {
return new PipeConnectionEvent(source, type, provider, paramMap);
} | [
"public",
"final",
"static",
"PipeConnectionEvent",
"build",
"(",
"AbstractPipe",
"source",
",",
"EventType",
"type",
",",
"IProvider",
"provider",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"paramMap",
")",
"{",
"return",
"new",
"PipeConnectionEvent",
"(",
... | Builds a PipeConnectionEvent with a source pipe and provider.
@param source pipe that triggers this event
@param type event type
@param provider the provider
@param paramMap parameters map
@return event | [
"Builds",
"a",
"PipeConnectionEvent",
"with",
"a",
"source",
"pipe",
"and",
"provider",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/messaging/PipeConnectionEvent.java#L202-L204 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/remoting/RemotingClient.java | RemotingClient.setCredentials | 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);
} | java | 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);
} | [
"public",
"void",
"setCredentials",
"(",
"String",
"userid",
",",
"String",
"password",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"data",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"data",
".",
"put",
"(",
"\"u... | Send authentication data with each remoting request.
@param userid
User identifier
@param password
Password | [
"Send",
"authentication",
"data",
"with",
"each",
"remoting",
"request",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/remoting/RemotingClient.java#L265-L271 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/remoting/RemotingClient.java | RemotingClient.addHeader | public void addHeader(String name, boolean required, Object value) {
RemotingHeader header = new RemotingHeader(name, required, value);
headers.put(name, header);
} | java | public void addHeader(String name, boolean required, Object value) {
RemotingHeader header = new RemotingHeader(name, required, value);
headers.put(name, header);
} | [
"public",
"void",
"addHeader",
"(",
"String",
"name",
",",
"boolean",
"required",
",",
"Object",
"value",
")",
"{",
"RemotingHeader",
"header",
"=",
"new",
"RemotingHeader",
"(",
"name",
",",
"required",
",",
"value",
")",
";",
"headers",
".",
"put",
"(",
... | Send an additional header to the server.
@param name
Header name
@param required
Header required?
@param value
Header body | [
"Send",
"an",
"additional",
"header",
"to",
"the",
"server",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/remoting/RemotingClient.java#L290-L293 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/remoting/RemotingClient.java | RemotingClient.invokeMethod | public Object invokeMethod(String method, Object[] params) {
log.debug("invokeMethod url: {}", (url + appendToUrl));
IoBuffer resultBuffer = null;
IoBuffer data = encodeInvoke(method, params);
//setup POST
HttpPost post = null;
try {
post = new HttpPost(url + appendToUrl);
post.addHeader("Content-Type", CONTENT_TYPE);
post.setEntity(new InputStreamEntity(data.asInputStream(), data.limit()));
// execute the method
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) {
//fix for Trac #676
int contentLength = (int) entity.getContentLength();
//default the content length to 16 if post doesn't contain a good value
if (contentLength < 1) {
contentLength = 16;
}
// get the response as bytes
byte[] bytes = EntityUtils.toByteArray(entity);
resultBuffer = IoBuffer.wrap(bytes);
Object result = decodeResult(resultBuffer);
if (result instanceof RecordSet) {
// Make sure we can retrieve paged results
((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;
} | java | public Object invokeMethod(String method, Object[] params) {
log.debug("invokeMethod url: {}", (url + appendToUrl));
IoBuffer resultBuffer = null;
IoBuffer data = encodeInvoke(method, params);
//setup POST
HttpPost post = null;
try {
post = new HttpPost(url + appendToUrl);
post.addHeader("Content-Type", CONTENT_TYPE);
post.setEntity(new InputStreamEntity(data.asInputStream(), data.limit()));
// execute the method
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) {
//fix for Trac #676
int contentLength = (int) entity.getContentLength();
//default the content length to 16 if post doesn't contain a good value
if (contentLength < 1) {
contentLength = 16;
}
// get the response as bytes
byte[] bytes = EntityUtils.toByteArray(entity);
resultBuffer = IoBuffer.wrap(bytes);
Object result = decodeResult(resultBuffer);
if (result instanceof RecordSet) {
// Make sure we can retrieve paged results
((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;
} | [
"public",
"Object",
"invokeMethod",
"(",
"String",
"method",
",",
"Object",
"[",
"]",
"params",
")",
"{",
"log",
".",
"debug",
"(",
"\"invokeMethod url: {}\"",
",",
"(",
"url",
"+",
"appendToUrl",
")",
")",
";",
"IoBuffer",
"resultBuffer",
"=",
"null",
";"... | Invoke a method synchronously on the remoting server.
@param method
Method name
@param params
Parameters passed to method
@return the result of the method call | [
"Invoke",
"a",
"method",
"synchronously",
"on",
"the",
"remoting",
"server",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/remoting/RemotingClient.java#L314-L362 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/remoting/RemotingClient.java | RemotingClient.invokeMethod | 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);
}
} | java | 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);
}
} | [
"public",
"void",
"invokeMethod",
"(",
"String",
"method",
",",
"Object",
"[",
"]",
"methodParams",
",",
"IRemotingCallback",
"callback",
")",
"{",
"try",
"{",
"RemotingWorker",
"worker",
"=",
"new",
"RemotingWorker",
"(",
"this",
",",
"method",
",",
"methodPa... | Invoke a method asynchronously on the remoting server.
@param method
Method name
@param methodParams
Parameters passed to method
@param callback
Callback | [
"Invoke",
"a",
"method",
"asynchronously",
"on",
"the",
"remoting",
"server",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/remoting/RemotingClient.java#L374-L381 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java | RTMPProtocolDecoder.decodeBuffer | public List<Object> decodeBuffer(RTMPConnection conn, IoBuffer buffer) {
final int position = buffer.position();
//if (log.isTraceEnabled()) {
//log.trace("decodeBuffer: {}", Hex.encodeHexString(Arrays.copyOfRange(buffer.array(), position, buffer.limit())));
//}
// decoded results
List<Object> result = null;
if (conn != null) {
//log.trace("Decoding for connection - session id: {}", conn.getSessionId());
try {
// instance list to hold results
result = new LinkedList<>();
// get the local decode state
RTMPDecodeState state = conn.getDecoderState();
//if (log.isTraceEnabled()) {
//log.trace("RTMP decode state {}", state);
//}
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)) {
//log.trace("Can start decoding");
state.startDecoding();
} else {
log.trace("Cannot start decoding");
break;
}
final Object decodedObject = decode(conn, state, buffer);
if (state.hasDecodedObject()) {
//log.trace("Has decoded object");
if (decodedObject != null) {
result.add(decodedObject);
}
} else if (state.canContinueDecoding()) {
//log.trace("Can continue decoding");
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())));
// catch any non-handshake exception in the decoding; close the connection
log.warn("Closing connection because decoding failed: {}", conn, ex);
// clear the buffer to eliminate memory leaks when we can't parse protocol
buffer.clear();
// close connection because we can't parse data from it
conn.close();
} finally {
//if (log.isTraceEnabled()) {
//log.trace("decodeBuffer - post decode input buffer position: {} remaining: {}", buffer.position(), buffer.remaining());
//}
buffer.compact();
}
} else {
log.error("Decoding buffer failed, no current connection!?");
}
return result;
} | java | public List<Object> decodeBuffer(RTMPConnection conn, IoBuffer buffer) {
final int position = buffer.position();
//if (log.isTraceEnabled()) {
//log.trace("decodeBuffer: {}", Hex.encodeHexString(Arrays.copyOfRange(buffer.array(), position, buffer.limit())));
//}
// decoded results
List<Object> result = null;
if (conn != null) {
//log.trace("Decoding for connection - session id: {}", conn.getSessionId());
try {
// instance list to hold results
result = new LinkedList<>();
// get the local decode state
RTMPDecodeState state = conn.getDecoderState();
//if (log.isTraceEnabled()) {
//log.trace("RTMP decode state {}", state);
//}
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)) {
//log.trace("Can start decoding");
state.startDecoding();
} else {
log.trace("Cannot start decoding");
break;
}
final Object decodedObject = decode(conn, state, buffer);
if (state.hasDecodedObject()) {
//log.trace("Has decoded object");
if (decodedObject != null) {
result.add(decodedObject);
}
} else if (state.canContinueDecoding()) {
//log.trace("Can continue decoding");
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())));
// catch any non-handshake exception in the decoding; close the connection
log.warn("Closing connection because decoding failed: {}", conn, ex);
// clear the buffer to eliminate memory leaks when we can't parse protocol
buffer.clear();
// close connection because we can't parse data from it
conn.close();
} finally {
//if (log.isTraceEnabled()) {
//log.trace("decodeBuffer - post decode input buffer position: {} remaining: {}", buffer.position(), buffer.remaining());
//}
buffer.compact();
}
} else {
log.error("Decoding buffer failed, no current connection!?");
}
return result;
} | [
"public",
"List",
"<",
"Object",
">",
"decodeBuffer",
"(",
"RTMPConnection",
"conn",
",",
"IoBuffer",
"buffer",
")",
"{",
"final",
"int",
"position",
"=",
"buffer",
".",
"position",
"(",
")",
";",
"//if (log.isTraceEnabled()) {\r",
"//log.trace(\"decodeBuffer: {}\",... | Decode all available objects in buffer.
@param conn
RTMP connection
@param buffer
IoBuffer of data to be decoded
@return a list of decoded objects, may be empty if nothing could be decoded | [
"Decode",
"all",
"available",
"objects",
"in",
"buffer",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java#L102-L163 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java | RTMPProtocolDecoder.decode | public Object decode(RTMPConnection conn, RTMPDecodeState state, IoBuffer in) throws ProtocolException {
//if (log.isTraceEnabled()) {
//log.trace("Decoding for {}", conn.getSessionId());
//}
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:
// throw away any remaining input data:
in.clear();
return null;
default:
throw new IllegalStateException("Invalid RTMP state: " + connectionState);
}
} catch (ProtocolException pe) {
// raise to caller unmodified
throw pe;
} catch (RuntimeException e) {
throw new ProtocolException("Error during decoding", e);
} finally {
//if (log.isTraceEnabled()) {
//log.trace("Decoding finished for {}", conn.getSessionId());
//}
}
} | java | public Object decode(RTMPConnection conn, RTMPDecodeState state, IoBuffer in) throws ProtocolException {
//if (log.isTraceEnabled()) {
//log.trace("Decoding for {}", conn.getSessionId());
//}
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:
// throw away any remaining input data:
in.clear();
return null;
default:
throw new IllegalStateException("Invalid RTMP state: " + connectionState);
}
} catch (ProtocolException pe) {
// raise to caller unmodified
throw pe;
} catch (RuntimeException e) {
throw new ProtocolException("Error during decoding", e);
} finally {
//if (log.isTraceEnabled()) {
//log.trace("Decoding finished for {}", conn.getSessionId());
//}
}
} | [
"public",
"Object",
"decode",
"(",
"RTMPConnection",
"conn",
",",
"RTMPDecodeState",
"state",
",",
"IoBuffer",
"in",
")",
"throws",
"ProtocolException",
"{",
"//if (log.isTraceEnabled()) {\r",
"//log.trace(\"Decoding for {}\", conn.getSessionId());\r",
"//}\r",
"try",
"{",
... | Decodes the buffer data.
@param conn
RTMP connection
@param state
Stores state for the protocol, ProtocolState is just a marker interface
@param in
IoBuffer of data to be decoded
@return one of three possible values:
<pre>
1. null : the object could not be decoded, or some data was skipped, just continue
2. ProtocolState : the decoder was unable to decode the whole object, refer to the protocol state
3. Object : something was decoded, continue
</pre>
@throws ProtocolException
on error | [
"Decodes",
"the",
"buffer",
"data",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java#L184-L212 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java | RTMPProtocolDecoder.decodeMessage | 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: // represents an SO in an AMF3 container
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());
}
// skip first byte
in.get();
// decode stream data; slice from the current position
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;
}
// add the header to the message
message.setHeader(header);
return message;
} | java | 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: // represents an SO in an AMF3 container
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());
}
// skip first byte
in.get();
// decode stream data; slice from the current position
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;
}
// add the header to the message
message.setHeader(header);
return message;
} | [
"public",
"IRTMPEvent",
"decodeMessage",
"(",
"RTMPConnection",
"conn",
",",
"Header",
"header",
",",
"IoBuffer",
"in",
")",
"{",
"IRTMPEvent",
"message",
";",
"byte",
"dataType",
"=",
"header",
".",
"getDataType",
"(",
")",
";",
"switch",
"(",
"dataType",
"... | Decodes RTMP message event.
@param conn
RTMP connection
@param header
RTMP header
@param in
Input IoBuffer
@return RTMP event | [
"Decodes",
"RTMP",
"message",
"event",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java#L499-L571 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java | RTMPProtocolDecoder.doDecodeSharedObject | protected void doDecodeSharedObject(SharedObjectMessage so, IoBuffer in, Input input) {
// Parse request body
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) {
// Status code
key = input.getString();
// Status level
value = input.getString();
} else if (type == ISharedObjectEvent.Type.CLIENT_UPDATE_DATA) {
key = null;
// Map containing new attribute values
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) {
// determine if the object is encoded with amf3
byte objType = in.get();
in.position(in.position() - 1);
Input propertyInput;
if (objType == AMF.TYPE_AMF3_OBJECT && !(input instanceof org.red5.io.amf3.Input)) {
// The next parameter is encoded using AMF3
propertyInput = amf3Input;
} else {
// The next parameter is encoded using AMF0
propertyInput = input;
}
value = Deserializer.deserialize(propertyInput, Object.class);
}
}
} else {
final int start = in.position();
// the "send" event seems to encode the handler name as complete AMF string including the string type byte
key = Deserializer.deserialize(input, String.class);
// read parameters
final List<Object> list = new LinkedList<Object>();
while (in.position() - start < length) {
byte objType = in.get();
in.position(in.position() - 1);
// determine if the object is encoded with amf3
Input propertyInput;
if (objType == AMF.TYPE_AMF3_OBJECT && !(input instanceof org.red5.io.amf3.Input)) {
// The next parameter is encoded using AMF3
propertyInput = amf3Input;
} else {
// The next parameter is encoded using AMF0
propertyInput = input;
}
Object tmp = Deserializer.deserialize(propertyInput, Object.class);
list.add(tmp);
}
value = list;
}
so.addEvent(type, key, value);
}
} | java | protected void doDecodeSharedObject(SharedObjectMessage so, IoBuffer in, Input input) {
// Parse request body
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) {
// Status code
key = input.getString();
// Status level
value = input.getString();
} else if (type == ISharedObjectEvent.Type.CLIENT_UPDATE_DATA) {
key = null;
// Map containing new attribute values
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) {
// determine if the object is encoded with amf3
byte objType = in.get();
in.position(in.position() - 1);
Input propertyInput;
if (objType == AMF.TYPE_AMF3_OBJECT && !(input instanceof org.red5.io.amf3.Input)) {
// The next parameter is encoded using AMF3
propertyInput = amf3Input;
} else {
// The next parameter is encoded using AMF0
propertyInput = input;
}
value = Deserializer.deserialize(propertyInput, Object.class);
}
}
} else {
final int start = in.position();
// the "send" event seems to encode the handler name as complete AMF string including the string type byte
key = Deserializer.deserialize(input, String.class);
// read parameters
final List<Object> list = new LinkedList<Object>();
while (in.position() - start < length) {
byte objType = in.get();
in.position(in.position() - 1);
// determine if the object is encoded with amf3
Input propertyInput;
if (objType == AMF.TYPE_AMF3_OBJECT && !(input instanceof org.red5.io.amf3.Input)) {
// The next parameter is encoded using AMF3
propertyInput = amf3Input;
} else {
// The next parameter is encoded using AMF0
propertyInput = input;
}
Object tmp = Deserializer.deserialize(propertyInput, Object.class);
list.add(tmp);
}
value = list;
}
so.addEvent(type, key, value);
}
} | [
"protected",
"void",
"doDecodeSharedObject",
"(",
"SharedObjectMessage",
"so",
",",
"IoBuffer",
"in",
",",
"Input",
"input",
")",
"{",
"// Parse request body\r",
"Input",
"amf3Input",
"=",
"new",
"org",
".",
"red5",
".",
"io",
".",
"amf3",
".",
"Input",
"(",
... | Perform the actual decoding of the shared object contents.
@param so
Shared object message
@param in
input buffer
@param input
Input object to be processed | [
"Perform",
"the",
"actual",
"decoding",
"of",
"the",
"shared",
"object",
"contents",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java#L669-L739 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java | RTMPProtocolDecoder.decodeAction | private Invoke decodeAction(Encoding encoding, IoBuffer in, Header header) {
// for response, the action string and invokeId is always encoded as AMF0 we use the first byte to decide which encoding to use
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);
}
// get the action
String action = Deserializer.deserialize(input, String.class);
if (action == null) {
throw new RuntimeException("Action was null");
}
if (log.isTraceEnabled()) {
log.trace("Action: {}", action);
}
// instance the invoke
Invoke invoke = new Invoke();
// set the transaction id
invoke.setTransactionId(readTransactionId(input));
// reset and decode parameters
input.reset();
// get / set the parameters if there any
Object[] params = in.hasRemaining() ? handleParameters(in, invoke, input) : new Object[0];
// determine service information
final int dotIndex = action.lastIndexOf('.');
String serviceName = (dotIndex == -1) ? null : action.substring(0, dotIndex);
// pull off the prefixes since java doesn't allow this on a method name
if (serviceName != null && (serviceName.startsWith("@") || serviceName.startsWith("|"))) {
serviceName = serviceName.substring(1);
}
String serviceMethod = (dotIndex == -1) ? action : action.substring(dotIndex + 1, action.length());
// pull off the prefixes since java doesnt allow this on a method name
if (serviceMethod.startsWith("@") || serviceMethod.startsWith("|")) {
serviceMethod = serviceMethod.substring(1);
}
// create the pending call for invoke
PendingCall call = new PendingCall(serviceName, serviceMethod, params);
invoke.setCall(call);
return invoke;
} | java | private Invoke decodeAction(Encoding encoding, IoBuffer in, Header header) {
// for response, the action string and invokeId is always encoded as AMF0 we use the first byte to decide which encoding to use
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);
}
// get the action
String action = Deserializer.deserialize(input, String.class);
if (action == null) {
throw new RuntimeException("Action was null");
}
if (log.isTraceEnabled()) {
log.trace("Action: {}", action);
}
// instance the invoke
Invoke invoke = new Invoke();
// set the transaction id
invoke.setTransactionId(readTransactionId(input));
// reset and decode parameters
input.reset();
// get / set the parameters if there any
Object[] params = in.hasRemaining() ? handleParameters(in, invoke, input) : new Object[0];
// determine service information
final int dotIndex = action.lastIndexOf('.');
String serviceName = (dotIndex == -1) ? null : action.substring(0, dotIndex);
// pull off the prefixes since java doesn't allow this on a method name
if (serviceName != null && (serviceName.startsWith("@") || serviceName.startsWith("|"))) {
serviceName = serviceName.substring(1);
}
String serviceMethod = (dotIndex == -1) ? action : action.substring(dotIndex + 1, action.length());
// pull off the prefixes since java doesnt allow this on a method name
if (serviceMethod.startsWith("@") || serviceMethod.startsWith("|")) {
serviceMethod = serviceMethod.substring(1);
}
// create the pending call for invoke
PendingCall call = new PendingCall(serviceName, serviceMethod, params);
invoke.setCall(call);
return invoke;
} | [
"private",
"Invoke",
"decodeAction",
"(",
"Encoding",
"encoding",
",",
"IoBuffer",
"in",
",",
"Header",
"header",
")",
"{",
"// for response, the action string and invokeId is always encoded as AMF0 we use the first byte to decide which encoding to use\r",
"in",
".",
"mark",
"(",... | Decode the 'action' for a supplied an Invoke.
@param encoding
AMF encoding
@param in
buffer
@param header
data header
@return notify | [
"Decode",
"the",
"action",
"for",
"a",
"supplied",
"an",
"Invoke",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java#L752-L796 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java | RTMPProtocolDecoder.decodePing | public Ping decodePing(IoBuffer in) {
Ping ping = null;
if (log.isTraceEnabled()) {
// gets the raw data as hex without changing the data or pointer
String hexDump = in.getHexDump();
log.trace("Ping dump: {}", hexDump);
}
// control type
short type = in.getShort();
switch (type) {
case Ping.CLIENT_BUFFER:
ping = new SetBuffer(in.getInt(), in.getInt());
break;
case Ping.PING_SWF_VERIFY:
// only contains the type (2 bytes)
ping = new Ping(type);
break;
case Ping.PONG_SWF_VERIFY:
byte[] bytes = new byte[42];
in.get(bytes);
ping = new SWFResponse(bytes);
break;
default:
//STREAM_BEGIN, STREAM_PLAYBUFFER_CLEAR, STREAM_DRY, RECORDED_STREAM
//PING_CLIENT, PONG_SERVER
//BUFFER_EMPTY, BUFFER_FULL
ping = new Ping(type, in.getInt());
break;
}
return ping;
} | java | public Ping decodePing(IoBuffer in) {
Ping ping = null;
if (log.isTraceEnabled()) {
// gets the raw data as hex without changing the data or pointer
String hexDump = in.getHexDump();
log.trace("Ping dump: {}", hexDump);
}
// control type
short type = in.getShort();
switch (type) {
case Ping.CLIENT_BUFFER:
ping = new SetBuffer(in.getInt(), in.getInt());
break;
case Ping.PING_SWF_VERIFY:
// only contains the type (2 bytes)
ping = new Ping(type);
break;
case Ping.PONG_SWF_VERIFY:
byte[] bytes = new byte[42];
in.get(bytes);
ping = new SWFResponse(bytes);
break;
default:
//STREAM_BEGIN, STREAM_PLAYBUFFER_CLEAR, STREAM_DRY, RECORDED_STREAM
//PING_CLIENT, PONG_SERVER
//BUFFER_EMPTY, BUFFER_FULL
ping = new Ping(type, in.getInt());
break;
}
return ping;
} | [
"public",
"Ping",
"decodePing",
"(",
"IoBuffer",
"in",
")",
"{",
"Ping",
"ping",
"=",
"null",
";",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"// gets the raw data as hex without changing the data or pointer\r",
"String",
"hexDump",
"=",
"in",
... | Decodes ping event.
@param in
IoBuffer
@return Ping event | [
"Decodes",
"ping",
"event",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java#L810-L840 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java | RTMPProtocolDecoder.isStreamCommand | @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;
}
} | java | @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;
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"private",
"boolean",
"isStreamCommand",
"(",
"String",
"action",
")",
"{",
"switch",
"(",
"StreamAction",
".",
"getEnum",
"(",
"action",
")",
")",
"{",
"case",
"CREATE_STREAM",
":",
"case",
"DELETE_STREAM",
":"... | Checks if the passed action is a reserved stream method.
@param action
Action to check
@return true if passed action is a reserved stream method, false otherwise | [
"Checks",
"if",
"the",
"passed",
"action",
"is",
"a",
"reserved",
"stream",
"method",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java#L1092-L1112 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/Channel.java | Channel.write | 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);
}
// if the stream is non-existant, the event will go out with stream id == 0
final Number streamId = (stream == null) ? 0 : stream.getStreamId();
write(event, streamId);
} else {
log.debug("Connection {} is closed, cannot write to channel: {}", connection.getSessionId(), id);
}
} | java | 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);
}
// if the stream is non-existant, the event will go out with stream id == 0
final Number streamId = (stream == null) ? 0 : stream.getStreamId();
write(event, streamId);
} else {
log.debug("Connection {} is closed, cannot write to channel: {}", connection.getSessionId(), id);
}
} | [
"public",
"void",
"write",
"(",
"IRTMPEvent",
"event",
")",
"{",
"if",
"(",
"!",
"connection",
".",
"isClosed",
"(",
")",
")",
"{",
"final",
"IClientStream",
"stream",
"=",
"connection",
".",
"getStreamByChannelId",
"(",
"id",
")",
";",
"if",
"(",
"id",
... | Writes packet from event data to RTMP connection.
@param event
Event data | [
"Writes",
"packet",
"from",
"event",
"data",
"to",
"RTMP",
"connection",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/Channel.java#L103-L115 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/Channel.java | Channel.write | 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);
// set the channel id
header.setChannelId(id);
int ts = event.getTimestamp();
if (ts != 0) {
header.setTimer(event.getTimestamp());
}
header.setStreamId(streamId);
header.setDataType(event.getDataType());
// should use RTMPConnection specific method..
//log.trace("Connection type for write: {}", connection.getClass().getName());
connection.write(packet);
} | java | 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);
// set the channel id
header.setChannelId(id);
int ts = event.getTimestamp();
if (ts != 0) {
header.setTimer(event.getTimestamp());
}
header.setStreamId(streamId);
header.setDataType(event.getDataType());
// should use RTMPConnection specific method..
//log.trace("Connection type for write: {}", connection.getClass().getName());
connection.write(packet);
} | [
"private",
"void",
"write",
"(",
"IRTMPEvent",
"event",
",",
"Number",
"streamId",
")",
"{",
"log",
".",
"trace",
"(",
"\"write to stream id: {} channel: {}\"",
",",
"streamId",
",",
"id",
")",
";",
"final",
"Header",
"header",
"=",
"new",
"Header",
"(",
")"... | Writes packet from event data to RTMP connection and stream id.
@param event
Event data
@param streamId
Stream id | [
"Writes",
"packet",
"from",
"event",
"data",
"to",
"RTMP",
"connection",
"and",
"stream",
"id",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/Channel.java#L125-L140 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/Channel.java | Channel.discard | @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);
} | java | @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);
} | [
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"private",
"void",
"discard",
"(",
"IRTMPEvent",
"event",
")",
"{",
"if",
"(",
"event",
"instanceof",
"IStreamData",
"<",
"?",
">",
")",
"{",
"log",
".",
"debug",
"(",
"\"Discarding: {}\"",
",",
"(",
"(",
... | Discard an event routed to this channel.
@param event | [
"Discard",
"an",
"event",
"routed",
"to",
"this",
"channel",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/Channel.java#L147-L159 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/Channel.java | Channel.sendStatus | 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);
}
// send directly to the corresponding stream as for some status codes, no stream has been created and thus "getStreamByChannelId" will fail
write(event, connection.getStreamIdForChannelId(id));
}
} | java | 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);
}
// send directly to the corresponding stream as for some status codes, no stream has been created and thus "getStreamByChannelId" will fail
write(event, connection.getStreamIdForChannelId(id));
}
} | [
"public",
"void",
"sendStatus",
"(",
"Status",
"status",
")",
"{",
"if",
"(",
"connection",
"!=",
"null",
")",
"{",
"final",
"boolean",
"andReturn",
"=",
"!",
"status",
".",
"getCode",
"(",
")",
".",
"equals",
"(",
"StatusCodes",
".",
"NS_DATA_START",
")... | Sends status notification.
@param status
Status | [
"Sends",
"status",
"notification",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/Channel.java#L167-L196 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/StreamService.java | StreamService.pause | 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;
// pausePlayback can be "null" if "pause" is called without any parameters from flash
if (pausePlayback == null) {
pausePlayback = !subscriberStream.isPaused();
}
if (pausePlayback) {
subscriberStream.pause(position);
} else {
subscriberStream.resume(position);
}
}
}
} | java | 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;
// pausePlayback can be "null" if "pause" is called without any parameters from flash
if (pausePlayback == null) {
pausePlayback = !subscriberStream.isPaused();
}
if (pausePlayback) {
subscriberStream.pause(position);
} else {
subscriberStream.resume(position);
}
}
}
} | [
"public",
"void",
"pause",
"(",
"Boolean",
"pausePlayback",
",",
"int",
"position",
")",
"{",
"IConnection",
"conn",
"=",
"Red5",
".",
"getConnectionLocal",
"(",
")",
";",
"if",
"(",
"conn",
"instanceof",
"IStreamCapableConnection",
")",
"{",
"IStreamCapableConn... | Pause at given position. Required as "pausePlayback" can be "null" if no flag is passed by the client
@param pausePlayback
Pause playback or not
@param position
Pause position | [
"Pause",
"at",
"given",
"position",
".",
"Required",
"as",
"pausePlayback",
"can",
"be",
"null",
"if",
"no",
"flag",
"is",
"passed",
"by",
"the",
"client"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/StreamService.java#L255-L274 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/StreamService.java | StreamService.play | 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:
//adds the stream to a playlist
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:
//maintains the playlist and returns all stream messages at once, rather than at intervals
break;
case 3:
//clears the playlist and returns all stream messages at once
break;
default:
//clears any previous play calls and plays name immediately
play(name, start, length, true);
}
} else {
play(name, start, length);
}
}
} | java | 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:
//adds the stream to a playlist
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:
//maintains the playlist and returns all stream messages at once, rather than at intervals
break;
case 3:
//clears the playlist and returns all stream messages at once
break;
default:
//clears any previous play calls and plays name immediately
play(name, start, length, true);
}
} else {
play(name, start, length);
}
}
} | [
"public",
"void",
"play",
"(",
"String",
"name",
",",
"int",
"start",
",",
"int",
"length",
",",
"Object",
"reset",
")",
"{",
"if",
"(",
"reset",
"instanceof",
"Boolean",
")",
"{",
"play",
"(",
"name",
",",
"start",
",",
"length",
",",
"(",
"(",
"B... | Plays back a stream based on the supplied name, from the specified position for the given length of time.
@param name
- The name of a recorded file, or the identifier for live data. If
@param start
- The start time, in seconds. Allowed values are -2, -1, 0, or a positive number. The default value is -2, which looks for
a live stream, then a recorded stream, and if it finds neither, opens a live stream. If -1, plays only a live stream. If 0
or a positive number, plays a recorded stream, beginning start seconds in.
@param length
- The duration of the playback, in seconds. Allowed values are -1, 0, or a positive number. The default value is -1, which
plays a live or recorded stream until it ends. If 0, plays a single frame that is start seconds from the beginning of a
recorded stream. If a positive number, plays a live or recorded stream for length seconds.
@param reset
- Whether to clear a playlist. The default value is 1 or true, which clears any previous play calls and plays name
immediately. If 0 or false, adds the stream to a playlist. If 2, maintains the playlist and returns all stream messages at
once, rather than at intervals. If 3, clears the playlist and returns all stream messages at once. | [
"Plays",
"back",
"a",
"stream",
"based",
"on",
"the",
"supplied",
"name",
"from",
"the",
"specified",
"position",
"for",
"the",
"given",
"length",
"of",
"time",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/StreamService.java#L294-L325 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/StreamService.java | StreamService.sendNSFailed | private void sendNSFailed(IConnection conn, String errorCode, String description, String name, Number streamId) {
StreamService.sendNetStreamStatus(conn, errorCode, description, name, Status.ERROR, streamId);
} | java | private void sendNSFailed(IConnection conn, String errorCode, String description, String name, Number streamId) {
StreamService.sendNetStreamStatus(conn, errorCode, description, name, Status.ERROR, streamId);
} | [
"private",
"void",
"sendNSFailed",
"(",
"IConnection",
"conn",
",",
"String",
"errorCode",
",",
"String",
"description",
",",
"String",
"name",
",",
"Number",
"streamId",
")",
"{",
"StreamService",
".",
"sendNetStreamStatus",
"(",
"conn",
",",
"errorCode",
",",
... | Send NetStream.Play.Failed to the client.
@param conn
@param errorCode
@param description
@param name
@param streamId | [
"Send",
"NetStream",
".",
"Play",
".",
"Failed",
"to",
"the",
"client",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/StreamService.java#L800-L802 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.initRC4Encryption | protected void initRC4Encryption(byte[] sharedSecret) {
log.debug("Shared secret: {}", Hex.encodeHexString(sharedSecret));
// create output cipher
log.debug("Outgoing public key [{}]: {}", outgoingPublicKey.length, Hex.encodeHexString(outgoingPublicKey));
byte[] rc4keyOut = new byte[32];
// digest is 32 bytes, but our key is 16
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);
}
// create input cipher
log.debug("Incoming public key [{}]: {}", incomingPublicKey.length, Hex.encodeHexString(incomingPublicKey));
// digest is 32 bytes, but our key is 16
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);
}
} | java | protected void initRC4Encryption(byte[] sharedSecret) {
log.debug("Shared secret: {}", Hex.encodeHexString(sharedSecret));
// create output cipher
log.debug("Outgoing public key [{}]: {}", outgoingPublicKey.length, Hex.encodeHexString(outgoingPublicKey));
byte[] rc4keyOut = new byte[32];
// digest is 32 bytes, but our key is 16
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);
}
// create input cipher
log.debug("Incoming public key [{}]: {}", incomingPublicKey.length, Hex.encodeHexString(incomingPublicKey));
// digest is 32 bytes, but our key is 16
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);
}
} | [
"protected",
"void",
"initRC4Encryption",
"(",
"byte",
"[",
"]",
"sharedSecret",
")",
"{",
"log",
".",
"debug",
"(",
"\"Shared secret: {}\"",
",",
"Hex",
".",
"encodeHexString",
"(",
"sharedSecret",
")",
")",
";",
"// create output cipher\r",
"log",
".",
"debug"... | Prepare the ciphers.
@param sharedSecret shared secret byte sequence | [
"Prepare",
"the",
"ciphers",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L213-L239 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.generateKeyPair | 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");
// key agreement is initialized with "this" ends private key
keyAgreement.init(keyPair.getPrivate());
} catch (Exception e) {
log.error("Error generating keypair", e);
}
return keyPair;
} | java | 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");
// key agreement is initialized with "this" ends private key
keyAgreement.init(keyPair.getPrivate());
} catch (Exception e) {
log.error("Error generating keypair", e);
}
return keyPair;
} | [
"protected",
"KeyPair",
"generateKeyPair",
"(",
")",
"{",
"KeyPair",
"keyPair",
"=",
"null",
";",
"DHParameterSpec",
"keySpec",
"=",
"new",
"DHParameterSpec",
"(",
"DH_MODULUS",
",",
"DH_BASE",
")",
";",
"try",
"{",
"KeyPairGenerator",
"keyGen",
"=",
"KeyPairGen... | Creates a Diffie-Hellman key pair.
@return dh keypair | [
"Creates",
"a",
"Diffie",
"-",
"Hellman",
"key",
"pair",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L246-L260 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.getPublicKey | 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);
} | java | 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);
} | [
"protected",
"byte",
"[",
"]",
"getPublicKey",
"(",
"KeyPair",
"keyPair",
")",
"{",
"DHPublicKey",
"incomingPublicKey",
"=",
"(",
"DHPublicKey",
")",
"keyPair",
".",
"getPublic",
"(",
")",
";",
"BigInteger",
"dhY",
"=",
"incomingPublicKey",
".",
"getY",
"(",
... | Returns the public key for a given key pair.
@param keyPair key pair
@return public key | [
"Returns",
"the",
"public",
"key",
"for",
"a",
"given",
"key",
"pair",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L268-L275 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.calculateDigest | 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; // 1504
byte[] message = new byte[messageLen];
// copy bytes from handshake message starting at handshake offset into message start at index 0 and up-to digest position length
System.arraycopy(handshakeMessage, handshakeOffset, message, 0, digestPos);
// copy bytes from handshake message starting at handshake offset plus digest position plus digest length
// into message start at digest position and up-to message length minus digest position
System.arraycopy(handshakeMessage, handshakeOffset + digestPos + DIGEST_LENGTH, message, digestPos, messageLen - digestPos);
calculateHMAC_SHA256(message, 0, messageLen, key, keyLen, digest, digestOffset);
} | java | 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; // 1504
byte[] message = new byte[messageLen];
// copy bytes from handshake message starting at handshake offset into message start at index 0 and up-to digest position length
System.arraycopy(handshakeMessage, handshakeOffset, message, 0, digestPos);
// copy bytes from handshake message starting at handshake offset plus digest position plus digest length
// into message start at digest position and up-to message length minus digest position
System.arraycopy(handshakeMessage, handshakeOffset + digestPos + DIGEST_LENGTH, message, digestPos, messageLen - digestPos);
calculateHMAC_SHA256(message, 0, messageLen, key, keyLen, digest, digestOffset);
} | [
"public",
"void",
"calculateDigest",
"(",
"int",
"digestPos",
",",
"byte",
"[",
"]",
"handshakeMessage",
",",
"int",
"handshakeOffset",
",",
"byte",
"[",
"]",
"key",
",",
"int",
"keyLen",
",",
"byte",
"[",
"]",
"digest",
",",
"int",
"digestOffset",
")",
... | Calculates the digest given the its offset in the handshake data.
@param digestPos digest position
@param handshakeMessage handshake message
@param handshakeOffset handshake message offset
@param key contains the key
@param keyLen the length of the key
@param digest contains the calculated digest
@param digestOffset digest offset | [
"Calculates",
"the",
"digest",
"given",
"the",
"its",
"offset",
"in",
"the",
"handshake",
"data",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L323-L335 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.verifyDigest | 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;
} | java | 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;
} | [
"public",
"boolean",
"verifyDigest",
"(",
"int",
"digestPos",
",",
"byte",
"[",
"]",
"handshakeMessage",
",",
"byte",
"[",
"]",
"key",
",",
"int",
"keyLen",
")",
"{",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"log",
".",
"trace",
"... | Verifies the digest.
@param digestPos digest position
@param handshakeMessage handshake message
@param key contains the key
@param keyLen the length of the key
@return true if valid and false otherwise | [
"Verifies",
"the",
"digest",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L346-L356 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.calculateHMAC_SHA256 | 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)));
//log.trace("calculateHMAC_SHA256 - digestOffset: {} digest: {}", digestOffset, Hex.encodeHexString(Arrays.copyOfRange(digest, digestOffset, digestOffset + DIGEST_LENGTH)));
}
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);
//if (log.isTraceEnabled()) {
// log.trace("Calculated digest: {}", Hex.encodeHexString(calcDigest));
//}
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);
}
} | java | 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)));
//log.trace("calculateHMAC_SHA256 - digestOffset: {} digest: {}", digestOffset, Hex.encodeHexString(Arrays.copyOfRange(digest, digestOffset, digestOffset + DIGEST_LENGTH)));
}
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);
//if (log.isTraceEnabled()) {
// log.trace("Calculated digest: {}", Hex.encodeHexString(calcDigest));
//}
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);
}
} | [
"public",
"void",
"calculateHMAC_SHA256",
"(",
"byte",
"[",
"]",
"message",
",",
"int",
"messageOffset",
",",
"int",
"messageLen",
",",
"byte",
"[",
"]",
"key",
",",
"int",
"keyLen",
",",
"byte",
"[",
"]",
"digest",
",",
"int",
"digestOffset",
")",
"{",
... | Calculates an HMAC SHA256 hash into the digest at the given offset.
@param message incoming bytes
@param messageOffset message offset
@param messageLen message length
@param key incoming key bytes
@param keyLen the length of the key
@param digest contains the calculated digest
@param digestOffset digest offset | [
"Calculates",
"an",
"HMAC",
"SHA256",
"hash",
"into",
"the",
"digest",
"at",
"the",
"given",
"offset",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L369-L391 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.calculateSwfVerification | public void calculateSwfVerification(byte[] handshakeMessage, byte[] swfHash, int swfSize) {
// SHA256 HMAC hash of decompressed SWF, key are the last 32 bytes of the server handshake
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);
// construct SWF verification pong payload
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));
} | java | public void calculateSwfVerification(byte[] handshakeMessage, byte[] swfHash, int swfSize) {
// SHA256 HMAC hash of decompressed SWF, key are the last 32 bytes of the server handshake
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);
// construct SWF verification pong payload
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));
} | [
"public",
"void",
"calculateSwfVerification",
"(",
"byte",
"[",
"]",
"handshakeMessage",
",",
"byte",
"[",
"]",
"swfHash",
",",
"int",
"swfSize",
")",
"{",
"// SHA256 HMAC hash of decompressed SWF, key are the last 32 bytes of the server handshake\r",
"byte",
"[",
"]",
"s... | Calculates the swf verification token.
@param handshakeMessage servers handshake bytes
@param swfHash hash of swf
@param swfSize size of swf | [
"Calculates",
"the",
"swf",
"verification",
"token",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L400-L417 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.getDHOffset | public int getDHOffset(int algorithm, byte[] handshake, int bufferOffset) {
switch (algorithm) {
case 1:
return getDHOffset2(handshake, bufferOffset);
default:
case 0:
return getDHOffset1(handshake, bufferOffset);
}
} | java | public int getDHOffset(int algorithm, byte[] handshake, int bufferOffset) {
switch (algorithm) {
case 1:
return getDHOffset2(handshake, bufferOffset);
default:
case 0:
return getDHOffset1(handshake, bufferOffset);
}
} | [
"public",
"int",
"getDHOffset",
"(",
"int",
"algorithm",
",",
"byte",
"[",
"]",
"handshake",
",",
"int",
"bufferOffset",
")",
"{",
"switch",
"(",
"algorithm",
")",
"{",
"case",
"1",
":",
"return",
"getDHOffset2",
"(",
"handshake",
",",
"bufferOffset",
")",... | Returns the DH offset from an array of bytes.
@param algorithm validation algorithm
@param handshake handshake sequence
@param bufferOffset buffer offset
@return DH offset | [
"Returns",
"the",
"DH",
"offset",
"from",
"an",
"array",
"of",
"bytes",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L427-L435 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.getDigestOffset | public int getDigestOffset(int algorithm, byte[] handshake, int bufferOffset) {
switch (algorithm) {
case 1:
return getDigestOffset2(handshake, bufferOffset);
default:
case 0:
return getDigestOffset1(handshake, bufferOffset);
}
} | java | public int getDigestOffset(int algorithm, byte[] handshake, int bufferOffset) {
switch (algorithm) {
case 1:
return getDigestOffset2(handshake, bufferOffset);
default:
case 0:
return getDigestOffset1(handshake, bufferOffset);
}
} | [
"public",
"int",
"getDigestOffset",
"(",
"int",
"algorithm",
",",
"byte",
"[",
"]",
"handshake",
",",
"int",
"bufferOffset",
")",
"{",
"switch",
"(",
"algorithm",
")",
"{",
"case",
"1",
":",
"return",
"getDigestOffset2",
"(",
"handshake",
",",
"bufferOffset"... | Returns the digest offset using current validation scheme.
@param algorithm validation algorithm
@param handshake handshake sequence
@param bufferOffset buffer offset
@return digest offset | [
"Returns",
"the",
"digest",
"offset",
"using",
"current",
"validation",
"scheme",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L491-L499 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.validHandshakeType | 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;
} | java | 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;
} | [
"public",
"final",
"static",
"boolean",
"validHandshakeType",
"(",
"byte",
"handshakeType",
")",
"{",
"switch",
"(",
"handshakeType",
")",
"{",
"case",
"RTMPConnection",
".",
"RTMP_NON_ENCRYPTED",
":",
"case",
"RTMPConnection",
".",
"RTMP_ENCRYPTED",
":",
"case",
... | Returns whether or not a given handshake type is valid.
@param handshakeType the type of handshake
@return true if valid and supported, false otherwise | [
"Returns",
"whether",
"or",
"not",
"a",
"given",
"handshake",
"type",
"is",
"valid",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L597-L607 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.useEncryption | public boolean useEncryption() {
switch (handshakeType) {
case RTMPConnection.RTMP_ENCRYPTED:
case RTMPConnection.RTMP_ENCRYPTED_XTEA:
case RTMPConnection.RTMP_ENCRYPTED_BLOWFISH:
return true;
}
return false;
} | java | public boolean useEncryption() {
switch (handshakeType) {
case RTMPConnection.RTMP_ENCRYPTED:
case RTMPConnection.RTMP_ENCRYPTED_XTEA:
case RTMPConnection.RTMP_ENCRYPTED_BLOWFISH:
return true;
}
return false;
} | [
"public",
"boolean",
"useEncryption",
"(",
")",
"{",
"switch",
"(",
"handshakeType",
")",
"{",
"case",
"RTMPConnection",
".",
"RTMP_ENCRYPTED",
":",
"case",
"RTMPConnection",
".",
"RTMP_ENCRYPTED_XTEA",
":",
"case",
"RTMPConnection",
".",
"RTMP_ENCRYPTED_BLOWFISH",
... | Whether or not encryptions is in use.
@return true if handshake type is an encrypted type, false otherwise | [
"Whether",
"or",
"not",
"encryptions",
"is",
"in",
"use",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L614-L622 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.setHandshakeType | 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;
} | java | 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;
} | [
"public",
"void",
"setHandshakeType",
"(",
"byte",
"handshakeType",
")",
"{",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"if",
"(",
"handshakeType",
"<",
"HANDSHAKE_TYPES",
".",
"length",
")",
"{",
"log",
".",
"trace",
"(",
"\"Setting han... | Sets the handshake type. Currently only two types are supported, plain and encrypted.
@param handshakeType handshake type | [
"Sets",
"the",
"handshake",
"type",
".",
"Currently",
"only",
"two",
"types",
"are",
"supported",
"plain",
"and",
"encrypted",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L629-L638 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.addBuffer | 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);
} | java | 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);
} | [
"public",
"void",
"addBuffer",
"(",
"IoBuffer",
"in",
")",
"{",
"byte",
"[",
"]",
"tmp",
"=",
"new",
"byte",
"[",
"in",
".",
"remaining",
"(",
")",
"]",
";",
"in",
".",
"get",
"(",
"tmp",
")",
";",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
... | Add a IoBuffer to the buffer.
@param in incoming IoBuffer | [
"Add",
"a",
"IoBuffer",
"to",
"the",
"buffer",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L699-L709 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.getBuffer | public byte[] getBuffer() {
buffer.flip();
byte[] tmp = new byte[buffer.remaining()];
buffer.get(tmp);
buffer.clear();
return tmp;
} | java | public byte[] getBuffer() {
buffer.flip();
byte[] tmp = new byte[buffer.remaining()];
buffer.get(tmp);
buffer.clear();
return tmp;
} | [
"public",
"byte",
"[",
"]",
"getBuffer",
"(",
")",
"{",
"buffer",
".",
"flip",
"(",
")",
";",
"byte",
"[",
"]",
"tmp",
"=",
"new",
"byte",
"[",
"buffer",
".",
"remaining",
"(",
")",
"]",
";",
"buffer",
".",
"get",
"(",
"tmp",
")",
";",
"buffer"... | Returns buffered byte array.
@return bytes | [
"Returns",
"buffered",
"byte",
"array",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L725-L731 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/PlaylistSubscriberStream.java | PlaylistSubscriberStream.moveToNext | private void moveToNext() {
if (controller != null) {
currentItemIndex = controller.nextItem(this, currentItemIndex);
} else {
currentItemIndex = defaultController.nextItem(this, currentItemIndex);
}
} | java | private void moveToNext() {
if (controller != null) {
currentItemIndex = controller.nextItem(this, currentItemIndex);
} else {
currentItemIndex = defaultController.nextItem(this, currentItemIndex);
}
} | [
"private",
"void",
"moveToNext",
"(",
")",
"{",
"if",
"(",
"controller",
"!=",
"null",
")",
"{",
"currentItemIndex",
"=",
"controller",
".",
"nextItem",
"(",
"this",
",",
"currentItemIndex",
")",
";",
"}",
"else",
"{",
"currentItemIndex",
"=",
"defaultContro... | Move the current item to the next in list. | [
"Move",
"the",
"current",
"item",
"to",
"the",
"next",
"in",
"list",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/PlaylistSubscriberStream.java#L595-L601 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/PlaylistSubscriberStream.java | PlaylistSubscriberStream.moveToPrevious | private void moveToPrevious() {
if (controller != null) {
currentItemIndex = controller.previousItem(this, currentItemIndex);
} else {
currentItemIndex = defaultController.previousItem(this, currentItemIndex);
}
} | java | private void moveToPrevious() {
if (controller != null) {
currentItemIndex = controller.previousItem(this, currentItemIndex);
} else {
currentItemIndex = defaultController.previousItem(this, currentItemIndex);
}
} | [
"private",
"void",
"moveToPrevious",
"(",
")",
"{",
"if",
"(",
"controller",
"!=",
"null",
")",
"{",
"currentItemIndex",
"=",
"controller",
".",
"previousItem",
"(",
"this",
",",
"currentItemIndex",
")",
";",
"}",
"else",
"{",
"currentItemIndex",
"=",
"defau... | Move the current item to the previous in list. | [
"Move",
"the",
"current",
"item",
"to",
"the",
"previous",
"in",
"list",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/PlaylistSubscriberStream.java#L606-L612 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/VideoCodecFactory.java | VideoCodecFactory.getVideoCodec | public static IVideoStreamCodec getVideoCodec(IoBuffer data) {
IVideoStreamCodec result = null;
//get the codec identifying byte
int codecId = data.get() & 0x0f;
try {
switch (codecId) {
case 2: //sorenson
result = (IVideoStreamCodec) Class.forName("org.red5.codec.SorensonVideo").newInstance();
break;
case 3: //screen video
result = (IVideoStreamCodec) Class.forName("org.red5.codec.ScreenVideo").newInstance();
break;
case 6: //screen video 2
result = (IVideoStreamCodec) Class.forName("org.red5.codec.ScreenVideo2").newInstance();
break;
case 7: //avc/h.264 video
result = (IVideoStreamCodec) Class.forName("org.red5.codec.AVCVideo").newInstance();
break;
}
} catch (Exception ex) {
log.error("Error creating codec instance", ex);
}
data.rewind();
//if codec is not found do the old-style loop
if (result == null) {
for (IVideoStreamCodec storedCodec : codecs) {
IVideoStreamCodec codec;
// XXX: this is a bit of a hack to create new instances of the
// configured video codec for each stream
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;
} | java | public static IVideoStreamCodec getVideoCodec(IoBuffer data) {
IVideoStreamCodec result = null;
//get the codec identifying byte
int codecId = data.get() & 0x0f;
try {
switch (codecId) {
case 2: //sorenson
result = (IVideoStreamCodec) Class.forName("org.red5.codec.SorensonVideo").newInstance();
break;
case 3: //screen video
result = (IVideoStreamCodec) Class.forName("org.red5.codec.ScreenVideo").newInstance();
break;
case 6: //screen video 2
result = (IVideoStreamCodec) Class.forName("org.red5.codec.ScreenVideo2").newInstance();
break;
case 7: //avc/h.264 video
result = (IVideoStreamCodec) Class.forName("org.red5.codec.AVCVideo").newInstance();
break;
}
} catch (Exception ex) {
log.error("Error creating codec instance", ex);
}
data.rewind();
//if codec is not found do the old-style loop
if (result == null) {
for (IVideoStreamCodec storedCodec : codecs) {
IVideoStreamCodec codec;
// XXX: this is a bit of a hack to create new instances of the
// configured video codec for each stream
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;
} | [
"public",
"static",
"IVideoStreamCodec",
"getVideoCodec",
"(",
"IoBuffer",
"data",
")",
"{",
"IVideoStreamCodec",
"result",
"=",
"null",
";",
"//get the codec identifying byte\r",
"int",
"codecId",
"=",
"data",
".",
"get",
"(",
")",
"&",
"0x0f",
";",
"try",
"{",... | Create and return new video codec applicable for byte buffer data
@param data
Byte buffer data
@return Video codec | [
"Create",
"and",
"return",
"new",
"video",
"codec",
"applicable",
"for",
"byte",
"buffer",
"data"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/VideoCodecFactory.java#L68-L110 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/DefaultStreamFilenameGenerator.java | DefaultStreamFilenameGenerator.getStreamDirectory | 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();
}
} | java | 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();
}
} | [
"private",
"String",
"getStreamDirectory",
"(",
"IScope",
"scope",
")",
"{",
"final",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"final",
"IScope",
"app",
"=",
"ScopeUtils",
".",
"findApplication",
"(",
"scope",
")",
";",
"final",
... | Generate stream directory based on relative scope path. The base directory is
<pre>
streams
</pre>
, e.g. a scope
<pre>
/application/one/two/
</pre>
will generate a directory
<pre>
/streams/one/two/
</pre>
inside the application.
@param scope
Scope
@return Directory based on relative scope path | [
"Generate",
"stream",
"directory",
"based",
"on",
"relative",
"scope",
"path",
".",
"The",
"base",
"directory",
"is"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/DefaultStreamFilenameGenerator.java#L58-L72 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/status/StatusObjectService.java | StatusObjectService.cacheStatusObjects | 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;
} | java | 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;
} | [
"public",
"void",
"cacheStatusObjects",
"(",
")",
"{",
"cachedStatusObjects",
"=",
"new",
"HashMap",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"(",
")",
";",
"String",
"statusCode",
";",
"IoBuffer",
"out",
"=",
"IoBuffer",
".",
"allocate",
"(",
"256",
"... | Cache status objects | [
"Cache",
"status",
"objects"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/status/StatusObjectService.java#L122-L148 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/status/StatusObjectService.java | StatusObjectService.serializeStatusObject | public void serializeStatusObject(IoBuffer out, StatusObject statusObject) {
Map<?, ?> statusMap = new BeanMap(statusObject);
Output output = new Output(out);
Serializer.serialize(output, statusMap);
} | java | public void serializeStatusObject(IoBuffer out, StatusObject statusObject) {
Map<?, ?> statusMap = new BeanMap(statusObject);
Output output = new Output(out);
Serializer.serialize(output, statusMap);
} | [
"public",
"void",
"serializeStatusObject",
"(",
"IoBuffer",
"out",
",",
"StatusObject",
"statusObject",
")",
"{",
"Map",
"<",
"?",
",",
"?",
">",
"statusMap",
"=",
"new",
"BeanMap",
"(",
"statusObject",
")",
";",
"Output",
"output",
"=",
"new",
"Output",
"... | Serializes status object
@param out
Byte buffer for output object
@param statusObject
Status object to serialize | [
"Serializes",
"status",
"object"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/status/StatusObjectService.java#L158-L162 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/ReceivedMessageTask.java | ReceivedMessageTask.runDeadlockFuture | @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);
}
} | java | @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);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"runDeadlockFuture",
"(",
"Runnable",
"deadlockGuardTask",
")",
"{",
"if",
"(",
"deadlockFuture",
"==",
"null",
")",
"{",
"ThreadPoolTaskScheduler",
"deadlockGuard",
"=",
"conn",
".",
"getDeadlock... | Runs deadlock guard task
@param deadlockGuardTask
deadlock guard task | [
"Runs",
"deadlock",
"guard",
"task"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/ReceivedMessageTask.java#L91-L107 | train |
Red5/red5-server-common | src/main/java/org/red5/server/api/stream/support/DynamicPlayItem.java | DynamicPlayItem.build | public static DynamicPlayItem build(String name, long start, long length) {
DynamicPlayItem playItem = new DynamicPlayItem(name, start, length);
return playItem;
} | java | public static DynamicPlayItem build(String name, long start, long length) {
DynamicPlayItem playItem = new DynamicPlayItem(name, start, length);
return playItem;
} | [
"public",
"static",
"DynamicPlayItem",
"build",
"(",
"String",
"name",
",",
"long",
"start",
",",
"long",
"length",
")",
"{",
"DynamicPlayItem",
"playItem",
"=",
"new",
"DynamicPlayItem",
"(",
"name",
",",
"start",
",",
"length",
")",
";",
"return",
"playIte... | Builder for DynamicPlayItem
@param name
name
@param start
start
@param length
length
@return play item instance | [
"Builder",
"for",
"DynamicPlayItem"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/api/stream/support/DynamicPlayItem.java#L186-L189 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/AbstractStream.java | AbstractStream.getMetaData | public Notify getMetaData() {
Notify md = metaData.get();
if (md != null) {
try {
return md.duplicate();
} catch (Exception e) {
}
}
return md;
} | java | public Notify getMetaData() {
Notify md = metaData.get();
if (md != null) {
try {
return md.duplicate();
} catch (Exception e) {
}
}
return md;
} | [
"public",
"Notify",
"getMetaData",
"(",
")",
"{",
"Notify",
"md",
"=",
"metaData",
".",
"get",
"(",
")",
";",
"if",
"(",
"md",
"!=",
"null",
")",
"{",
"try",
"{",
"return",
"md",
".",
"duplicate",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e... | Returns a copy of the metadata for the associated stream, if it exists.
@return stream meta data | [
"Returns",
"a",
"copy",
"of",
"the",
"metadata",
"for",
"the",
"associated",
"stream",
"if",
"it",
"exists",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/AbstractStream.java#L143-L152 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/AbstractStream.java | AbstractStream.setState | public void setState(StreamState newState) {
StreamState oldState = state.get();
if (!oldState.equals(newState) && state.compareAndSet(oldState, newState)) {
fireStateChange(oldState, newState);
}
} | java | public void setState(StreamState newState) {
StreamState oldState = state.get();
if (!oldState.equals(newState) && state.compareAndSet(oldState, newState)) {
fireStateChange(oldState, newState);
}
} | [
"public",
"void",
"setState",
"(",
"StreamState",
"newState",
")",
"{",
"StreamState",
"oldState",
"=",
"state",
".",
"get",
"(",
")",
";",
"if",
"(",
"!",
"oldState",
".",
"equals",
"(",
"newState",
")",
"&&",
"state",
".",
"compareAndSet",
"(",
"oldSta... | Sets the stream state.
@param newState stream state | [
"Sets",
"the",
"stream",
"state",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/AbstractStream.java#L235-L240 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/AbstractStream.java | AbstractStream.getStreamAwareHandler | protected IStreamAwareScopeHandler getStreamAwareHandler() {
if (scope != null) {
IScopeHandler handler = scope.getHandler();
if (handler instanceof IStreamAwareScopeHandler) {
return (IStreamAwareScopeHandler) handler;
}
}
return null;
} | java | protected IStreamAwareScopeHandler getStreamAwareHandler() {
if (scope != null) {
IScopeHandler handler = scope.getHandler();
if (handler instanceof IStreamAwareScopeHandler) {
return (IStreamAwareScopeHandler) handler;
}
}
return null;
} | [
"protected",
"IStreamAwareScopeHandler",
"getStreamAwareHandler",
"(",
")",
"{",
"if",
"(",
"scope",
"!=",
"null",
")",
"{",
"IScopeHandler",
"handler",
"=",
"scope",
".",
"getHandler",
"(",
")",
";",
"if",
"(",
"handler",
"instanceof",
"IStreamAwareScopeHandler",... | Return stream aware scope handler or null if scope is null.
@return IStreamAwareScopeHandler implementation | [
"Return",
"stream",
"aware",
"scope",
"handler",
"or",
"null",
"if",
"scope",
"is",
"null",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/AbstractStream.java#L247-L255 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.encode | 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;
} | java | 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;
} | [
"public",
"IoBuffer",
"encode",
"(",
"Object",
"message",
")",
"throws",
"Exception",
"{",
"if",
"(",
"message",
"!=",
"null",
")",
"{",
"try",
"{",
"return",
"encodePacket",
"(",
"(",
"Packet",
")",
"message",
")",
";",
"}",
"catch",
"(",
"Exception",
... | Encodes object with given protocol state to byte buffer
@param message
Object to encode
@return IoBuffer with encoded data
@throws Exception
Any decoding exception | [
"Encodes",
"object",
"with",
"given",
"protocol",
"state",
"to",
"byte",
"buffer"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L108-L124 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.encodePacket | public IoBuffer encodePacket(Packet packet) {
IoBuffer out = null;
Header header = packet.getHeader();
int channelId = header.getChannelId();
//log.trace("Channel id: {}", channelId);
IRTMPEvent message = packet.getMessage();
if (message instanceof ChunkSize) {
ChunkSize chunkSizeMsg = (ChunkSize) message;
((RTMPConnection) Red5.getConnectionLocal()).getState().setWriteChunkSize(chunkSizeMsg.getSize());
}
// normally the message is expected not to be dropped
if (!dropMessage(channelId, message)) {
//log.trace("Header time: {} message timestamp: {}", header.getTimer(), message.getTimestamp());
IoBuffer data = encodeMessage(header, message);
if (data != null) {
RTMP rtmp = ((RTMPConnection) Red5.getConnectionLocal()).getState();
// set last write packet
rtmp.setLastWritePacket(channelId, packet);
// ensure we're at the beginning
if (data.position() != 0) {
data.flip();
} else {
data.rewind();
}
// length of the data to be chunked
int dataLen = data.limit();
header.setSize(dataLen);
//if (log.isTraceEnabled()) {
//log.trace("Message: {}", data);
//}
// chunk size for writing
int chunkSize = rtmp.getWriteChunkSize();
// number of chunks to write
int numChunks = (int) Math.ceil(dataLen / (float) chunkSize);
// get last header
Header lastHeader = rtmp.getLastWriteHeader(channelId);
if (log.isTraceEnabled()) {
log.trace("Channel id: {} chunkSize: {}", channelId, chunkSize);
}
// attempt to properly guess the size of the buffer we'll need
int bufSize = dataLen + 18 + (numChunks * 2);
//log.trace("Allocated buffer size: {}", bufSize);
out = IoBuffer.allocate(bufSize, false);
out.setAutoExpand(true);
do {
// encode the header
encodeHeader(header, lastHeader, out);
// write a chunk
byte[] buf = new byte[Math.min(chunkSize, data.remaining())];
data.get(buf);
//log.trace("Buffer: {}", Hex.encodeHexString(buf));
out.put(buf);
// move header over to last header
lastHeader = header.clone();
} while (data.hasRemaining());
// collapse the time stamps on the last header after decode is complete
lastHeader.setTimerBase(lastHeader.getTimer());
// clear the delta
lastHeader.setTimerDelta(0);
// set last write header
rtmp.setLastWriteHeader(channelId, lastHeader);
data.free();
out.flip();
data = null;
}
}
message.release();
return out;
} | java | public IoBuffer encodePacket(Packet packet) {
IoBuffer out = null;
Header header = packet.getHeader();
int channelId = header.getChannelId();
//log.trace("Channel id: {}", channelId);
IRTMPEvent message = packet.getMessage();
if (message instanceof ChunkSize) {
ChunkSize chunkSizeMsg = (ChunkSize) message;
((RTMPConnection) Red5.getConnectionLocal()).getState().setWriteChunkSize(chunkSizeMsg.getSize());
}
// normally the message is expected not to be dropped
if (!dropMessage(channelId, message)) {
//log.trace("Header time: {} message timestamp: {}", header.getTimer(), message.getTimestamp());
IoBuffer data = encodeMessage(header, message);
if (data != null) {
RTMP rtmp = ((RTMPConnection) Red5.getConnectionLocal()).getState();
// set last write packet
rtmp.setLastWritePacket(channelId, packet);
// ensure we're at the beginning
if (data.position() != 0) {
data.flip();
} else {
data.rewind();
}
// length of the data to be chunked
int dataLen = data.limit();
header.setSize(dataLen);
//if (log.isTraceEnabled()) {
//log.trace("Message: {}", data);
//}
// chunk size for writing
int chunkSize = rtmp.getWriteChunkSize();
// number of chunks to write
int numChunks = (int) Math.ceil(dataLen / (float) chunkSize);
// get last header
Header lastHeader = rtmp.getLastWriteHeader(channelId);
if (log.isTraceEnabled()) {
log.trace("Channel id: {} chunkSize: {}", channelId, chunkSize);
}
// attempt to properly guess the size of the buffer we'll need
int bufSize = dataLen + 18 + (numChunks * 2);
//log.trace("Allocated buffer size: {}", bufSize);
out = IoBuffer.allocate(bufSize, false);
out.setAutoExpand(true);
do {
// encode the header
encodeHeader(header, lastHeader, out);
// write a chunk
byte[] buf = new byte[Math.min(chunkSize, data.remaining())];
data.get(buf);
//log.trace("Buffer: {}", Hex.encodeHexString(buf));
out.put(buf);
// move header over to last header
lastHeader = header.clone();
} while (data.hasRemaining());
// collapse the time stamps on the last header after decode is complete
lastHeader.setTimerBase(lastHeader.getTimer());
// clear the delta
lastHeader.setTimerDelta(0);
// set last write header
rtmp.setLastWriteHeader(channelId, lastHeader);
data.free();
out.flip();
data = null;
}
}
message.release();
return out;
} | [
"public",
"IoBuffer",
"encodePacket",
"(",
"Packet",
"packet",
")",
"{",
"IoBuffer",
"out",
"=",
"null",
";",
"Header",
"header",
"=",
"packet",
".",
"getHeader",
"(",
")",
";",
"int",
"channelId",
"=",
"header",
".",
"getChannelId",
"(",
")",
";",
"//lo... | Encode packet.
@param packet
RTMP packet
@return Encoded data | [
"Encode",
"packet",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L133-L201 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.getHeaderType | private byte getHeaderType(final Header header, final Header lastHeader) {
//int lastFullTs = ((RTMPConnection) Red5.getConnectionLocal()).getState().getLastFullTimestampWritten(header.getChannelId());
if (lastHeader == null || header.getStreamId() != lastHeader.getStreamId() || header.getTimer() < lastHeader.getTimer()) {
// new header mark if header for another stream
return HEADER_NEW;
} else if (header.getSize() != lastHeader.getSize() || header.getDataType() != lastHeader.getDataType()) {
// same source header if last header data type or size differ
return HEADER_SAME_SOURCE;
} else if (header.getTimer() != lastHeader.getTimer()) {
// timer change marker if there's time gap between header time stamps
return HEADER_TIMER_CHANGE;
}
// continue encoding
return HEADER_CONTINUE;
} | java | private byte getHeaderType(final Header header, final Header lastHeader) {
//int lastFullTs = ((RTMPConnection) Red5.getConnectionLocal()).getState().getLastFullTimestampWritten(header.getChannelId());
if (lastHeader == null || header.getStreamId() != lastHeader.getStreamId() || header.getTimer() < lastHeader.getTimer()) {
// new header mark if header for another stream
return HEADER_NEW;
} else if (header.getSize() != lastHeader.getSize() || header.getDataType() != lastHeader.getDataType()) {
// same source header if last header data type or size differ
return HEADER_SAME_SOURCE;
} else if (header.getTimer() != lastHeader.getTimer()) {
// timer change marker if there's time gap between header time stamps
return HEADER_TIMER_CHANGE;
}
// continue encoding
return HEADER_CONTINUE;
} | [
"private",
"byte",
"getHeaderType",
"(",
"final",
"Header",
"header",
",",
"final",
"Header",
"lastHeader",
")",
"{",
"//int lastFullTs = ((RTMPConnection) Red5.getConnectionLocal()).getState().getLastFullTimestampWritten(header.getChannelId());\r",
"if",
"(",
"lastHeader",
"==",
... | Determine type of header to use.
@param header RTMP message header
@param lastHeader Previous header
@return Header type to use | [
"Determine",
"type",
"of",
"header",
"to",
"use",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L356-L370 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.calculateHeaderSize | 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;
} | java | 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;
} | [
"private",
"int",
"calculateHeaderSize",
"(",
"final",
"Header",
"header",
",",
"final",
"Header",
"lastHeader",
")",
"{",
"final",
"byte",
"headerType",
"=",
"getHeaderType",
"(",
"header",
",",
"lastHeader",
")",
";",
"int",
"channelIdAdd",
"=",
"0",
";",
... | Calculate number of bytes necessary to encode the header.
@param header
RTMP message header
@param lastHeader
Previous header
@return Calculated size | [
"Calculate",
"number",
"of",
"bytes",
"necessary",
"to",
"encode",
"the",
"header",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L381-L391 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.encodeHeader | public IoBuffer encodeHeader(Header header, Header lastHeader) {
final IoBuffer result = IoBuffer.allocate(calculateHeaderSize(header, lastHeader));
encodeHeader(header, lastHeader, result);
return result;
} | java | public IoBuffer encodeHeader(Header header, Header lastHeader) {
final IoBuffer result = IoBuffer.allocate(calculateHeaderSize(header, lastHeader));
encodeHeader(header, lastHeader, result);
return result;
} | [
"public",
"IoBuffer",
"encodeHeader",
"(",
"Header",
"header",
",",
"Header",
"lastHeader",
")",
"{",
"final",
"IoBuffer",
"result",
"=",
"IoBuffer",
".",
"allocate",
"(",
"calculateHeaderSize",
"(",
"header",
",",
"lastHeader",
")",
")",
";",
"encodeHeader",
... | Encode RTMP header.
@param header
RTMP message header
@param lastHeader
Previous header
@return Encoded header data | [
"Encode",
"RTMP",
"header",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L402-L406 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.encodeHeader | 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);
}
/*
Timestamps in RTMP are given as an integer number of milliseconds relative to an unspecified epoch. Typically, each stream will start
with a timestamp of 0, but this is not required, as long as the two endpoints agree on the epoch. Note that this means that any
synchronization across multiple streams (especially from separate hosts) requires some additional mechanism outside of RTMP.
Because timestamps are 32 bits long, they roll over every 49 days, 17 hours, 2 minutes and 47.296 seconds. Because streams are allowed to
run continuously, potentially for years on end, an RTMP application SHOULD use serial number arithmetic [RFC1982] when processing
timestamps, and SHOULD be capable of handling wraparound. For example, an application assumes that all adjacent timestamps are
within 2^31 - 1 milliseconds of each other, so 10000 comes after 4000000000, and 3000000000 comes before 4000000000.
Timestamp deltas are also specified as an unsigned integer number of milliseconds, relative to the previous timestamp. Timestamp deltas
may be either 24 or 32 bits long.
*/
int timeBase = 0, timeDelta = 0;
int headerSize = header.getSize();
// encode the message header section
switch (headerType) {
case HEADER_NEW: // type 0 - 11 bytes
timeBase = header.getTimerBase();
// absolute time - unsigned 24-bit (3 bytes) (chop at max 24bit time)
RTMPUtils.writeMediumInt(buf, Math.min(timeBase, MEDIUM_INT_MAX));
// header size 24-bit (3 bytes)
RTMPUtils.writeMediumInt(buf, headerSize);
// 1 byte
buf.put(header.getDataType());
// little endian 4 bytes
RTMPUtils.writeReverseInt(buf, header.getStreamId().intValue());
header.setTimerDelta(timeDelta);
// write the extended timestamp if we are indicated to do so
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: // type 1 - 7 bytes
// delta type
timeDelta = (int) RTMPUtils.diffTimestamps(header.getTimer(), lastHeader.getTimer());
header.setTimerDelta(timeDelta);
// write the time delta 24-bit 3 bytes
RTMPUtils.writeMediumInt(buf, Math.min(timeDelta, MEDIUM_INT_MAX));
// write header size
RTMPUtils.writeMediumInt(buf, headerSize);
buf.put(header.getDataType());
// write the extended timestamp if we are indicated to do so
if (timeDelta >= MEDIUM_INT_MAX) {
buf.putInt(timeDelta);
header.setExtended(true);
}
// time base is from last header minus delta
timeBase = header.getTimerBase() - timeDelta;
header.setTimerBase(timeBase);
break;
case HEADER_TIMER_CHANGE: // type 2 - 3 bytes
// delta type
timeDelta = (int) RTMPUtils.diffTimestamps(header.getTimer(), lastHeader.getTimer());
header.setTimerDelta(timeDelta);
// write the time delta 24-bit 3 bytes
RTMPUtils.writeMediumInt(buf, Math.min(timeDelta, MEDIUM_INT_MAX));
// write the extended timestamp if we are indicated to do so
if (timeDelta >= MEDIUM_INT_MAX) {
buf.putInt(timeDelta);
header.setExtended(true);
}
// time base is from last header minus delta
timeBase = header.getTimerBase() - timeDelta;
header.setTimerBase(timeBase);
break;
case HEADER_CONTINUE: // type 3 - 0 bytes
// time base from the most recent header
timeBase = header.getTimerBase() - timeDelta;
// write the extended timestamp if we are indicated to do so
if (lastHeader.isExtended()) {
buf.putInt(timeBase);
}
break;
default:
break;
}
log.trace("Encoded chunk {} {}", Header.HeaderType.values()[headerType], header);
} | java | 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);
}
/*
Timestamps in RTMP are given as an integer number of milliseconds relative to an unspecified epoch. Typically, each stream will start
with a timestamp of 0, but this is not required, as long as the two endpoints agree on the epoch. Note that this means that any
synchronization across multiple streams (especially from separate hosts) requires some additional mechanism outside of RTMP.
Because timestamps are 32 bits long, they roll over every 49 days, 17 hours, 2 minutes and 47.296 seconds. Because streams are allowed to
run continuously, potentially for years on end, an RTMP application SHOULD use serial number arithmetic [RFC1982] when processing
timestamps, and SHOULD be capable of handling wraparound. For example, an application assumes that all adjacent timestamps are
within 2^31 - 1 milliseconds of each other, so 10000 comes after 4000000000, and 3000000000 comes before 4000000000.
Timestamp deltas are also specified as an unsigned integer number of milliseconds, relative to the previous timestamp. Timestamp deltas
may be either 24 or 32 bits long.
*/
int timeBase = 0, timeDelta = 0;
int headerSize = header.getSize();
// encode the message header section
switch (headerType) {
case HEADER_NEW: // type 0 - 11 bytes
timeBase = header.getTimerBase();
// absolute time - unsigned 24-bit (3 bytes) (chop at max 24bit time)
RTMPUtils.writeMediumInt(buf, Math.min(timeBase, MEDIUM_INT_MAX));
// header size 24-bit (3 bytes)
RTMPUtils.writeMediumInt(buf, headerSize);
// 1 byte
buf.put(header.getDataType());
// little endian 4 bytes
RTMPUtils.writeReverseInt(buf, header.getStreamId().intValue());
header.setTimerDelta(timeDelta);
// write the extended timestamp if we are indicated to do so
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: // type 1 - 7 bytes
// delta type
timeDelta = (int) RTMPUtils.diffTimestamps(header.getTimer(), lastHeader.getTimer());
header.setTimerDelta(timeDelta);
// write the time delta 24-bit 3 bytes
RTMPUtils.writeMediumInt(buf, Math.min(timeDelta, MEDIUM_INT_MAX));
// write header size
RTMPUtils.writeMediumInt(buf, headerSize);
buf.put(header.getDataType());
// write the extended timestamp if we are indicated to do so
if (timeDelta >= MEDIUM_INT_MAX) {
buf.putInt(timeDelta);
header.setExtended(true);
}
// time base is from last header minus delta
timeBase = header.getTimerBase() - timeDelta;
header.setTimerBase(timeBase);
break;
case HEADER_TIMER_CHANGE: // type 2 - 3 bytes
// delta type
timeDelta = (int) RTMPUtils.diffTimestamps(header.getTimer(), lastHeader.getTimer());
header.setTimerDelta(timeDelta);
// write the time delta 24-bit 3 bytes
RTMPUtils.writeMediumInt(buf, Math.min(timeDelta, MEDIUM_INT_MAX));
// write the extended timestamp if we are indicated to do so
if (timeDelta >= MEDIUM_INT_MAX) {
buf.putInt(timeDelta);
header.setExtended(true);
}
// time base is from last header minus delta
timeBase = header.getTimerBase() - timeDelta;
header.setTimerBase(timeBase);
break;
case HEADER_CONTINUE: // type 3 - 0 bytes
// time base from the most recent header
timeBase = header.getTimerBase() - timeDelta;
// write the extended timestamp if we are indicated to do so
if (lastHeader.isExtended()) {
buf.putInt(timeBase);
}
break;
default:
break;
}
log.trace("Encoded chunk {} {}", Header.HeaderType.values()[headerType], header);
} | [
"public",
"void",
"encodeHeader",
"(",
"Header",
"header",
",",
"Header",
"lastHeader",
",",
"IoBuffer",
"buf",
")",
"{",
"byte",
"headerType",
"=",
"getHeaderType",
"(",
"header",
",",
"lastHeader",
")",
";",
"RTMPUtils",
".",
"encodeHeaderByte",
"(",
"buf",
... | Encode RTMP header into given IoBuffer.
@param header RTMP message header
@param lastHeader Previous header
@param buf Buffer for writing encoded header into | [
"Encode",
"RTMP",
"header",
"into",
"given",
"IoBuffer",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L415-L502 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.encodeServerBW | private IoBuffer encodeServerBW(ServerBW serverBW) {
final IoBuffer out = IoBuffer.allocate(4);
out.putInt(serverBW.getBandwidth());
return out;
} | java | private IoBuffer encodeServerBW(ServerBW serverBW) {
final IoBuffer out = IoBuffer.allocate(4);
out.putInt(serverBW.getBandwidth());
return out;
} | [
"private",
"IoBuffer",
"encodeServerBW",
"(",
"ServerBW",
"serverBW",
")",
"{",
"final",
"IoBuffer",
"out",
"=",
"IoBuffer",
".",
"allocate",
"(",
"4",
")",
";",
"out",
".",
"putInt",
"(",
"serverBW",
".",
"getBandwidth",
"(",
")",
")",
";",
"return",
"o... | Encode server-side bandwidth event.
@param serverBW
Server-side bandwidth event
@return Encoded event data | [
"Encode",
"server",
"-",
"side",
"bandwidth",
"event",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L605-L609 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.encodeClientBW | private IoBuffer encodeClientBW(ClientBW clientBW) {
final IoBuffer out = IoBuffer.allocate(5);
out.putInt(clientBW.getBandwidth());
out.put(clientBW.getLimitType());
return out;
} | java | private IoBuffer encodeClientBW(ClientBW clientBW) {
final IoBuffer out = IoBuffer.allocate(5);
out.putInt(clientBW.getBandwidth());
out.put(clientBW.getLimitType());
return out;
} | [
"private",
"IoBuffer",
"encodeClientBW",
"(",
"ClientBW",
"clientBW",
")",
"{",
"final",
"IoBuffer",
"out",
"=",
"IoBuffer",
".",
"allocate",
"(",
"5",
")",
";",
"out",
".",
"putInt",
"(",
"clientBW",
".",
"getBandwidth",
"(",
")",
")",
";",
"out",
".",
... | Encode client-side bandwidth event.
@param clientBW
Client-side bandwidth event
@return Encoded event data | [
"Encode",
"client",
"-",
"side",
"bandwidth",
"event",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L618-L623 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.encodeCommand | protected IoBuffer encodeCommand(Notify invoke) {
IoBuffer out = IoBuffer.allocate(1024);
out.setAutoExpand(true);
encodeCommand(out, invoke);
return out;
} | java | protected IoBuffer encodeCommand(Notify invoke) {
IoBuffer out = IoBuffer.allocate(1024);
out.setAutoExpand(true);
encodeCommand(out, invoke);
return out;
} | [
"protected",
"IoBuffer",
"encodeCommand",
"(",
"Notify",
"invoke",
")",
"{",
"IoBuffer",
"out",
"=",
"IoBuffer",
".",
"allocate",
"(",
"1024",
")",
";",
"out",
".",
"setAutoExpand",
"(",
"true",
")",
";",
"encodeCommand",
"(",
"out",
",",
"invoke",
")",
... | Encode notification event.
@param invoke
Notification event
@return Encoded event data | [
"Encode",
"notification",
"event",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L801-L806 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.generateErrorResult | protected StatusObject generateErrorResult(String code, Throwable error) {
// Construct error object to return
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) {
// Return exception details to client
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;
} | java | protected StatusObject generateErrorResult(String code, Throwable error) {
// Construct error object to return
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) {
// Return exception details to client
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;
} | [
"protected",
"StatusObject",
"generateErrorResult",
"(",
"String",
"code",
",",
"Throwable",
"error",
")",
"{",
"// Construct error object to return\r",
"String",
"message",
"=",
"\"\"",
";",
"while",
"(",
"error",
"!=",
"null",
"&&",
"error",
".",
"getCause",
"("... | Generate error object to return for given exception.
@param code
call
@param error
error
@return status object | [
"Generate",
"error",
"object",
"to",
"return",
"for",
"given",
"exception",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L976-L1005 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java | RTMPProtocolEncoder.encodeFlexMessage | public IoBuffer encodeFlexMessage(FlexMessage msg) {
IoBuffer out = IoBuffer.allocate(1024);
out.setAutoExpand(true);
// Unknown byte, always 0?
out.put((byte) 0);
encodeCommand(out, msg);
return out;
} | java | public IoBuffer encodeFlexMessage(FlexMessage msg) {
IoBuffer out = IoBuffer.allocate(1024);
out.setAutoExpand(true);
// Unknown byte, always 0?
out.put((byte) 0);
encodeCommand(out, msg);
return out;
} | [
"public",
"IoBuffer",
"encodeFlexMessage",
"(",
"FlexMessage",
"msg",
")",
"{",
"IoBuffer",
"out",
"=",
"IoBuffer",
".",
"allocate",
"(",
"1024",
")",
";",
"out",
".",
"setAutoExpand",
"(",
"true",
")",
";",
"// Unknown byte, always 0?\r",
"out",
".",
"put",
... | Encodes Flex message event.
@param msg
Flex message event
@return Encoded data | [
"Encodes",
"Flex",
"message",
"event",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L1014-L1021 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/bandwidth/ServerClientDetection.java | ServerClientDetection.resultReceived | public void resultReceived(IPendingServiceCall call) {
// if we aren't connection, skip any further testing
if (Call.STATUS_NOT_CONNECTED != call.getStatus()) {
// receive time using nanos
long now = System.nanoTime();
// increment received
int received = packetsReceived.incrementAndGet();
log.debug("Call time stamps - write: {} read: {}", call.getWriteTime(), call.getReadTime());
// time passed is in milliseconds
timePassed = (now - startTime) / 1000000;
log.debug("Received count: {} sent: {} timePassed: {} ms", new Object[] { received, packetsSent.get(), timePassed });
switch (received) {
case 1:
// first packet is used to test latency
latency = Math.max(Math.min(timePassed, LATENCY_MAX), LATENCY_MIN);
log.debug("Receive latency: {}", latency);
// We now have a latency figure so can start sending test data.
// Second call. 1st packet sent
log.debug("Sending first payload at {} ns", now);
callBWCheck(payload); // 1k
break;
case 2:
log.debug("Sending second payload at {} ns", now);
// increment cumulative latency
cumLatency++;
callBWCheck(payload1); // 32k
break;
default:
log.debug("Doing calculations at {} ns", now);
// increment cumulative latency
cumLatency++;
// bytes to kbits
deltaDown = ((conn.getWrittenBytes() - startBytesWritten) * 8) / 1000d;
log.debug("Delta kbits: {}", deltaDown);
// total dl time - latency for each packet sent in secs
deltaTime = (timePassed - (latency * cumLatency));
if (deltaTime <= 0) {
deltaTime = (timePassed + latency);
}
log.debug("Delta time: {} ms", deltaTime);
// calculate kbit/s
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");
}
} | java | public void resultReceived(IPendingServiceCall call) {
// if we aren't connection, skip any further testing
if (Call.STATUS_NOT_CONNECTED != call.getStatus()) {
// receive time using nanos
long now = System.nanoTime();
// increment received
int received = packetsReceived.incrementAndGet();
log.debug("Call time stamps - write: {} read: {}", call.getWriteTime(), call.getReadTime());
// time passed is in milliseconds
timePassed = (now - startTime) / 1000000;
log.debug("Received count: {} sent: {} timePassed: {} ms", new Object[] { received, packetsSent.get(), timePassed });
switch (received) {
case 1:
// first packet is used to test latency
latency = Math.max(Math.min(timePassed, LATENCY_MAX), LATENCY_MIN);
log.debug("Receive latency: {}", latency);
// We now have a latency figure so can start sending test data.
// Second call. 1st packet sent
log.debug("Sending first payload at {} ns", now);
callBWCheck(payload); // 1k
break;
case 2:
log.debug("Sending second payload at {} ns", now);
// increment cumulative latency
cumLatency++;
callBWCheck(payload1); // 32k
break;
default:
log.debug("Doing calculations at {} ns", now);
// increment cumulative latency
cumLatency++;
// bytes to kbits
deltaDown = ((conn.getWrittenBytes() - startBytesWritten) * 8) / 1000d;
log.debug("Delta kbits: {}", deltaDown);
// total dl time - latency for each packet sent in secs
deltaTime = (timePassed - (latency * cumLatency));
if (deltaTime <= 0) {
deltaTime = (timePassed + latency);
}
log.debug("Delta time: {} ms", deltaTime);
// calculate kbit/s
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");
}
} | [
"public",
"void",
"resultReceived",
"(",
"IPendingServiceCall",
"call",
")",
"{",
"// if we aren't connection, skip any further testing",
"if",
"(",
"Call",
".",
"STATUS_NOT_CONNECTED",
"!=",
"call",
".",
"getStatus",
"(",
")",
")",
"{",
"// receive time using nanos",
"... | Handle callback from service call. | [
"Handle",
"callback",
"from",
"service",
"call",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/bandwidth/ServerClientDetection.java#L106-L154 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/message/Packet.java | Packet.setData | public void setData(IoBuffer buffer) {
if (noCopy) {
log.trace("Using buffer reference");
this.data = buffer;
} else {
// try the backing array first if it exists
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");
// fallback to ByteBuffer
data.put(buffer.buf()).flip();
}
}
} | java | public void setData(IoBuffer buffer) {
if (noCopy) {
log.trace("Using buffer reference");
this.data = buffer;
} else {
// try the backing array first if it exists
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");
// fallback to ByteBuffer
data.put(buffer.buf()).flip();
}
}
} | [
"public",
"void",
"setData",
"(",
"IoBuffer",
"buffer",
")",
"{",
"if",
"(",
"noCopy",
")",
"{",
"log",
".",
"trace",
"(",
"\"Using buffer reference\"",
")",
";",
"this",
".",
"data",
"=",
"buffer",
";",
"}",
"else",
"{",
"// try the backing array first if i... | Setter for data
@param buffer
Packet data | [
"Setter",
"for",
"data"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/message/Packet.java#L136-L155 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/message/SharedObjectTypeMapping.java | SharedObjectTypeMapping.toByte | 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;
}
} | java | 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;
}
} | [
"public",
"static",
"byte",
"toByte",
"(",
"Type",
"type",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"SERVER_CONNECT",
":",
"return",
"0x01",
";",
"case",
"SERVER_DISCONNECT",
":",
"return",
"0x02",
";",
"case",
"SERVER_SET_ATTRIBUTE",
":",
"return"... | Convert SO event type to byte representation that RTMP uses
@param type
Event type
@return Byte representation of given event type | [
"Convert",
"SO",
"event",
"type",
"to",
"byte",
"representation",
"that",
"RTMP",
"uses"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/message/SharedObjectTypeMapping.java#L66-L96 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/consumer/ConnectionConsumer.java | ConnectionConsumer.sendChunkSize | 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);
}
} | java | 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);
}
} | [
"private",
"void",
"sendChunkSize",
"(",
")",
"{",
"if",
"(",
"chunkSizeSent",
".",
"compareAndSet",
"(",
"false",
",",
"true",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Sending chunk size: {}\"",
",",
"chunkSize",
")",
";",
"ChunkSize",
"chunkSizeMsg",
"=... | Send the chunk size | [
"Send",
"the",
"chunk",
"size"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/consumer/ConnectionConsumer.java#L284-L290 | train |
Red5/red5-server-common | src/main/java/org/red5/server/stream/consumer/ConnectionConsumer.java | ConnectionConsumer.closeChannels | private void closeChannels() {
conn.closeChannel(video.getId());
conn.closeChannel(audio.getId());
conn.closeChannel(data.getId());
} | java | private void closeChannels() {
conn.closeChannel(video.getId());
conn.closeChannel(audio.getId());
conn.closeChannel(data.getId());
} | [
"private",
"void",
"closeChannels",
"(",
")",
"{",
"conn",
".",
"closeChannel",
"(",
"video",
".",
"getId",
"(",
")",
")",
";",
"conn",
".",
"closeChannel",
"(",
"audio",
".",
"getId",
"(",
")",
")",
";",
"conn",
".",
"closeChannel",
"(",
"data",
"."... | Close all the channels | [
"Close",
"all",
"the",
"channels"
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/consumer/ConnectionConsumer.java#L295-L299 | train |
Red5/red5-server-common | src/main/java/org/red5/server/net/servlet/ServletUtils.java | ServletUtils.copy | 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");
}
} | java | 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");
}
} | [
"public",
"static",
"void",
"copy",
"(",
"HttpServletRequest",
"req",
",",
"OutputStream",
"output",
")",
"throws",
"IOException",
"{",
"InputStream",
"input",
"=",
"req",
".",
"getInputStream",
"(",
")",
";",
"int",
"availableBytes",
"=",
"req",
".",
"getCont... | Copies information from the http request to the output stream using the specified content length.
@param req
Request
@param output
Output stream
@throws java.io.IOException
on error | [
"Copies",
"information",
"from",
"the",
"http",
"request",
"to",
"the",
"output",
"stream",
"using",
"the",
"specified",
"content",
"length",
"."
] | 39ae73710c25bda86d70b13ef37ae707962217b9 | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/servlet/ServletUtils.java#L110-L126 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.