【流媒体】RTMPDump—RTMP_ConnectStream(创建流连接)

目录

  • 1. RTMP_ConnectStream函数
    • 1.1 读取packet(RTMP_ReadPacket)
    • 1.2 解析packet(RTMP_ClientPacket)
      • 1.2.1 设置Chunk Size(HandleChangeChunkSize)
      • 1.2.2 用户控制信息(HandleCtrl)
      • 1.2.3 设置应答窗口大小(HandleServerBW)
      • 1.2.4 设置对端带宽(HandleClientBW)
      • 1.2.5 音频数据(HandleAudio)
      • 1.2.6 视频数据(HandleVideo)
      • 1.2.7 元数据(HandleMetadata)
      • 1.2.8 命令消息(HandleInvoke)
  • 2.小结

RTMP协议相关:
【流媒体】RTMP协议概述
【流媒体】RTMP协议的数据格式
【流媒体】RTMP协议的消息类型
【流媒体】RTMPDump—主流程简单分析
【流媒体】RTMPDump—RTMP_Connect函数(握手、网络连接)
【流媒体】RTMPDump—RTMP_ConnectStream(创建流连接)
【流媒体】RTMPDump—Download(接收流媒体信息)
【流媒体】RTMPDump—AMF编码
【流媒体】基于libRTMP的H264推流器

参考雷博的系列文章(可以从一篇链接到其他文章):
RTMPdump 源代码分析 1: main()函数

1. RTMP_ConnectStream函数

RTMP_ConnectStream()的作用是建立流连接,先回顾一下RTMP标准文档当中是如何进行流的连接的,以client向server发送play命令为例,流程图如下所示。从流程中看,在进行了握手和RTMP连接之后,由client向server发送一个命令 “createStream”,随后由server返回一个命令消息 _result,表示对这个 “createStream” 的反馈。随后进行play命令
在这里插入图片描述
RTMP实现 “createStream” 这条命令的函数为RTMP_ConnectStream(),这个函数的实现比较简单,主要有两个步骤:
(1)读取packet(RTMP_ReadPacket)
(2)解析packet(RTMP_ClientPacket)

int
RTMP_ConnectStream(RTMP * r, int seekTime)
{RTMPPacket packet = { 0 };/* seekTime was already set by SetupStream / SetupURL.* This is only needed by ReconnectStream.*/if (seekTime > 0)r->Link.seekTime = seekTime;r->m_mediaChannel = 0;// 1.读取packetwhile (!r->m_bPlaying && RTMP_IsConnected(r) && RTMP_ReadPacket(r, &packet)){if (RTMPPacket_IsReady(&packet)){if (!packet.m_nBodySize)continue;if ((packet.m_packetType == RTMP_PACKET_TYPE_AUDIO) ||(packet.m_packetType == RTMP_PACKET_TYPE_VIDEO) ||(packet.m_packetType == RTMP_PACKET_TYPE_INFO)){RTMP_Log(RTMP_LOGWARNING, "Received FLV packet before play()! Ignoring.");RTMPPacket_Free(&packet);continue;}// 2.解析packetRTMP_ClientPacket(r, &packet);RTMPPacket_Free(&packet);}}return r->m_bPlaying;
}

1.1 读取packet(RTMP_ReadPacket)

RTMP_ReadPacket()函数的实现如下

