手动实现如何从H264流中提取SPS/PPS信息

1,代码比较简单,可以直接用了。流的第一个NALU一定是SPS

void get_sps_pps_nalu(uint8_t *data, int len, std::vector<uint8_t> &sps, std::vector<uint8_t> &pps)
{
    const uint8_t* pkt_bgn = data;
    const uint8_t* pkt_end = pkt_bgn + len;
    const uint8_t* pbgn = pkt_bgn;
    const uint8_t* pend = pkt_end;
    while (pbgn < pkt_end) {
        pbgn = find_next_nal(pbgn, pkt_end);
        if (pbgn == pkt_end) {
           continue;
        } else {
           while (*pbgn == 0) ++pbgn; //skip all 0x00
           ++pbgn; //skip 0x01
        }
        pend = find_next_nal(pbgn, pkt_end);

        if (((*pbgn) & 0x1F) == 0x07) {    //SPS NAL
            std::cout<<"find sps nal"<<std::endl;
            sps.assign(pbgn, pbgn + static_cast<int>(pend - pbgn));
        }
        if (((*pbgn) & 0x1F) == 0x08) {    //PPS NAL
            std::cout<<"find pps nal"<<std::endl;
            pps.assign(pbgn, pbgn + static_cast<int>(pend - pbgn));
       }
       pbgn = pend;
    }
}
const uint8_t* find_next_nal(const uint8_t* start, const uint8_t* end)
{
   const uint8_t *p = start;
   /* Simply lookup "0x000001" or "0x00000001" pattern */
   while (p <= end - 3) {
      if (p[0] == 0x00) {
         if (p[1] == 0x00) {
            if ((p[2] == 0x01) || (p[2] == 0x00 && p[3] == 0x01)) {
               return p;
            } else {
               p += 3;
            }
         } else {
            p += 2;
         }
      } else {
         ++p;
      }
   }
   return end;
}
int main()
    H264FramefromCam(data, &len);
    get_sps_pps_nalu((uint8_t *)data, len, pps, sps);
    return 0;
}
posted @ 2019-10-17 15:16  Ray.floyd  阅读(867)  评论(0编辑  收藏  举报