libavformat/rtpdec_h264.c
1d1be919
 /*
  * RTP H264 Protocol (RFC3984)
406792e7
  * Copyright (c) 2006 Ryan Martell
1d1be919
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
f3d471f4
  * @file
1d1be919
  * @brief H.264 / RTP Code (RFC3984)
  * @author Ryan Martell <rdm4@martellventures.com>
  *
  * @note Notes:
  * Notes:
  * This currently supports packetization mode:
  * Single Nal Unit Mode (0), or
  * Non-Interleaved Mode (1).  It currently does not support
f3d471f4
  * Interleaved Mode (2). (This requires implementing STAP-B, MTAP16, MTAP24,
  *                        FU-B packet types)
1d1be919
  */
 
245976da
 #include "libavutil/base64.h"
 #include "libavutil/avstring.h"
9106a698
 #include "libavcodec/get_bits.h"
1d1be919
 #include "avformat.h"
 
42572ef5
 #include "network.h"
1d1be919
 #include <assert.h>
 
302879cb
 #include "rtpdec.h"
965a3ddb
 #include "rtpdec_formats.h"
1d1be919
 
ed0aacc7
 struct PayloadContext {
f3d471f4
     // sdp setup parameters
8d43b8b8
     uint8_t profile_idc;
     uint8_t profile_iop;
     uint8_t level_idc;
     int packetization_mode;
1d1be919
 #ifdef DEBUG
     int packet_types_received[32];
 #endif
ed0aacc7
 };
1d1be919
 
48666c2b
 #ifdef DEBUG
 #define COUNT_NAL_TYPE(data, nal) data->packet_types_received[(nal) & 0x1f]++
 #else
 #define COUNT_NAL_TYPE(data, nal) do { } while (0)
 #endif
 
b3688617
 static const uint8_t start_sequence[] = { 0, 0, 0, 1 };
 
0b3ac9fe
 static int sdp_parse_fmtp_config_h264(AVStream *stream,
                                       PayloadContext *h264_data,
1ed3cef5
                                       char *attr, char *value)