int
RTMP_ReadPacket(RTMP * r, RTMPPacket * packet)
{uint8_t hbuf[RTMP_MAX_HEADER_SIZE] = { 0 };char* header = (char*)hbuf;int nSize, hSize, nToRead, nChunk;int didAlloc = FALSE;int extendedTimestamp;RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d", __FUNCTION__, r->m_sb.sb_socket);// 读取packet的第1个字节,即basic headerif (ReadN(r, (char*)hbuf, 1) == 0){RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header", __FUNCTION__);return FALSE;}// fmtpacket->m_headerType = (hbuf[0] & 0xc0) >> 6;// chunk stream id (cs_id)packet->m_nChannel = (hbuf[0] & 0x3f);header++;// 第1字节后6位为0,说明basic header size为2字节if (packet->m_nChannel == 0){if (ReadN(r, (char*)& hbuf[1], 1) != 1){RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header 2nd byte",__FUNCTION__);return FALSE;}packet->m_nChannel = hbuf[1];packet->m_nChannel += 64;header++;}else if (packet->m_nChannel == 1) // 第1字节后6位为1,说明basic header size为3字节{int tmp;if (ReadN(r, (char*)& hbuf[1], 2) != 2){RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header 3nd byte",__FUNCTION__);return FALSE;}tmp = (hbuf[2] << 8) + hbuf[1];packet->m_nChannel = tmp + 64; // 计算cs_idRTMP_Log(RTMP_LOGDEBUG, "%s, m_nChannel: %0x", __FUNCTION__, packet->m_nChannel);header += 2;}// 计算message header sizenSize = packetSize[packet->m_headerType];// cs_id大于已分配的,需要进行重新分配if (packet->m_nChannel >= r->m_channelsAllocatedIn){int n = packet->m_nChannel + 10;int* timestamp = realloc(r->m_channelTimestamp, sizeof(int) * n);RTMPPacket** packets = realloc(r->m_vecChannelsIn, sizeof(RTMPPacket*) * n);if (!timestamp)free(r->m_channelTimestamp);if (!packets)free(r->m_vecChannelsIn);r->m_channelTimestamp = timestamp;r->m_vecChannelsIn = packets;if (!timestamp || !packets) {r->m_channelsAllocatedIn = 0;return FALSE;}memset(r->m_channelTimestamp + r->m_channelsAllocatedIn, 0, sizeof(int) * (n - r->m_channelsAllocatedIn));memset(r->m_vecChannelsIn + r->m_channelsAllocatedIn, 0, sizeof(RTMPPacket*) * (n - r->m_channelsAllocatedIn));r->m_channelsAllocatedIn = n;}// 如果获取到整个header信息,timestamp是绝对值if (nSize == RTMP_LARGE_HEADER_SIZE)	/* if we get a full header the timestamp is absolute */packet->m_hasAbsTimestamp = TRUE;else if (nSize < RTMP_LARGE_HEADER_SIZE){				/* using values from the last message of this channel */if (r->m_vecChannelsIn[packet->m_nChannel])memcpy(packet, r->m_vecChannelsIn[packet->m_nChannel],sizeof(RTMPPacket));}nSize--; // {11, 7, 3, 0}// 读取RTMP的message headerif (nSize > 0 && ReadN(r, header, nSize) != nSize){RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header. type: %x",__FUNCTION__, (unsigned int)hbuf[0]);return FALSE;}hSize = nSize + (header - (char*)hbuf);// 下面根据不同格式的message header来解析字段if (nSize >= 3){// 解析timestampacket->m_nTimeStamp = AMF_DecodeInt24(header);/*RTMP_Log(RTMP_LOGDEBUG, "%s, reading RTMP packet chunk on channel %x, headersz %i, timestamp %i, abs timestamp %i", __FUNCTION__, packet.m_nChannel, nSize, packet.m_nTimeStamp, packet.m_hasAbsTimestamp); */if (nSize >= 6){// 解析message lengthpacket->m_nBodySize = AMF_DecodeInt24(header + 3);packet->m_nBytesRead = 0;if (nSize > 6){// 解析message type idpacket->m_packetType = header[6];if (nSize == 11) // 解析message stream idpacket->m_nInfoField2 = DecodeInt32LE(header + 7);}}}// 检查是否有扩展时间戳,如果有则读取extendedTimestamp = packet->m_nTimeStamp == 0xffffff;if (extendedTimestamp){if (ReadN(r, header + nSize, 4) != 4){RTMP_Log(RTMP_LOGERROR, "%s, failed to read extended timestamp",__FUNCTION__);return FALSE;}packet->m_nTimeStamp = AMF_DecodeInt32(header + nSize);hSize += 4;}RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t*)hbuf, hSize);if (packet->m_nBodySize > 0 && packet->m_body == NULL){if (!RTMPPacket_Alloc(packet, packet->m_nBodySize)){RTMP_Log(RTMP_LOGDEBUG, "%s, failed to allocate packet", __FUNCTION__);return FALSE;}didAlloc = TRUE;packet->m_headerType = (hbuf[0] & 0xc0) >> 6;}// 剩余需要读取的字节数nToRead = packet->m_nBodySize - packet->m_nBytesRead;nChunk = r->m_inChunkSize;if (nToRead < nChunk)nChunk = nToRead;// 是否需要将原始chunk拷贝/* Does the caller want the raw chunk? */if (packet->m_chunk){packet->m_chunk->c_headerSize = hSize;memcpy(packet->m_chunk->c_header, hbuf, hSize);packet->m_chunk->c_chunk = packet->m_body + packet->m_nBytesRead;packet->m_chunk->c_chunkSize = nChunk;}// 获取body的信息if (ReadN(r, packet->m_body + packet->m_nBytesRead, nChunk) != nChunk){RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet body. len: %u",__FUNCTION__, packet->m_nBodySize);return FALSE;}RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t*)packet->m_body + packet->m_nBytesRead, nChunk);packet->m_nBytesRead += nChunk;// 保留该数据包作为该通道上其他数据包的参考/* keep the packet as ref for other packets on this channel */if (!r->m_vecChannelsIn[packet->m_nChannel])r->m_vecChannelsIn[packet->m_nChannel] = malloc(sizeof(RTMPPacket));memcpy(r->m_vecChannelsIn[packet->m_nChannel], packet, sizeof(RTMPPacket));if (extendedTimestamp){r->m_vecChannelsIn[packet->m_nChannel]->m_nTimeStamp = 0xffffff;}// 当前packet所有信息都读取到了,拷贝时间戳并且将当前packet重置if (RTMPPacket_IsReady(packet)){/* make packet's timestamp absolute */if (!packet->m_hasAbsTimestamp)packet->m_nTimeStamp += r->m_channelTimestamp[packet->m_nChannel];	/* timestamps seem to be always relative!! */r->m_channelTimestamp[packet->m_nChannel] = packet->m_nTimeStamp;/* reset the data from the stored packet. we keep the header since we may use it later if a new packet for this channel *//* arrives and requests to re-use some info (small packet header) */r->m_vecChannelsIn[packet->m_nChannel]->m_body = NULL;r->m_vecChannelsIn[packet->m_nChannel]->m_nBytesRead = 0;r->m_vecChannelsIn[packet->m_nChannel]->m_hasAbsTimestamp = FALSE;	/* can only be false if we reuse header */}else{packet->m_body = NULL;	/* so it won't be erased on free */}return TRUE;
}

1.2 解析packet(RTMP_ClientPacket)

该函数的主要作用是解析接收到的数据报,根据数据报的类型进行相应的操作。这些操作包括:
(1)RTMP_PACKET_TYPE_CHUNK_SIZE
设置chunk size

(2)RTMP_PACKET_TYPE_BYTES_READ_REPORT
应答消息,表示已经接收到了传输过来的数据报,返回的是已读取的比特数

(3)RTMP_PACKET_TYPE_CONTROL
用户控制信息

(4)RTMP_PACKET_TYPE_SERVER_BW
设置服务器带宽

(5)RTMP_PACKET_TYPE_CLIENT_BW
设置用户带宽

(6)RTMP_PACKET_TYPE_AUDIO
音频数据

(7)RTMP_PACKET_TYPE_VIDEO
视频数据

(8)RTMP_PACKET_TYPE_FLEX_STREAM_SEND
数据消息,发送元数据或任何用户数据到对端,AMF3 = 15

(9)RTMP_PACKET_TYPE_FLEX_SHARED_OBJECT
共享对象消息, AMF3 = 16

