SRS 代码分析【HLS切片】

来源:互联网 发布:java gbk转utf8 编辑:程序博客网 时间:2024/05/17 22:46

转载:http://blog.csdn.net/ManagerUser/article/details/76087151

一、前言

        SRS流媒体服务器支持rtmp协议,但是rtmp协议仅仅支持PC直播。移动端直播需要HLS协议,HLS协议是苹果公司开发出来的,用于移动端视频直播,Android也对HLS做了友好支持。所以,SRS流媒体服务器支持rtmp协议和hls协议,满足了PC和移动端直播要求。
     HLS协议有两个关键文件:.m3u8文件和.ts文件:
  • .m3u8文件:播放控制文件,存放了地址和播放参数。
  • .ts文件:真正存储视频文件。
相关HLS协议详细说明参见:https://www.jianshu.com/p/2ce402a485ca。

       SRS流媒体接受到通过rtmp传输协议传输的编码格式为H264/AAC(注意:HLS协议只支持Video编码:H264;Audio编码:AAC/mp3)音视频数据,进行切片成.m3u8文件和.ts文件,存储在磁盘或者内存当中(注意:一般为了提高cpu使用率,将.m3u8和.ts文件存储在内存中)。再通过nginx分发到端(注意:nginx工作目录要和存储.m3u8路径一致)。

       HLS切片处理,其实就是ts编码的处理,通过将H264/AAC编码数据按照TS协议来分成一个一个的TS包。TS协议规定,TS首包内容为PAT(Program Association Table 节目关联表)表,其PID为0x0;接下来为PMT(Program Map Table 节目映射表)表,其PID为0x1001。其次,视频帧PID为:0x100,音频PID为:0x101。后面TS包为实际音视频数据。

二、代码分析

SRS源码相关其他总结:
       SRS(simple-rtmp-server)流媒体服务器源码分析--系统启动
       SRS(simple-rtmp-server)流媒体服务器源码分析--RTMP消息play
       SRS(simple-rtmp-server)流媒体服务器源码分析--RTMP信息Publish
       SRS(simple-rtmp-server)流媒体服务器源码分析--HLS切片

SRS源码HLS处理框架如下:



接着SRS(simple-rtmp-server)流媒体服务器源码分析--RTMP消息play分析,在接受到rtmp信息之后,进行HLS处理。

[cpp] view plain copy
  1. int SrsSource::on_video_imp(SrsSharedPtrMessage* msg)  
在函数中,除了转发给client和forward之外,还有HLS处理。注意:在HLS这一讲中,只分析跟video相关的代码,audio类同。

[cpp] view plain copy
  1. #ifdef SRS_AUTO_HLS  
  2.     if ((ret = hls->on_video(msg, is_sequence_header)) != ERROR_SUCCESS) {  
  3.         // apply the error strategy for hls.  
  4.         // @see https://github.com/ossrs/srs/issues/264  
  5.         std::string hls_error_strategy = _srs_config->get_hls_on_error(_req->vhost);  
  6.         if (srs_config_hls_is_on_error_ignore(hls_error_strategy)) {  
  7.             srs_warn("hls process video message failed, ignore and disable hls. ret=%d", ret);  
  8.             // unpublish, ignore ret.  
  9.             hls->on_unpublish();  
  10.             // ignore.  
  11.             ret = ERROR_SUCCESS;  
  12.         } else if (srs_config_hls_is_on_error_continue(hls_error_strategy)) {  
  13.             if (srs_hls_can_continue(ret, cache_sh_video, msg)) {  
  14.                 ret = ERROR_SUCCESS;  
  15.             } else {  
  16.                 srs_warn("hls continue video failed. ret=%d", ret);  
  17.                 return ret;  
  18.             }  
  19.         } else {  
  20.             srs_warn("hls disconnect publisher for video error. ret=%d", ret);  
  21.             return ret;  
  22.         }  
  23.     }  
  24. #endif  