1d1be919
 {
     AVCodecContext *codec = stream->codec;
36ef5369
     assert(codec->codec_id == AV_CODEC_ID_H264);
1d1be919
     assert(h264_data != NULL);
 
     if (!strcmp(attr, "packetization-mode")) {
2fddbb68
         av_log(codec, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value));
272872e4
         h264_data->packetization_mode = atoi(value);
1d1be919
         /*
f3d471f4
          * Packetization Mode:
          * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed)
          * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed.
          * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A),
          *                      and 29 (FU-B) are allowed.
1d1be919
          */
         if (h264_data->packetization_mode > 1)
2fddbb68
             av_log(codec, AV_LOG_ERROR,
2ed503af
                    "Interleaved RTP mode is not supported yet.\n");
1d1be919
     } else if (!strcmp(attr, "profile-level-id")) {
         if (strlen(value) == 6) {
             char buffer[3];
             // 6 characters=3 bytes, in hex.
             uint8_t profile_idc;
             uint8_t profile_iop;
             uint8_t level_idc;
 
0b3ac9fe
             buffer[0]   = value[0];
             buffer[1]   = value[1];
             buffer[2]   = '\0';
1d1be919
             profile_idc = strtol(buffer, NULL, 16);
0b3ac9fe
             buffer[0]   = value[2];
             buffer[1]   = value[3];
1d1be919
             profile_iop = strtol(buffer, NULL, 16);
0b3ac9fe
             buffer[0]   = value[4];
             buffer[1]   = value[5];
             level_idc   = strtol(buffer, NULL, 16);
1d1be919
 
2fddbb68
             av_log(codec, AV_LOG_DEBUG,
                    "RTP Profile IDC: %x Profile IOP: %x Level: %x\n",
1d1be919
                    profile_idc, profile_iop, level_idc);
             h264_data->profile_idc = profile_idc;
             h264_data->profile_iop = profile_iop;
0b3ac9fe
             h264_data->level_idc   = level_idc;
1d1be919
         }
0b3ac9fe
     } else if (!strcmp(attr, "sprop-parameter-sets")) {
         codec->extradata_size = 0;
b97d21e4
         av_freep(&codec->extradata);
1d1be919
 
         while (*value) {
             char base64packet[1024];
             uint8_t decoded_packet[1024];
dc6cf61e
             int packet_size;
1d1be919
             char *dst = base64packet;
 
             while (*value && *value != ','
                    && (dst - base64packet) < sizeof(base64packet) - 1) {
                 *dst++ = *value++;
             }
             *dst++ = '\0';
 
             if (*value == ',')
                 value++;
 
0b3ac9fe
             packet_size = av_base64_decode(decoded_packet, base64packet,
                                            sizeof(decoded_packet));
dc6cf61e
             if (packet_size > 0) {
b9b8ed2a
                 uint8_t *dest = av_malloc(packet_size + sizeof(start_sequence) +
0b3ac9fe
                                           codec->extradata_size +
                                           FF_INPUT_BUFFER_PADDING_SIZE);
3c148703
                 if (!dest) {
0b3ac9fe
                     av_log(codec, AV_LOG_ERROR,
2ed503af
                            "Unable to allocate memory for extradata!\n");
7aa0118c
                     return AVERROR(ENOMEM);
1d1be919
                 }
3c148703
                 if (codec->extradata_size) {
                     memcpy(dest, codec->extradata, codec->extradata_size);
                     av_free(codec->extradata);
                 }
 
                 memcpy(dest + codec->extradata_size, start_sequence,
                        sizeof(start_sequence));
                 memcpy(dest + codec->extradata_size + sizeof(start_sequence),
                        decoded_packet, packet_size);
                 memset(dest + codec->extradata_size + sizeof(start_sequence) +
                        packet_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
 
                 codec->extradata       = dest;
                 codec->extradata_size += sizeof(start_sequence) + packet_size;
1d1be919
             }
         }
2ed503af
         av_log(codec, AV_LOG_DEBUG, "Extradata set to %p (size: %d)!\n",
0b3ac9fe
                codec->extradata, codec->extradata_size);
1d1be919
     }
7aa0118c
     return 0;
1d1be919
 }
 
f3d471f4
 // return 0 on packet, no more left, 1 on packet, 1 on partial packet
0b3ac9fe
 static int h264_handle_packet(AVFormatContext *ctx, PayloadContext *data,
                               AVStream *st, AVPacket *pkt, uint32_t *timestamp,
90c784cc
                               const uint8_t *buf, int len, uint16_t seq,
                               int flags)