(10)RTMP_PACKET_TYPE_FLEX_MESSAGE
传递AMF编码命令,AMF3 = 17

(11)RTMP_PACKET_TYPE_INFO
数据消息,发送元数据或任何用户数据到对端,AFM0 = 18

(12)RTMP_PACKET_TYPE_SHARED_OBJECT
共享对象消息,AMF0 = 19

(13)RTMP_PACKET_TYPE_INVOKE
传递AMF编码命令,AMF0 = 20

(14)RTMP_PACKET_TYPE_FLASH_VIDEO
聚合消息,一个单一的包含一系列的RTMP子消息的消息;FLV视频

int
RTMP_ClientPacket(RTMP * r, RTMPPacket * packet)
{int bHasMediaPacket = 0;switch (packet->m_packetType){case RTMP_PACKET_TYPE_CHUNK_SIZE:	// 设置chunk size/* chunk size */HandleChangeChunkSize(r, packet);break;case RTMP_PACKET_TYPE_BYTES_READ_REPORT:	// 应答消息,表示已经接收到了传输过来的数据报,返回的是已读取的比特数/* bytes read report */RTMP_Log(RTMP_LOGDEBUG, "%s, received: bytes read report", __FUNCTION__);break;case RTMP_PACKET_TYPE_CONTROL:	// 控制命令/* ctrl */HandleCtrl(r, packet);break;case RTMP_PACKET_TYPE_SERVER_BW:	// 设置服务器带宽/* server bw */HandleServerBW(r, packet);break;case RTMP_PACKET_TYPE_CLIENT_BW:	// 设置用户带宽/* client bw */HandleClientBW(r, packet);break;case RTMP_PACKET_TYPE_AUDIO:		// 音频数据/* audio data *//*RTMP_Log(RTMP_LOGDEBUG, "%s, received: audio %lu bytes", __FUNCTION__, packet.m_nBodySize); */HandleAudio(r, packet);bHasMediaPacket = 1;if (!r->m_mediaChannel)r->m_mediaChannel = packet->m_nChannel;if (!r->m_pausing)r->m_mediaStamp = packet->m_nTimeStamp;break;case RTMP_PACKET_TYPE_VIDEO:		// 视频数据/* video data *//*RTMP_Log(RTMP_LOGDEBUG, "%s, received: video %lu bytes", __FUNCTION__, packet.m_nBodySize); */HandleVideo(r, packet);bHasMediaPacket = 1;if (!r->m_mediaChannel)r->m_mediaChannel = packet->m_nChannel;if (!r->m_pausing)r->m_mediaStamp = packet->m_nTimeStamp;break;case RTMP_PACKET_TYPE_FLEX_STREAM_SEND:	// 数据消息,发送元数据或任何用户数据到对端,AMF3 = 15/* flex stream send */RTMP_Log(RTMP_LOGDEBUG,"%s, flex stream send, size %u bytes, not supported, ignoring",__FUNCTION__, packet->m_nBodySize);break;case RTMP_PACKET_TYPE_FLEX_SHARED_OBJECT:	// 共享对象消息, AMF3 = 16/* flex shared object */RTMP_Log(RTMP_LOGDEBUG,"%s, flex shared object, size %u bytes, not supported, ignoring",__FUNCTION__, packet->m_nBodySize);break;case RTMP_PACKET_TYPE_FLEX_MESSAGE:		// 传递AMF编码命令,AMF3 = 17/* flex message */{RTMP_Log(RTMP_LOGDEBUG,"%s, flex message, size %u bytes, not fully supported",__FUNCTION__, packet->m_nBodySize);/*RTMP_LogHex(packet.m_body, packet.m_nBodySize); *//* some DEBUG code */
#if 0RTMP_LIB_AMFObject obj;int nRes = obj.Decode(packet.m_body + 1, packet.m_nBodySize - 1);if (nRes < 0) {RTMP_Log(RTMP_LOGERROR, "%s, error decoding AMF3 packet", __FUNCTION__);/*return; */}obj.Dump();
#endifif (HandleInvoke(r, packet->m_body + 1, packet->m_nBodySize - 1) == 1)bHasMediaPacket = 2;break;}case RTMP_PACKET_TYPE_INFO:	// 数据消息,发送元数据或任何用户数据到对端,AFM0 = 18/* metadata (notify) */RTMP_Log(RTMP_LOGDEBUG, "%s, received: notify %u bytes", __FUNCTION__,packet->m_nBodySize);if (HandleMetadata(r, packet->m_body, packet->m_nBodySize))bHasMediaPacket = 1;break;case RTMP_PACKET_TYPE_SHARED_OBJECT:	// 共享对象消息, AMF3 = 16RTMP_Log(RTMP_LOGDEBUG, "%s, shared object, not supported, ignoring",__FUNCTION__);break;case RTMP_PACKET_TYPE_INVOKE:	// 传递AMF编码命令,AMF0 = 20/* invoke */RTMP_Log(RTMP_LOGDEBUG, "%s, received: invoke %u bytes", __FUNCTION__,packet->m_nBodySize);/*RTMP_LogHex(packet.m_body, packet.m_nBodySize); */if (HandleInvoke(r, packet->m_body, packet->m_nBodySize) == 1)bHasMediaPacket = 2;break;case RTMP_PACKET_TYPE_FLASH_VIDEO:	// 聚合消息,一个单一的包含一系列的RTMP子消息的消息{// FLV视频现在使用量比较少,这里就不分析了/* go through FLV packets and handle metadata packets */unsigned int pos = 0;uint32_t nTimeStamp = packet->m_nTimeStamp;while (pos + 11 < packet->m_nBodySize){uint32_t dataSize = AMF_DecodeInt24(packet->m_body + pos + 1);	/* size without header (11) and prevTagSize (4) */if (pos + 11 + dataSize + 4 > packet->m_nBodySize){RTMP_Log(RTMP_LOGWARNING, "Stream corrupt?!");break;}if (packet->m_body[pos] == 0x12){HandleMetadata(r, packet->m_body + pos + 11, dataSize);}else if (packet->m_body[pos] == 8 || packet->m_body[pos] == 9){nTimeStamp = AMF_DecodeInt24(packet->m_body + pos + 4);nTimeStamp |= (packet->m_body[pos + 7] << 24);}pos += (11 + dataSize + 4);}if (!r->m_pausing)r->m_mediaStamp = nTimeStamp;/* FLV tag(s) *//*RTMP_Log(RTMP_LOGDEBUG, "%s, received: FLV tag(s) %lu bytes", __FUNCTION__, packet.m_nBodySize); */bHasMediaPacket = 1;break;}default:RTMP_Log(RTMP_LOGDEBUG, "%s, unknown packet type received: 0x%02x", __FUNCTION__,packet->m_packetType);
#ifdef _DEBUGRTMP_LogHex(RTMP_LOGDEBUG, packet->m_body, packet->m_nBodySize);
#endif}return bHasMediaPacket;
}

1.2.1 设置Chunk Size(HandleChangeChunkSize)

static void
HandleChangeChunkSize(RTMP * r, const RTMPPacket * packet)
{if (packet->m_nBodySize >= 4){// 解码4字节AMF编码的信息r->m_inChunkSize = AMF_DecodeInt32(packet->m_body);RTMP_Log(RTMP_LOGDEBUG, "%s, received: chunk size change to %d", __FUNCTION__,r->m_inChunkSize);}
}

1.2.2 用户控制信息(HandleCtrl)

static void
HandleCtrl(RTMP * r, const RTMPPacket * packet)
{short nType = -1;unsigned int tmp;if (packet->m_body && packet->m_nBodySize >= 2)nType = AMF_DecodeInt16(packet->m_body); // 前2个字节为Event typeRTMP_Log(RTMP_LOGDEBUG, "%s, received ctrl. type: %d, len: %d", __FUNCTION__, nType,packet->m_nBodySize);/*RTMP_LogHex(packet.m_body, packet.m_nBodySize); */if (packet->m_nBodySize >= 6){switch (nType){case 0: // Stream Begintmp = AMF_DecodeInt32(packet->m_body + 2);RTMP_Log(RTMP_LOGDEBUG, "%s, Stream Begin %d", __FUNCTION__, tmp);break;case 1: // Stream EOFtmp = AMF_DecodeInt32(packet->m_body + 2);RTMP_Log(RTMP_LOGDEBUG, "%s, Stream EOF %d", __FUNCTION__, tmp);if (r->m_pausing == 1)r->m_pausing = 2;break;case 2: // Stream Drytmp = AMF_DecodeInt32(packet->m_body + 2);RTMP_Log(RTMP_LOGDEBUG, "%s, Stream Dry %d", __FUNCTION__, tmp);break;case 4: // Stream IsRecordedtmp = AMF_DecodeInt32(packet->m_body + 2);RTMP_Log(RTMP_LOGDEBUG, "%s, Stream IsRecorded %d", __FUNCTION__, tmp);break;case 6:		/* server ping. reply with pong. */tmp = AMF_DecodeInt32(packet->m_body + 2);RTMP_Log(RTMP_LOGDEBUG, "%s, Ping %d", __FUNCTION__, tmp);RTMP_SendCtrl(r, 0x07, tmp, 0);break;/* FMS 3.5 servers send the following two controls to let the client* know when the server has sent a complete buffer. I.e., when the* server has sent an amount of data equal to m_nBufferMS in duration.* The server meters its output so that data arrives at the client* in realtime and no faster.** The rtmpdump program tries to set m_nBufferMS as large as* possible, to force the server to send data as fast as possible.* In practice, the server appears to cap this at about 1 hour's* worth of data. After the server has sent a complete buffer, and* sends this BufferEmpty message, it will wait until the play* duration of that buffer has passed before sending a new buffer.* The BufferReady message will be sent when the new buffer starts.* (There is no BufferReady message for the very first buffer;* presumably the Stream Begin message is sufficient for that* purpose.)** If the network speed is much faster than the data bitrate, then* there may be long delays between the end of one buffer and the* start of the next.** Since usually the network allows data to be sent at* faster than realtime, and rtmpdump wants to download the data* as fast as possible, we use this RTMP_LF_BUFX hack: when we* get the BufferEmpty message, we send a Pause followed by an* Unpause. This causes the server to send the next buffer immediately* instead of waiting for the full duration to elapse. (That's* also the purpose of the ToggleStream function, which rtmpdump* calls if we get a read timeout.)** Media player apps don't need this hack since they are just* going to play the data in realtime anyway. It also doesn't work* for live streams since they obviously can only be sent in* realtime. And it's all moot if the network speed is actually* slower than the media bitrate.*//*1. 由于网络通常允许以比实时更快的速度发送数据,并且rtmpdump希望尽可能快地下载数据,因此我们使用RTMP_LF_BUFX hack:当我们获得BufferEmpty消息时,我们发送一个Pause,然后发送一个Unpause这将导致服务器立即发送下一个缓冲区,而不是等待整个持续时间结束。(这也是ToggleStream函数的目的,rtmpdump在读取超时时调用该函数2. 媒体播放器应用程序不需要这个hack,因为它们只是要实时播放数据。它也不适用于直播流,因为它们显然只能实时发送。如果网络速度实际上比媒体比特率慢,那么这一切都没有意义*/case 31: // Stream BufferEmptytmp = AMF_DecodeInt32(packet->m_body + 2);RTMP_Log(RTMP_LOGDEBUG, "%s, Stream BufferEmpty %d", __FUNCTION__, tmp);if (!(r->Link.lFlags & RTMP_LF_BUFX))break;if (!r->m_pausing){r->m_pauseStamp = r->m_mediaChannel < r->m_channelsAllocatedIn ?r->m_channelTimestamp[r->m_mediaChannel] : 0;RTMP_SendPause(r, TRUE, r->m_pauseStamp);r->m_pausing = 1;}else if (r->m_pausing == 2){RTMP_SendPause(r, FALSE, r->m_pauseStamp);r->m_pausing = 3;}break;case 32: // Stream BufferReadytmp = AMF_DecodeInt32(packet->m_body + 2);RTMP_Log(RTMP_LOGDEBUG, "%s, Stream BufferReady %d", __FUNCTION__, tmp);break;default: // Stream xxtmp = AMF_DecodeInt32(packet->m_body + 2);RTMP_Log(RTMP_LOGDEBUG, "%s, Stream xx %d", __FUNCTION__, tmp);break;}}if (nType == 0x1A){RTMP_Log(RTMP_LOGDEBUG, "%s, SWFVerification ping received: ", __FUNCTION__);if (packet->m_nBodySize > 2 && packet->m_body[2] > 0x01){RTMP_Log(RTMP_LOGERROR,"%s: SWFVerification Type %d request not supported! Patches welcome...",__FUNCTION__, packet->m_body[2]);}
#ifdef CRYPTO/*RTMP_LogHex(packet.m_body, packet.m_nBodySize); *//* respond with HMAC SHA256 of decompressed SWF, key is the 30byte player key, also the last 30 bytes of the server handshake are applied */else if (r->Link.SWFSize){RTMP_SendCtrl(r, 0x1B, 0, 0);}else{RTMP_Log(RTMP_LOGERROR,"%s: Ignoring SWFVerification request, use --swfVfy!",__FUNCTION__);}
#elseRTMP_Log(RTMP_LOGERROR,"%s: Ignoring SWFVerification request, no CRYPTO support!",__FUNCTION__);
#endif}
}

1.2.3 设置应答窗口大小(HandleServerBW)

从RTMPDump代码中看,这条命令消息通常由client发出到server,用于设置应答窗口大小

static void
HandleServerBW(RTMP * r, const RTMPPacket * packet)
{r->m_nServerBW = AMF_DecodeInt32(packet->m_body);RTMP_Log(RTMP_LOGDEBUG, "%s: server BW = %d", __FUNCTION__, r->m_nServerBW);
}

1.2.4 设置对端带宽(HandleClientBW)

从RTMPDump代码中看,这条命令通常由server发送给client,用于设置client发送带宽

static void
HandleClientBW(RTMP * r, const RTMPPacket * packet)
{// 解析带宽r->m_nClientBW = AMF_DecodeInt32(packet->m_body);// m_nClientBW2表示limit type/*1)Limit type = 0 (Hard Limit)硬限制,对端应该限制其输出带宽到指示的窗口大小(2)Limit type = 1 (Soft Limit)对端应该限制其输出带宽到知识的窗口大小,或者已经有限制在其作用的话就取两者之间的较小值(3)Limit type = 2(Dynamic Limit)如果先前的限制类型为 Hard,处理这个消息就好像它被标记为 Hard,否则的话忽略这个消息*/if (packet->m_nBodySize > 4)r->m_nClientBW2 = packet->m_body[4];elser->m_nClientBW2 = -1;RTMP_Log(RTMP_LOGDEBUG, "%s: client BW = %d %d", __FUNCTION__, r->m_nClientBW,r->m_nClientBW2);
}

1.2.5 音频数据(HandleAudio)

这个函数没有在RTMPDump中实现

static void
HandleAudio(RTMP * r, const RTMPPacket * packet)
{
}

1.2.6 视频数据(HandleVideo)

这个函数没有在RTMPDump中实现

static void
HandleVideo(RTMP * r, const RTMPPacket * packet)
{
}

1.2.7 元数据(HandleMetadata)

static int
HandleMetadata(RTMP * r, char* body, unsigned int len)
{/* allright we get some info here, so parse it and print it *//* also keep duration or filesize to make a nice progress bar */AMFObject obj;AVal metastring;int ret = FALSE;int nRes = AMF_Decode(&obj, body, len, FALSE);if (nRes < 0){RTMP_Log(RTMP_LOGERROR, "%s, error decoding meta data packet", __FUNCTION__);return FALSE;}AMF_Dump(&obj);AMFProp_GetString(AMF_GetProp(&obj, NULL, 0), &metastring);if (AVMATCH(&metastring, &av_onMetaData)){AMFObjectProperty prop;/* Show metadata */RTMP_Log(RTMP_LOGINFO, "Metadata:");DumpMetaData(&obj); // 输出metadata格式if (RTMP_FindFirstMatchingProperty(&obj, &av_duration, &prop)){r->m_fDuration = prop.p_vu.p_number;/*RTMP_Log(RTMP_LOGDEBUG, "Set duration: %.2f", m_fDuration); */}// 寻找音频或视频标记/* Search for audio or video tags */if (RTMP_FindPrefixProperty(&obj, &av_video, &prop))r->m_read.dataType |= 1;if (RTMP_FindPrefixProperty(&obj, &av_audio, &prop))r->m_read.dataType |= 4;ret = TRUE;}AMF_Reset(&obj);return ret;
}

1.2.8 命令消息(HandleInvoke)

在RTMPDump中,该函数主要被用于处理server返回过来的命令消息

/* Returns 0 for OK/Failed/error, 1 for 'Stop or Complete' */
static int
HandleInvoke(RTMP * r, const char* body, unsigned int nBodySize)
{AMFObject obj;AVal method;double txn;int ret = 0, nRes;if (body[0] != 0x02)		/* make sure it is a string method name we start with */{RTMP_Log(RTMP_LOGWARNING, "%s, Sanity failed. no string method in invoke packet",__FUNCTION__);return 0;}nRes = AMF_Decode(&obj, body, nBodySize, FALSE);if (nRes < 0){RTMP_Log(RTMP_LOGERROR, "%s, error decoding invoke packet", __FUNCTION__);return 0;}AMF_Dump(&obj);AMFProp_GetString(AMF_GetProp(&obj, NULL, 0), &method);txn = AMFProp_GetNumber(AMF_GetProp(&obj, NULL, 1));RTMP_Log(RTMP_LOGDEBUG, "%s, server invoking <%s>", __FUNCTION__, method.av_val);if (AVMATCH(&method, &av__result))	// 检查是否是av__result命令{AVal methodInvoked = { 0 };int i;for (i = 0; i < r->m_numCalls; i++) {if (r->m_methodCalls[i].num == (int)txn) {methodInvoked = r->m_methodCalls[i].name;AV_erase(r->m_methodCalls, &r->m_numCalls, i, FALSE);break;}}if (!methodInvoked.av_val) {RTMP_Log(RTMP_LOGDEBUG, "%s, received result id %f without matching request",__FUNCTION__, txn);goto leave;}RTMP_Log(RTMP_LOGDEBUG, "%s, received result for method call <%s>", __FUNCTION__,methodInvoked.av_val);// 检查是否是av_connect命令/*我理解这里的意思应该是,从server返回了一个result,并且是client发送出去av_connect的result*/if (AVMATCH(&methodInvoked, &av_connect)){if (r->Link.token.av_len){AMFObjectProperty p;if (RTMP_FindFirstMatchingProperty(&obj, &av_secureToken, &p)){DecodeTEA(&r->Link.token, &p.p_vu.p_aval);SendSecureTokenResponse(r, &p.p_vu.p_aval);}}if (r->Link.protocol & RTMP_FEATURE_WRITE){SendReleaseStream(r);SendFCPublish(r);}else{RTMP_SendServerBW(r);RTMP_SendCtrl(r, 3, 0, 300);}// 前面发送的connect已经成功了,现在可以发送申请创建流的命令RTMP_SendCreateStream(r);if (!(r->Link.protocol & RTMP_FEATURE_WRITE)){/* Authenticate on Justin.tv legacy servers before sending FCSubscribe */if (r->Link.usherToken.av_len)SendUsherToken(r, &r->Link.usherToken);/* Send the FCSubscribe if live stream or if subscribepath is set */if (r->Link.subscribepath.av_len)SendFCSubscribe(r, &r->Link.subscribepath);else if (r->Link.lFlags & RTMP_LF_LIVE)SendFCSubscribe(r, &r->Link.playpath);}}else if (AVMATCH(&methodInvoked, &av_createStream)) // 检查是否是av_createStream命令{r->m_stream_id = (int)AMFProp_GetNumber(AMF_GetProp(&obj, NULL, 3));if (r->Link.protocol & RTMP_FEATURE_WRITE){SendPublish(r);}else{if (r->Link.lFlags & RTMP_LF_PLST)SendPlaylist(r);// 前面发送的av_createStream命令成功了,现在可以发送play和control的命令SendPlay(r);RTMP_SendCtrl(r, 3, r->m_stream_id, r->m_nBufferMS);}}else if (AVMATCH(&methodInvoked, &av_play) ||AVMATCH(&methodInvoked, &av_publish)) // 检查是否是av_play或av_publish命令{r->m_bPlaying = TRUE;}free(methodInvoked.av_val);}else if (AVMATCH(&method, &av_onBWDone)) // 检查是否是av_onBWDone命令{if (!r->m_nBWCheckCounter)SendCheckBW(r);}else if (AVMATCH(&method, &av_onFCSubscribe)) // 检查是否是av_onFCSubscribe命令{/* SendOnFCSubscribe(); */}else if (AVMATCH(&method, &av_onFCUnsubscribe)) // 检查是否是av_onFCUnsubscribe命令{RTMP_Close(r);ret = 1;}else if (AVMATCH(&method, &av_ping)) // 检查是否是av_ping命令{SendPong(r, txn);}else if (AVMATCH(&method, &av__onbwcheck)) // 检查是否是av__onbwcheck命令{SendCheckBWResult(r, txn);}else if (AVMATCH(&method, &av__onbwdone)) // 检查是否是av__onbwdone命令{int i;for (i = 0; i < r->m_numCalls; i++)if (AVMATCH(&r->m_methodCalls[i].name, &av__checkbw)){AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE);break;}}else if (AVMATCH(&method, &av__error)) // 检查是否是av__error命令{
#ifdef CRYPTOAVal methodInvoked = { 0 };int i;if (r->Link.protocol & RTMP_FEATURE_WRITE){for (i = 0; i < r->m_numCalls; i++){if (r->m_methodCalls[i].num == txn){methodInvoked = r->m_methodCalls[i].name;AV_erase(r->m_methodCalls, &r->m_numCalls, i, FALSE);break;}}if (!methodInvoked.av_val){RTMP_Log(RTMP_LOGDEBUG, "%s, received result id %f without matching request",__FUNCTION__, txn);goto leave;}RTMP_Log(RTMP_LOGDEBUG, "%s, received error for method call <%s>", __FUNCTION__,methodInvoked.av_val);if (AVMATCH(&methodInvoked, &av_connect)){AMFObject obj2;AVal code, level, description;AMFProp_GetObject(AMF_GetProp(&obj, NULL, 3), &obj2);AMFProp_GetString(AMF_GetProp(&obj2, &av_code, -1), &code);AMFProp_GetString(AMF_GetProp(&obj2, &av_level, -1), &level);AMFProp_GetString(AMF_GetProp(&obj2, &av_description, -1), &description);RTMP_Log(RTMP_LOGDEBUG, "%s, error description: %s", __FUNCTION__, description.av_val);/* if PublisherAuth returns 1, then reconnect */if (PublisherAuth(r, &description) == 1){CloseInternal(r, 1);if (!RTMP_Connect(r, NULL) || !RTMP_ConnectStream(r, 0))goto leave;}}}else{RTMP_Log(RTMP_LOGERROR, "rtmp server sent error");}free(methodInvoked.av_val);
#elseRTMP_Log(RTMP_LOGERROR, "rtmp server sent error");
#endif}else if (AVMATCH(&method, &av_close)) // 检查是否是av_close命令{RTMP_Log(RTMP_LOGERROR, "rtmp server requested close");RTMP_Close(r);}else if (AVMATCH(&method, &av_onStatus)) // 检查是否是av_onStatus命令{	// server使用“onStatus”命令向client发送NetStream状态更新AMFObject obj2;AVal code, level;AMFProp_GetObject(AMF_GetProp(&obj, NULL, 3), &obj2);AMFProp_GetString(AMF_GetProp(&obj2, &av_code, -1), &code);AMFProp_GetString(AMF_GetProp(&obj2, &av_level, -1), &level);RTMP_Log(RTMP_LOGDEBUG, "%s, onStatus: %s", __FUNCTION__, code.av_val);if (AVMATCH(&code, &av_NetStream_Failed)|| AVMATCH(&code, &av_NetStream_Play_Failed)|| AVMATCH(&code, &av_NetStream_Play_StreamNotFound)|| AVMATCH(&code, &av_NetConnection_Connect_InvalidApp)){r->m_stream_id = -1;RTMP_Close(r);RTMP_Log(RTMP_LOGERROR, "Closing connection: %s", code.av_val);}else if (AVMATCH(&code, &av_NetStream_Play_Start)|| AVMATCH(&code, &av_NetStream_Play_PublishNotify)){int i;r->m_bPlaying = TRUE;for (i = 0; i < r->m_numCalls; i++){if (AVMATCH(&r->m_methodCalls[i].name, &av_play)){AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE);break;}}}else if (AVMATCH(&code, &av_NetStream_Publish_Start)){int i;r->m_bPlaying = TRUE;for (i = 0; i < r->m_numCalls; i++){if (AVMATCH(&r->m_methodCalls[i].name, &av_publish)){AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE);break;}}}/* Return 1 if this is a Play.Complete or Play.Stop */else if (AVMATCH(&code, &av_NetStream_Play_Complete)|| AVMATCH(&code, &av_NetStream_Play_Stop)|| AVMATCH(&code, &av_NetStream_Play_UnpublishNotify)){RTMP_Close(r);ret = 1;}else if (AVMATCH(&code, &av_NetStream_Seek_Notify)){r->m_read.flags &= ~RTMP_READ_SEEKING;}else if (AVMATCH(&code, &av_NetStream_Pause_Notify)){if (r->m_pausing == 1 || r->m_pausing == 2){RTMP_SendPause(r, FALSE, r->m_pauseStamp);r->m_pausing = 3;}}}else if (AVMATCH(&method, &av_playlist_ready)){int i;for (i = 0; i < r->m_numCalls; i++){if (AVMATCH(&r->m_methodCalls[i].name, &av_set_playlist)){AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE);break;}}}else{}
leave:AMF_Reset(&obj);return ret;
}

现在假设状态为client向server发送了av_connect命令,server会给予一个反馈,client会根据这个反馈去进行下一步的操作,如果server告诉client,connect成功了,现在就可以调用RTMP_SendCreateStream()函数发送av_createStream命令,RTMP_SendCreateStream()函数定义如下

int
RTMP_SendCreateStream(RTMP * r)
{RTMPPacket packet;char pbuf[256], * pend = pbuf + sizeof(pbuf);char* enc;packet.m_nChannel = 0x03;	/* control channel (invoke) */packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;packet.m_nTimeStamp = 0;packet.m_nInfoField2 = 0;packet.m_hasAbsTimestamp = 0;packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;enc = packet.m_body;enc = AMF_EncodeString(enc, pend, &av_createStream); // 写入av_createStream命令enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);*enc++ = AMF_NULL;		/* NULL */packet.m_nBodySize = enc - packet.m_body;return RTMP_SendPacket(r, &packet, TRUE);
}

2.小结

本文记录了使用RTMP进行流连接的过程,主要内容包括:
(1)读取server反馈的packet
(2)解析packet。前面client已经发送了av_connect命令,这里会解析这条命令是否成功,如果成功则可以使用RTMP_SendCreateStream()来发送av_createStream命令,申请创建流连接

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/50941.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

嵌入式开发就业方向有哪些?前景未来可期!

在科技日新月异的今天&#xff0c;嵌入式系统几乎渗透到了我们生活的各个角落。从简单的家用电器到复杂的工业自动化设备&#xff0c;再到我们手中的智能手机&#xff0c;无一不体现出嵌入式技术的魅力。因此&#xff0c;嵌入式领域的就业前景广阔&#xff0c;为众多求职者提供…

职场难题怎么破?六西格玛培训给你答案!

在当今追求高效与卓越的职场环境中&#xff0c;六西格玛培训如同一股强劲的东风&#xff0c;为众多职场人士带来了提升自我、突破瓶颈的契机。作为起源于摩托罗拉、在通用电气得到广泛应用的管理方法论&#xff0c;六西格玛以其严谨的数据分析、持续的流程优化和卓越的质量提升…

公认最强充电宝有哪些?盘点四款公认强悍级别充电宝推荐

随着智能手机和其他移动设备的广泛应用&#xff0c;充电宝已经成为我们生活中不可或缺的一部分。然而&#xff0c;市场上众多品牌和型号的充电宝也让消费者面临选择难题&#xff0c;安全隐患也随之浮现。因此&#xff0c;选择一款安全可靠、性能卓越的充电宝显得尤为重要。本文…

[数据集][目标检测]起子检测数据集VOC+YOLO格式1215张1类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;1215 标注数量(xml文件个数)&#xff1a;1215 标注数量(txt文件个数)&#xff1a;1215 标注…

python逻辑控制 学习

if 语句 普通if &#xff0c;与多条件语句 #! /usr/bin/python3 age int(input("请输入你的年龄&#xff1a;")) print("你今年", age, "岁了。") if age < 18:print("你还未成年&#xff0c;请多加努力&#xff01;") elif age …

[802.11e]WMM

WMM概念 WiFi WMM&#xff08;无线多媒体&#xff09;是一种用于无线局域网&#xff08;WLAN&#xff09;的QoS&#xff08;服务质量&#xff09;标准。WMM旨在提供更好的网络性能&#xff0c;特别是在传输多媒体内容&#xff08;如音频和视频&#xff09;时。它通过对不同类型…

Halcon20.11深度学习目标检测模型

1.前言&#xff1a;.Halcon的深度学习标注工具一直在更新&#xff0c;我下载的20.11版本的Deep Learning Tool已经显示过期&#xff0c;无奈只能下载最新版MVTec Deep Learning Tool 24.05。不过最新版的标注工具做的很人性化&#xff0c;分类&#xff0c;目标检测&#xff0c;…

获取阿里云Docker镜像加速器地址

注册并登录阿里云账号&#xff1a;首先&#xff0c;你需要有一个阿里云账号。如果还没有&#xff0c;可以在阿里云官网注册。 访问容器镜像服务&#xff1a;登录后&#xff0c;进入“产品与服务”&#xff0c;找到“容器服务”或“容器镜像服务”。阿里云容器服务 找到镜像加…

iOS开发进阶(二十二):Xcode* 离线安装 iOS Simulator

文章目录 一、前言二、模拟器安装 一、前言 Xcode 15 安装包的大小相比之前更小&#xff0c;因为除了 macOS 的 Components&#xff0c;其他都需要动态下载安装&#xff0c;否则提示 iOS 17 Simulator Not Installed。 如果不安装对应的运行模拟库&#xff0c;真机和模拟器无法…

【UE】关卡实例基本介绍与使用

目录 一、什么是关卡实例 二、创建关卡实例 三、编辑关卡实例 四、破坏关卡实例 五、创建关卡实例蓝图 一、什么是关卡实例 关卡实例本质上是一个已存在关卡的可重复使用的实例化版本。它基于原始关卡&#xff0c;但可以在运行时进行独立的修改和定制&#xff0c;同时保持…

哪个牌子的开放式耳机性价比高?五款地表最强机型推荐!

在我们的日常生活中&#xff0c;街道、地铁车厢或公交车等地方常常充满了噪音&#xff0c;这些杂音不仅可能扰乱心情&#xff0c;还可能对我们的听力造成潜在的伤害。在这样的环境下&#xff0c;如果想要享受音乐或追剧&#xff0c;同时又能保持对周围环境的警觉&#xff0c;开…

【WebSocket】websocket学习【二】

1.需求&#xff1a;通过websocket实现在线聊天室 2.流程分析 3.消息格式 客户端 --> 服务端 {"toName":"张三","message":"你好"}服务端 --> 客户端 系统消息格式&#xff1a;{"system":true,"fromName"…

全自动内衣洗衣机什么牌子好?五款业界高性能内衣洗衣机推荐

在日常生活中&#xff0c;内衣洗衣机已成为现代家庭必备的重要家电之一。选择一款耐用、质量优秀的内衣洗衣机&#xff0c;不仅可以减少洗衣负担&#xff0c;还能提供高效的洗涤效果。然而&#xff0c;市场上众多内衣洗衣机品牌琳琅满目&#xff0c;让我们往往难以选择。那么&a…

google浏览器chrome用户数据(拓展程序,书签等)丢失问题

一、问题背景 我出现这个情况的问题背景是&#xff1a;因为C盘块满了想清理一部分空间&#xff08;具体看这&#xff1a;windows -- C盘清理_c盘softwaredistribution-CSDN博客&#xff09;&#xff0c;于是找到了更改AppDatta这个方法&#xff0c;但因为&#xff0c;当时做迁移…

文本匹配任务(上)

文本匹配任务 1.文本匹配介绍1.1文本匹配定义1.1.1狭义定义1.1.2广义定义 1.2文本匹配应用1.2.1问答对话1.2.1信息检索 2.文本匹配--智能问答2.1基本思路2.2技术路线分类2.2.1按基础资源划分2.2.2 答案生成方式2.2.3 NLP技术 2.3智能问答-Faq知识库问答2.3.1运行逻辑2.3.2核心关…

QT中鼠标事件示例(包含点击,点击之后移动,释放的坐标获取)

QT中的鼠标事件 简介&#xff1a;结果展示&#xff1a;实例代码&#xff1a; 简介&#xff1a; 在Qt中&#xff0c;处理鼠标事件是图形用户界面&#xff08;GUI&#xff09;编程中的一个重要方面。Qt通过一系列的事件处理函数来支持鼠标事件的响应。这些事件包括鼠标点击&…

【容器安全系列Ⅲ】- 深入了解Capabilities的作用

在本系列的上一部分中&#xff0c;我们提到 Docker 容器尚未使用 time 命名空间。我们还探讨了容器在许多情况下如何以 root 用户身份运行。考虑到这两点&#xff0c;如果我们尝试更改容器内的日期和时间会发生什么&#xff1f; 为了测试这一点&#xff0c;我们先运行 docker r…

Golang | Leetcode Golang题解之第338题比特位计数

题目&#xff1a; 题解&#xff1a; func countBits(n int) []int {bits : make([]int, n1)for i : 1; i < n; i {bits[i] bits[i&(i-1)] 1}return bits }

Excel数字中间指定位置插入符号——以120120加*为例

设置单元格格式——自定义 更多阅读Excel数字中间指定位置插入符号_哔哩哔哩_bilibili

【Linux】2.Linux常见指令以及权限理解(1)

文章目录 1.Xshell的一些快捷键操作2.Linux指令2.1常用指令示例2.2常用指令选项2.2.1 ls指令2.2.2 cd/pwd/shoami指令2.2.3 touch指令2.2.4 mkdir指令2.2.5 rmdir指令2.2.6 rm指令 1.Xshell的一些快捷键操作 Xshell&#xff1a; altenter&#xff1a;Xshell自动全屏&#xff0c…