进入on_video(),
[cpp] view plain copy
  1. int SrsHls::on_video(SrsSharedPtrMessage* shared_video, bool is_sps_pps)  
  2. {  
  3.     int ret = ERROR_SUCCESS;  
  4.       
  5.     if (!hls_enabled) {  
  6.         return ret;  
  7.     }  
  8.       
  9.     // update the hls time, for hls_dispose.  
  10.     last_update_time = srs_get_system_time_ms();  
  11.   
  12.     SrsSharedPtrMessage* video = shared_video->copy();  
  13.     SrsAutoFree(SrsSharedPtrMessage, video);  
  14.       
  15.     // user can disable the sps parse to workaround when parse sps failed.  
  16.     // @see https://github.com/ossrs/srs/issues/474  
  17.     /* 
  18.         SPS: 
  19.             H.264中定义的sequence parameter sets中包括了一个图像序列的所有信息.它也是H.264的基础之一 
  20.         PPS: 
  21.             H.264中定义的picture parameter sets中包括了一个图像的所有切片信息.它也是H.264的基础之一 
  22.     */  
  23.     if (is_sps_pps) {  
  24.         codec->avc_parse_sps = _srs_config->get_parse_sps(_req->vhost);  
  25.     }  
  26.       
  27.     sample->clear();  
  28.     //检查H264编码,序列头  
  29.     if ((ret = codec->video_avc_demux(video->payload, video->size, sample)) != ERROR_SUCCESS) {  
  30.         srs_error("hls codec demux video failed. ret=%d", ret);  
  31.         return ret;  
  32.     }  
  33.     srs_info("video decoded, type=%d, codec=%d, avc=%d, cts=%d, size=%d, time=%"PRId64,   
  34.         sample->frame_type, codec->video_codec_id, sample->avc_packet_type, sample->cts, video->size, video->timestamp);  
  35.       
  36.     // ignore info frame,  
  37.     // @see https://github.com/ossrs/srs/issues/288#issuecomment-69863909  
  38.     if (sample->frame_type == SrsCodecVideoAVCFrameVideoInfoFrame) {  
  39.         return ret;  
  40.     }  
  41.       
  42.     if (codec->video_codec_id != SrsCodecVideoAVC) {  
  43.         return ret;  
  44.     }  
  45.       
  46.     // ignore sequence header  
  47.     if (sample->frame_type == SrsCodecVideoAVCFrameKeyFrame  
  48.          && sample->avc_packet_type == SrsCodecVideoAVCTypeSequenceHeader) {  
  49.         return hls_cache->on_sequence_header(muxer);  
  50.     }  
  51.     // rtmp抖动矫正  
  52.     // TODO: FIXME: config the jitter of HLS.  
  53.     if ((ret = jitter->correct(video, SrsRtmpJitterAlgorithmOFF)) != ERROR_SUCCESS) {  
  54.         srs_error("rtmp jitter correct video failed. ret=%d", ret);  
  55.         return ret;  
  56.     }  
  57.     // PAR(pixel aspect ratio):像素横纵比 方形为1,长方形小于1  
  58.     // DAR(display aspect ratio):显示比例 16:9   4:3  
  59.     /* 
  60.         DTS:Decode Time Stamp.DTS主要是标识读入内存的字节流在什么时候开始送人解码器中进行解码 
  61.         DTS主要是用于视频解码,在解码阶段使用 
  62.         PTS主要用于视频同步和输出,在显示阶段使用,在没有B frame的情况下,DTS和PTS的输出顺序是一样的 
  63.     */   
  64.     int64_t dts = video->timestamp * 90;  
  65.     stream_dts = dts;  
  66.     if ((ret = hls_cache->write_video(codec, muxer, dts, sample)) != ERROR_SUCCESS) {  
  67.         srs_error("hls cache write video failed. ret=%d", ret);  
  68.         return ret;  
  69.     }  
  70.       
  71.     // pithy print message.  
  72.     hls_show_mux_log();  
  73.       
  74.     return ret;  
  75. }  
在该函数中做了几个工作:

1、获取H264编码信息SPS和PPS,注意:SPS和PPS不是每个流中都会有的,它只包含在头帧当中。

2、检测视频压缩编码格式:必须为H264,否则直接退出。

3、RTMP抖动矫正(不清楚做了些什么事,不管了)

4、HLS切片处理。

以上4点,前三点不在这里详细说明。只看HLS切片部分:

[cpp] view plain copy
  1. int SrsHlsCache::write_video(SrsAvcAacCodec* codec, SrsHlsMuxer* muxer, int64_t dts, SrsCodecSample* sample)  
  2. {  
  3.     int ret = ERROR_SUCCESS;  
  4.       
  5.     // write video to cache.  
  6.     if ((ret = cache->cache_video(codec, dts, sample)) != ERROR_SUCCESS) {  
  7.         return ret;  
  8.     }  
  9.      
  10.     // when segment overflow, reap if possible.  
  11.     if (muxer->is_segment_overflow()) {  
  12.         // do reap ts if any of:  
  13.         //      a. wait keyframe and got keyframe.  
  14.         //      b. always reap when not wait keyframe.  
  15.         if (!muxer->wait_keyframe() || sample->frame_type == SrsCodecVideoAVCFrameKeyFrame) {  
  16.             // reap the segment, which will also flush the video.  
  17.             if ((ret = reap_segment("video", muxer, cache->video->dts)) != ERROR_SUCCESS) {  
  18.                 return ret;  
  19.             }  
  20.         }  
  21.     }  
  22.       
  23.     // flush video when got one  
  24.     if ((ret = muxer->flush_video(cache)) != ERROR_SUCCESS) {  
  25.         srs_error("m3u8 muxer flush video failed. ret=%d", ret);  
  26.         return ret;  
  27.     }  
  28.       
  29.     return ret;  
  30. }  
该函数做一下两点工作:

1、首次或者.ts文件时间溢出时,进入reap_segment()函数,该函数主要负责.m3u8和.ts文件管理(创建,打开,关闭)。注意:.m3u8文件是在ts文件写入完毕之后,在关闭操作中一次性将播放参数,ts地址等等参数写入。

2、其他时间,直接进入后面flush_video()函数,该函数负责ts流编码和.ts文件写入。

其中ts流编码设计到很多知识,大家自行查看相关知识:http://blog.csdn.net/u013354805/article/details/51578457

[cpp] view plain copy
  1. int SrsHlsMuxer::flush_video(SrsTsCache* cache)  
  2. {  
  3.     int ret = ERROR_SUCCESS;  
  4.       
  5.     // if current is NULL, segment is not open, ignore the flush event.  
  6.     if (!current) {  
  7.         srs_warn("flush video ignored, for segment is not open.");  
  8.         return ret;  
  9.     }  
  10.       
  11.     if (!cache->video || cache->video->payload->length() <= 0) {  
  12.         return ret;  
  13.     }  
  14.       
  15.     srs_assert(current);  
  16.     //更新该ts文件持续时间  
  17.     // update the duration of segment.  
  18.     current->update_duration(cache->video->dts);  
  19.     //贴片处理  
  20.     if ((ret = current->muxer->write_video(cache->video)) != ERROR_SUCCESS) {  
  21.         return ret;  
  22.     }  
  23.       
  24.     // write success, clear and free the msg  
  25.     srs_freep(cache->video);  
  26.       
  27.     return ret;  
  28. }  
进入编码函数