1d1be919
 {
de26a4b6
     uint8_t nal;
     uint8_t type;
0b3ac9fe
     int result = 0;
1d1be919
 
de26a4b6
     if (!len) {
         av_log(ctx, AV_LOG_ERROR, "Empty H264 RTP packet\n");
         return AVERROR_INVALIDDATA;
     }
     nal  = buf[0];
     type = nal & 0x1f;
 
1d1be919
     assert(data);
     assert(buf);
 
f3d471f4
     /* Simplify the case (these are all the nal types used internally by
      * the h264 codec). */
1d1be919
     if (type >= 1 && type <= 23)
f3d471f4
         type = 1;
1d1be919
     switch (type) {
86042de8
     case 0:                    // undefined, but pass them through
1d1be919
     case 1:
0b3ac9fe
         av_new_packet(pkt, len + sizeof(start_sequence));
1d1be919
         memcpy(pkt->data, start_sequence, sizeof(start_sequence));
0b3ac9fe
         memcpy(pkt->data + sizeof(start_sequence), buf, len);
48666c2b
         COUNT_NAL_TYPE(data, nal);
1d1be919
         break;
 
     case 24:                   // STAP-A (one packet, multiple nals)
         // consume the STAP-A NAL
         buf++;
         len--;
f3d471f4
         // first we are going to figure out the total size
1d1be919
         {
0b3ac9fe
             int pass         = 0;
             int total_length = 0;
             uint8_t *dst     = NULL;
1d1be919
 
0b3ac9fe
             for (pass = 0; pass < 2; pass++) {
                 const uint8_t *src = buf;
                 int src_len        = len;
1d1be919
 
5245adb9
                 while (src_len > 2) {
8d43b8b8
                     uint16_t nal_size = AV_RB16(src);
1d1be919
 
f3d471f4
                     // consume the length of the aggregate
0b3ac9fe
                     src     += 2;
1d1be919
                     src_len -= 2;
 
                     if (nal_size <= src_len) {
0b3ac9fe
                         if (pass == 0) {
f3d471f4
                             // counting
0b3ac9fe
                             total_length += sizeof(start_sequence) + nal_size;
1d1be919
                         } else {
                             // copying
                             assert(dst);
                             memcpy(dst, start_sequence, sizeof(start_sequence));
0b3ac9fe
                             dst += sizeof(start_sequence);
1d1be919
                             memcpy(dst, src, nal_size);
48666c2b
                             COUNT_NAL_TYPE(data, *src);
0b3ac9fe
                             dst += nal_size;
1d1be919
                         }
                     } else {
2fddbb68
                         av_log(ctx, AV_LOG_ERROR,
1d1be919
                                "nal size exceeds length: %d %d\n", nal_size, src_len);
                     }
 
f3d471f4
                     // eat what we handled
0b3ac9fe
                     src     += nal_size;
1d1be919
                     src_len -= nal_size;
 
                     if (src_len < 0)
2fddbb68
                         av_log(ctx, AV_LOG_ERROR,
1d1be919
                                "Consumed more bytes than we got! (%d)\n", src_len);
5245adb9
                 }
1d1be919
 
0b3ac9fe
                 if (pass == 0) {
f3d471f4
                     /* now we know the total size of the packet (with the
                      * start sequences added) */
1d1be919
                     av_new_packet(pkt, total_length);
0b3ac9fe
                     dst = pkt->data;
1d1be919
                 } else {
0b3ac9fe
                     assert(dst - pkt->data == total_length);
1d1be919
                 }
             }
         }
         break;
 
     case 25:                   // STAP-B
     case 26:                   // MTAP-16
     case 27:                   // MTAP-24
     case 29:                   // FU-B
2fddbb68
         av_log(ctx, AV_LOG_ERROR,
1d1be919
                "Unhandled type (%d) (See RFC for implementation details\n",
                type);
b7b7354c
         result = AVERROR(ENOSYS);
1d1be919
         break;
 
     case 28:                   // FU-A (fragmented nal)
         buf++;
f3d471f4
         len--;                 // skip the fu_indicator
de26a4b6
         if (len > 1) {
f3d471f4
             // these are the same as above, we just redo them here for clarity
0b3ac9fe
             uint8_t fu_indicator      = nal;
             uint8_t fu_header         = *buf;
             uint8_t start_bit         = fu_header >> 7;
dee48d09
             uint8_t av_unused end_bit = (fu_header & 0x40) >> 6;
0b3ac9fe
             uint8_t nal_type          = fu_header & 0x1f;
1d1be919
             uint8_t reconstructed_nal;
 
f3d471f4
             // Reconstruct this packet's true nal; only the data follows.
             /* The original nal forbidden bit and NRI are stored in this
              * packet's nal. */
0b3ac9fe
             reconstructed_nal  = fu_indicator & 0xe0;
7699645e
             reconstructed_nal |= nal_type;
1d1be919
 
f3d471f4
             // skip the fu_header
1d1be919
             buf++;
             len--;
 
             if (start_bit)
48666c2b
                 COUNT_NAL_TYPE(data, nal_type);
0b3ac9fe
             if (start_bit) {
f3d471f4
                 /* copy in the start sequence, and the reconstructed nal */
0b3ac9fe
                 av_new_packet(pkt, sizeof(start_sequence) + sizeof(nal) + len);
1d1be919
                 memcpy(pkt->data, start_sequence, sizeof(start_sequence));
0b3ac9fe
                 pkt->data[sizeof(start_sequence)] = reconstructed_nal;
                 memcpy(pkt->data + sizeof(start_sequence) + sizeof(nal), buf, len);
1d1be919
             } else {
                 av_new_packet(pkt, len);
                 memcpy(pkt->data, buf, len);
             }
de26a4b6
         } else {
             av_log(ctx, AV_LOG_ERROR, "Too short data for FU-A H264 RTP packet\n");
             result = AVERROR_INVALIDDATA;
1d1be919
         }
         break;
 
     case 30:                   // undefined
     case 31:                   // undefined
     default:
2ed503af
         av_log(ctx, AV_LOG_ERROR, "Undefined type (%d)\n", type);
b7b7354c
         result = AVERROR_INVALIDDATA;
1d1be919
         break;
     }
 
eafb17d1
     pkt->stream_index = st->index;
 
1d1be919
     return result;
 }
 