[cpp] view plain copy
  1. int SrsTsContext::encode(SrsFileWriter* writer, SrsTsMessage* msg, SrsCodecVideo vc, SrsCodecAudio ac)  
  2. {  
  3.     int ret = ERROR_SUCCESS;  
  4.   
  5.     SrsTsStream vs, as;  
  6.     int16_t video_pid = 0, audio_pid = 0;  
  7.     switch (vc) {  
  8.         case SrsCodecVideoAVC:   
  9.             vs = SrsTsStreamVideoH264;   
  10.             video_pid = TS_VIDEO_AVC_PID;  
  11.             break;  
  12.         case SrsCodecVideoDisabled:  
  13.             vs = SrsTsStreamReserved;  
  14.             break;  
  15.         case SrsCodecVideoReserved:  
  16.         case SrsCodecVideoReserved1:  
  17.         case SrsCodecVideoReserved2:  
  18.         case SrsCodecVideoSorensonH263:  
  19.         case SrsCodecVideoScreenVideo:  
  20.         case SrsCodecVideoOn2VP6:  
  21.         case SrsCodecVideoOn2VP6WithAlphaChannel:  
  22.         case SrsCodecVideoScreenVideoVersion2:  
  23.             vs = SrsTsStreamReserved;  
  24.             break;  
  25.     }  
  26.     switch (ac) {  
  27.         case SrsCodecAudioAAC:  
  28.             as = SrsTsStreamAudioAAC;   
  29.             audio_pid = TS_AUDIO_AAC_PID;  
  30.             break;  
  31.         case SrsCodecAudioMP3:  
  32.             as = SrsTsStreamAudioMp3;   
  33.             audio_pid = TS_AUDIO_MP3_PID;  
  34.             break;  
  35.         case SrsCodecAudioDisabled:  
  36.             as = SrsTsStreamReserved;  
  37.             break;  
  38.         case SrsCodecAudioReserved1:  
  39.         case SrsCodecAudioLinearPCMPlatformEndian:  
  40.         case SrsCodecAudioADPCM:  
  41.         case SrsCodecAudioLinearPCMLittleEndian:  
  42.         case SrsCodecAudioNellymoser16kHzMono:  
  43.         case SrsCodecAudioNellymoser8kHzMono:  
  44.         case SrsCodecAudioNellymoser:  
  45.         case SrsCodecAudioReservedG711AlawLogarithmicPCM:  
  46.         case SrsCodecAudioReservedG711MuLawLogarithmicPCM:  
  47.         case SrsCodecAudioReserved:  
  48.         case SrsCodecAudioSpeex:  
  49.         case SrsCodecAudioReservedMP3_8kHz:  
  50.         case SrsCodecAudioReservedDeviceSpecificSound:  
  51.             as = SrsTsStreamReserved;  
  52.             break;  
  53.     }  
  54.       
  55.     if (as == SrsTsStreamReserved && vs == SrsTsStreamReserved) {  
  56.         ret = ERROR_HLS_NO_STREAM;  
  57.         srs_error("hls: no video or audio stream, vcodec=%d, acodec=%d. ret=%d", vc, ac, ret);  
  58.         return ret;  
  59.     }  
  60.       
  61.     // when any codec changed, write PAT/PMT table.  
  62.     if (vcodec != vc || acodec != ac) {  
  63.         vcodec = vc;  
  64.         acodec = ac;  
  65.         if ((ret = encode_pat_pmt(writer, video_pid, vs, audio_pid, as)) != ERROR_SUCCESS) {  
  66.             return ret;  
  67.         }  
  68.     }  
  69.       
  70.     // encode the media frame to PES packets over TS.  
  71.     if (msg->is_audio()) {  
  72.         return encode_pes(writer, msg, audio_pid, as, vs == SrsTsStreamReserved);  
  73.     } else {  
  74.         return encode_pes(writer, msg, video_pid, vs, vs == SrsTsStreamReserved);  
  75.     }  
  76. }  
该函数内容有点多:

1、根据音视频类型,获取不同的PID(在TS协议当中,TS包包含了音视频数据,它们是通过TS头协议PID来区分的)

2、TS编码,PAT帧,PMT帧(首帧TS流)

3、TS编码,音视频数据编码(TS流数据部分)

可以先进入encode_pat_pmt()函数函数中看看:

[cpp] view plain copy
  1. int SrsTsContext::encode_pat_pmt(SrsFileWriter* writer, int16_t vpid, SrsTsStream vs, int16_t apid, SrsTsStream as)  
  2. {  
  3.     int ret = ERROR_SUCCESS;  
  4.       
  5.     if (vs != SrsTsStreamVideoH264 && as != SrsTsStreamAudioAAC && as != SrsTsStreamAudioMp3) {  
  6.         ret = ERROR_HLS_NO_STREAM;  
  7.         srs_error("hls: no pmt pcr pid, vs=%d, as=%d. ret=%d", vs, as, ret);  
  8.         return ret;  
  9.     }  
  10.   
  11.     int16_t pmt_number = TS_PMT_NUMBER;  
  12.     int16_t pmt_pid = TS_PMT_PID;  
  13.     if (true) {  
  14.     // 创建一个PAT(节目关联表)  
  15.         SrsTsPacket* pkt = SrsTsPacket::create_pat(this, pmt_number, pmt_pid);  
  16.         SrsAutoFree(SrsTsPacket, pkt);  
  17.     // TS包188字节,其中头字节(4字节,184个字节)。加上16字节CRC,总共204字节  
  18.         char* buf = new char[SRS_TS_PACKET_SIZE];  
  19.         SrsAutoFreeA(char, buf);  
  20.   
  21.         // set the left bytes with 0xFF.  
  22.         int nb_buf = pkt->size();  
  23.         srs_assert(nb_buf < SRS_TS_PACKET_SIZE);  
  24.         memset(buf + nb_buf, 0xFF, SRS_TS_PACKET_SIZE - nb_buf);  
  25.   
  26.         SrsStream stream;  
  27.         if ((ret = stream.initialize(buf, nb_buf)) != ERROR_SUCCESS) {  
  28.             return ret;  
  29.         }  
  30.     // 编码  
  31.         if ((ret = pkt->encode(&stream)) != ERROR_SUCCESS) {  
  32.             srs_error("ts encode ts packet failed. ret=%d", ret);  
  33.             return ret;  
  34.         }  
  35.         if ((ret = writer->write(buf, SRS_TS_PACKET_SIZE, NULL)) != ERROR_SUCCESS) {  
  36.             srs_error("ts write ts packet failed. ret=%d", ret);  
  37.             return ret;  
  38.         }  
  39.     }  
  40.     if (true) {  
  41.     //创建一个PMT  
  42.         SrsTsPacket* pkt = SrsTsPacket::create_pmt(this, pmt_number, pmt_pid, vpid, vs, apid, as);  
  43.         SrsAutoFree(SrsTsPacket, pkt);  
  44.   
  45.         char* buf = new char[SRS_TS_PACKET_SIZE];  
  46.         SrsAutoFreeA(char, buf);  
  47.   
  48.         // set the left bytes with 0xFF.  
  49.         int nb_buf = pkt->size();  
  50.         srs_assert(nb_buf < SRS_TS_PACKET_SIZE);  
  51.         memset(buf + nb_buf, 0xFF, SRS_TS_PACKET_SIZE - nb_buf);  
  52.   
  53.         SrsStream stream;  
  54.         if ((ret = stream.initialize(buf, nb_buf)) != ERROR_SUCCESS) {  
  55.             return ret;  
  56.         }  
  57.     // 编码  
  58.         if ((ret = pkt->encode(&stream)) != ERROR_SUCCESS) {  
  59.             srs_error("ts encode ts packet failed. ret=%d", ret);  
  60.             return ret;  
  61.         }  
  62.        
  63.         if ((ret = writer->write(buf, SRS_TS_PACKET_SIZE, NULL)) != ERROR_SUCCESS) {  
  64.             srs_error("ts write ts packet failed. ret=%d", ret);  
  65.             return ret;  
  66.         }  
  67.     }  
  68.       
  69.     // When PAT and PMT are writen, the context is ready now.  
  70.     ready = true;  
  71.   
  72.     return ret;  
  73. }  
上面代码创建PAT和PMT两个TS包。将TS文件前两个包解析,如下:


再来看encode_pes()函数

[cpp] view plain copy
  1. int SrsTsContext::encode_pes(SrsFileWriter* writer, SrsTsMessage* msg, int16_t pid, SrsTsStream sid, bool pure_audio)  
  2. {  
  3.     int ret = ERROR_SUCCESS;  
  4.       
  5.     // Sometimes, the context is not ready(PAT/PMT write failed), error in this situation.  
  6.     if (!ready) {  
  7.         ret = ERROR_TS_CONTEXT_NOT_READY;  
  8.         srs_error("TS: context not ready, ret=%d", ret);  
  9.         return ret;  
  10.     }  
  11.   
  12.     if (msg->payload->length() == 0) {  
  13.         return ret;  
  14.     }  
  15.   
  16.     if (sid != SrsTsStreamVideoH264 && sid != SrsTsStreamAudioMp3 && sid != SrsTsStreamAudioAAC) {  
  17.         srs_info("ts: ignore the unknown stream, sid=%d", sid);  
  18.         return ret;  
  19.     }  
  20.   
  21.     SrsTsChannel* channel = get(pid);  
  22.     srs_assert(channel);  
  23.   
  24.     char* start = msg->payload->bytes();  
  25.     char* end = start + msg->payload->length();  
  26.     char* p = start;  
  27.   
  28.     while (p < end) {  
  29.         SrsTsPacket* pkt = NULL;  
  30.         if (p == start) {  
  31.             // write pcr according to message.  
  32.             bool write_pcr = msg->write_pcr;  
  33.               
  34.             // for pure audio, always write pcr.  
  35.             // TODO: FIXME: maybe only need to write at begin and end of ts.  
  36.             if (pure_audio && msg->is_audio()) {  
  37.                 write_pcr = true;  
  38.             }  
  39.   
  40.             // it's ok to set pcr equals to dts,  
  41.             // @see https://github.com/ossrs/srs/issues/311  
  42.             // Fig. 3.18. Program Clock Reference of Digital-Video-and-Audio-Broadcasting-Technology, page 65  
  43.             // In MPEG-2, these are the "Program Clock Refer- ence" (PCR) values which are  
  44.             // nothing else than an up-to-date copy of the STC counter fed into the transport  
  45.             // stream at a certain time. The data stream thus carries an accurate internal  
  46.             // "clock time". All coding and de- coding processes are controlled by this clock  
  47.             // time. To do this, the receiver, i.e. the MPEG decoder, must read out the  
  48.             // "clock time", namely the PCR values, and compare them with its own internal  
  49.             // system clock, that is to say its own 42 bit counter.  
  50.             int64_t pcr = write_pcr? msg->dts : -1;  
  51.               
  52.             // TODO: FIXME: finger it why use discontinuity of msg.  
  53.             pkt = SrsTsPacket::create_pes_first(this,   
  54.                 pid, msg->sid, channel->continuity_counter++, msg->is_discontinuity,  
  55.                 pcr, msg->dts, msg->pts, msg->payload->length()  
  56.             );  
  57.         } else {  
  58.             pkt = SrsTsPacket::create_pes_continue(this,   
  59.                 pid, msg->sid, channel->continuity_counter++  
  60.             );  
  61.         }  
  62.         SrsAutoFree(SrsTsPacket, pkt);  
  63.   
  64.         char* buf = new char[SRS_TS_PACKET_SIZE];  
  65.         SrsAutoFreeA(char, buf);  
  66.   
  67.         // set the left bytes with 0xFF.  
  68.         int nb_buf = pkt->size();  
  69.         srs_assert(nb_buf < SRS_TS_PACKET_SIZE);  
  70.   
  71.         int left = (int)srs_min(end - p, SRS_TS_PACKET_SIZE - nb_buf);  
  72.         int nb_stuffings = SRS_TS_PACKET_SIZE - nb_buf - left;  
  73.         if (nb_stuffings > 0) {  
  74.             // set all bytes to stuffings.  
  75.             memset(buf, 0xFF, SRS_TS_PACKET_SIZE);  
  76.   
  77.             // padding with stuffings.  
  78.             pkt->padding(nb_stuffings);  
  79.   
  80.             // size changed, recalc it.  
  81.             nb_buf = pkt->size();  
  82.             srs_assert(nb_buf < SRS_TS_PACKET_SIZE);  
  83.   
  84.             left = (int)srs_min(end - p, SRS_TS_PACKET_SIZE - nb_buf);  
  85.             nb_stuffings = SRS_TS_PACKET_SIZE - nb_buf - left;  
  86.             srs_assert(nb_stuffings == 0);  
  87.         }  
  88.         memcpy(buf + nb_buf, p, left);  
  89.         p += left;  
  90.   
  91.         SrsStream stream;  
  92.         if ((ret = stream.initialize(buf, nb_buf)) != ERROR_SUCCESS) {  
  93.             return ret;  
  94.         }  
  95.         if ((ret = pkt->encode(&stream)) != ERROR_SUCCESS) {  
  96.             srs_error("ts encode ts packet failed. ret=%d", ret);  
  97.             return ret;  
  98.         }  
  99.         if ((ret = writer->write(buf, SRS_TS_PACKET_SIZE, NULL)) != ERROR_SUCCESS) {  
  100.             srs_error("ts write ts packet failed. ret=%d", ret);  
  101.             return ret;  
  102.         }  
  103.     }  
  104.   
  105.     return ret;  
  106. }  

编码成TS包,写入TS文件。


三、总结

      1、TS编码,实际是按照TS协议来重新整理数据,TS协议是传输协议。TS协议传输的音视频数据压缩格式还是H264/AAC。

      2、TS切片,实际是按照TS协议要求的字段长度对音视频数据进行分包处理。

      3、TS文件,TS包存储的位置。又涉及到HLS协议和TS协议关系。


原创粉丝点击