202a6697
 static PayloadContext *h264_new_context(void)
1d1be919
 {
5a571d32
     return av_mallocz(sizeof(PayloadContext) + FF_INPUT_BUFFER_PADDING_SIZE);
1d1be919
 }
 
202a6697
 static void h264_free_context(PayloadContext *data)
1d1be919
 {
 #ifdef DEBUG
     int ii;
 
     for (ii = 0; ii < 32; ii++) {
         if (data->packet_types_received[ii])
             av_log(NULL, AV_LOG_DEBUG, "Received %d packets of type %d\n",
                    data->packet_types_received[ii], ii);
     }
 #endif
 
     av_free(data);
 }
 
7b2a0708
 static int parse_h264_sdp_line(AVFormatContext *s, int st_index,
                                PayloadContext *h264_data, const char *line)
1d1be919
 {
45600148
     AVStream *stream;
     AVCodecContext *codec;
1d1be919
     const char *p = line;
 
45600148
     if (st_index < 0)
         return 0;
 
     stream = s->streams[st_index];
0b3ac9fe
     codec  = stream->codec;
1d1be919
 
f7d78f36
     if (av_strstart(p, "framesize:", &p)) {
1d1be919
         char buf1[50];
         char *dst = buf1;
 
f3d471f4
         // remove the protocol identifier
0b3ac9fe
         while (*p && *p == ' ')
             p++;                     // strip spaces.
         while (*p && *p != ' ')
             p++;                     // eat protocol identifier
         while (*p && *p == ' ')
             p++;                     // strip trailing spaces.
         while (*p && *p != '-' && (dst - buf1) < sizeof(buf1) - 1)
1d1be919
             *dst++ = *p++;
         *dst = '\0';
 
         // a='framesize:96 320-240'
f3d471f4
         // set our parameters
0b3ac9fe
         codec->width   = atoi(buf1);
         codec->height  = atoi(p + 1); // skip the -
f7d78f36
     } else if (av_strstart(p, "fmtp:", &p)) {
fb4ca2cb
         return ff_parse_fmtp(stream, h264_data, p, sdp_parse_fmtp_config_h264);
f7d78f36
     } else if (av_strstart(p, "cliprect:", &p)) {
1d1be919
         // could use this if we wanted.
     }
 
8d43b8b8
     return 0;
1d1be919
 }
 
 RTPDynamicProtocolHandler ff_h264_dynamic_handler = {
202a6697
     .enc_name         = "H264",
72415b2a
     .codec_type       = AVMEDIA_TYPE_VIDEO,
36ef5369
     .codec_id         = AV_CODEC_ID_H264,
202a6697
     .parse_sdp_a_line = parse_h264_sdp_line,
9261e6cf
     .alloc            = h264_new_context,
     .free             = h264_free_context,
202a6697
     .parse_packet     = h264_handle_packet
1d1be919
 };