]> git.sesse.net Git - ffmpeg/blob - libavformat/rtpdec_h264.c
rtpdec_h264: Remove an unnecessary include
[ffmpeg] / libavformat / rtpdec_h264.c
1 /*
2  * RTP H264 Protocol (RFC3984)
3  * Copyright (c) 2006 Ryan Martell
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * @brief H.264 / RTP Code (RFC3984)
25  * @author Ryan Martell <rdm4@martellventures.com>
26  *
27  * @note Notes:
28  * Notes:
29  * This currently supports packetization mode:
30  * Single Nal Unit Mode (0), or
31  * Non-Interleaved Mode (1).  It currently does not support
32  * Interleaved Mode (2). (This requires implementing STAP-B, MTAP16, MTAP24,
33  *                        FU-B packet types)
34  */
35
36 #include "libavutil/attributes.h"
37 #include "libavutil/base64.h"
38 #include "libavutil/intreadwrite.h"
39 #include "libavutil/avstring.h"
40 #include "avformat.h"
41
42 #include "rtpdec.h"
43 #include "rtpdec_formats.h"
44
45 struct PayloadContext {
46     // sdp setup parameters
47     uint8_t profile_idc;
48     uint8_t profile_iop;
49     uint8_t level_idc;
50     int packetization_mode;
51 #ifdef DEBUG
52     int packet_types_received[32];
53 #endif
54 };
55
56 #ifdef DEBUG
57 #define COUNT_NAL_TYPE(data, nal) data->packet_types_received[(nal) & 0x1f]++
58 #define NAL_COUNTERS data->packet_types_received
59 #else
60 #define COUNT_NAL_TYPE(data, nal) do { } while (0)
61 #define NAL_COUNTERS NULL
62 #endif
63 #define NAL_MASK 0x1f
64
65 static const uint8_t start_sequence[] = { 0, 0, 0, 1 };
66
67 static void parse_profile_level_id(AVFormatContext *s,
68                                    PayloadContext *h264_data,
69                                    char *value)
70 {
71     char buffer[3];
72     // 6 characters=3 bytes, in hex.
73     uint8_t profile_idc;
74     uint8_t profile_iop;
75     uint8_t level_idc;
76
77     buffer[0]   = value[0];
78     buffer[1]   = value[1];
79     buffer[2]   = '\0';
80     profile_idc = strtol(buffer, NULL, 16);
81     buffer[0]   = value[2];
82     buffer[1]   = value[3];
83     profile_iop = strtol(buffer, NULL, 16);
84     buffer[0]   = value[4];
85     buffer[1]   = value[5];
86     level_idc   = strtol(buffer, NULL, 16);
87
88     av_log(s, AV_LOG_DEBUG,
89            "RTP Profile IDC: %x Profile IOP: %x Level: %x\n",
90            profile_idc, profile_iop, level_idc);
91     h264_data->profile_idc = profile_idc;
92     h264_data->profile_iop = profile_iop;
93     h264_data->level_idc   = level_idc;
94 }
95
96 int ff_h264_parse_sprop_parameter_sets(AVFormatContext *s,
97                                        uint8_t **data_ptr, int *size_ptr,
98                                        const char *value)
99 {
100     char base64packet[1024];
101     uint8_t decoded_packet[1024];
102     int packet_size;
103
104     while (*value) {
105         char *dst = base64packet;
106
107         while (*value && *value != ','
108                && (dst - base64packet) < sizeof(base64packet) - 1) {
109             *dst++ = *value++;
110         }
111         *dst++ = '\0';
112
113         if (*value == ',')
114             value++;
115
116         packet_size = av_base64_decode(decoded_packet, base64packet,
117                                        sizeof(decoded_packet));
118         if (packet_size > 0) {
119             uint8_t *dest = av_realloc(*data_ptr,
120                                        packet_size + sizeof(start_sequence) +
121                                        *size_ptr +
122                                        FF_INPUT_BUFFER_PADDING_SIZE);
123             if (!dest) {
124                 av_log(s, AV_LOG_ERROR,
125                        "Unable to allocate memory for extradata!\n");
126                 return AVERROR(ENOMEM);
127             }
128             *data_ptr = dest;
129
130             memcpy(dest + *size_ptr, start_sequence,
131                    sizeof(start_sequence));
132             memcpy(dest + *size_ptr + sizeof(start_sequence),
133                    decoded_packet, packet_size);
134             memset(dest + *size_ptr + sizeof(start_sequence) +
135                    packet_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
136
137             *size_ptr += sizeof(start_sequence) + packet_size;
138         }
139     }
140
141     return 0;
142 }
143
144 static int sdp_parse_fmtp_config_h264(AVFormatContext *s,
145                                       AVStream *stream,
146                                       PayloadContext *h264_data,
147                                       char *attr, char *value)
148 {
149     AVCodecContext *codec = stream->codec;
150
151     if (!strcmp(attr, "packetization-mode")) {
152         av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value));
153         h264_data->packetization_mode = atoi(value);
154         /*
155          * Packetization Mode:
156          * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed)
157          * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed.
158          * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A),
159          *                      and 29 (FU-B) are allowed.
160          */
161         if (h264_data->packetization_mode > 1)
162             av_log(s, AV_LOG_ERROR,
163                    "Interleaved RTP mode is not supported yet.\n");
164     } else if (!strcmp(attr, "profile-level-id")) {
165         if (strlen(value) == 6)
166             parse_profile_level_id(s, h264_data, value);
167     } else if (!strcmp(attr, "sprop-parameter-sets")) {
168         int ret;
169         codec->extradata_size = 0;
170         av_freep(&codec->extradata);
171         ret = ff_h264_parse_sprop_parameter_sets(s, &codec->extradata,
172                                                  &codec->extradata_size, value);
173         av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n",
174                codec->extradata, codec->extradata_size);
175         return ret;
176     }
177     return 0;
178 }
179
180 int ff_h264_handle_aggregated_packet(AVFormatContext *ctx, AVPacket *pkt,
181                                      const uint8_t *buf, int len,
182                                      int skip_between, int *nal_counters,
183                                      int nal_mask)
184 {
185     int pass         = 0;
186     int total_length = 0;
187     uint8_t *dst     = NULL;
188     int ret;
189
190     // first we are going to figure out the total size
191     for (pass = 0; pass < 2; pass++) {
192         const uint8_t *src = buf;
193         int src_len        = len;
194
195         while (src_len > 2) {
196             uint16_t nal_size = AV_RB16(src);
197
198             // consume the length of the aggregate
199             src     += 2;
200             src_len -= 2;
201
202             if (nal_size <= src_len) {
203                 if (pass == 0) {
204                     // counting
205                     total_length += sizeof(start_sequence) + nal_size;
206                 } else {
207                     // copying
208                     memcpy(dst, start_sequence, sizeof(start_sequence));
209                     dst += sizeof(start_sequence);
210                     memcpy(dst, src, nal_size);
211                     if (nal_counters)
212                         nal_counters[(*src) & nal_mask]++;
213                     dst += nal_size;
214                 }
215             } else {
216                 av_log(ctx, AV_LOG_ERROR,
217                        "nal size exceeds length: %d %d\n", nal_size, src_len);
218                 return AVERROR_INVALIDDATA;
219             }
220
221             // eat what we handled
222             src     += nal_size + skip_between;
223             src_len -= nal_size + skip_between;
224         }
225
226         if (pass == 0) {
227             /* now we know the total size of the packet (with the
228              * start sequences added) */
229             if ((ret = av_new_packet(pkt, total_length)) < 0)
230                 return ret;
231             dst = pkt->data;
232         }
233     }
234
235     return 0;
236 }
237
238 static int h264_handle_packet_fu_a(AVFormatContext *ctx, AVPacket *pkt,
239                                    const uint8_t *buf, int len,
240                                    int *nal_counters, int nal_mask)
241 {
242     uint8_t fu_indicator, fu_header, start_bit, nal_type, nal;
243     int ret;
244
245     if (len < 3) {
246         av_log(ctx, AV_LOG_ERROR, "Too short data for FU-A H264 RTP packet\n");
247         return AVERROR_INVALIDDATA;
248     }
249
250     fu_indicator = buf[0];
251     fu_header    = buf[1];
252     start_bit    = fu_header >> 7;
253     nal_type     = fu_header & 0x1f;
254     nal          = fu_indicator & 0xe0 | nal_type;
255
256     // skip the fu_indicator and fu_header
257     buf += 2;
258     len -= 2;
259
260     if (start_bit) {
261         if (nal_counters)
262             nal_counters[nal_type & nal_mask]++;
263         /* copy in the start sequence, and the reconstructed nal */
264         if ((ret = av_new_packet(pkt, sizeof(start_sequence) + sizeof(nal) + len)) < 0)
265             return ret;
266         memcpy(pkt->data, start_sequence, sizeof(start_sequence));
267         pkt->data[sizeof(start_sequence)] = nal;
268         memcpy(pkt->data + sizeof(start_sequence) + sizeof(nal), buf, len);
269     } else {
270         if ((ret = av_new_packet(pkt, len)) < 0)
271             return ret;
272         memcpy(pkt->data, buf, len);
273     }
274
275     return 0;
276 }
277
278 // return 0 on packet, no more left, 1 on packet, 1 on partial packet
279 static int h264_handle_packet(AVFormatContext *ctx, PayloadContext *data,
280                               AVStream *st, AVPacket *pkt, uint32_t *timestamp,
281                               const uint8_t *buf, int len, uint16_t seq,
282                               int flags)
283 {
284     uint8_t nal;
285     uint8_t type;
286     int result = 0;
287
288     if (!len) {
289         av_log(ctx, AV_LOG_ERROR, "Empty H264 RTP packet\n");
290         return AVERROR_INVALIDDATA;
291     }
292     nal  = buf[0];
293     type = nal & 0x1f;
294
295     /* Simplify the case (these are all the nal types used internally by
296      * the h264 codec). */
297     if (type >= 1 && type <= 23)
298         type = 1;
299     switch (type) {
300     case 0:                    // undefined, but pass them through
301     case 1:
302         if ((result = av_new_packet(pkt, len + sizeof(start_sequence))) < 0)
303             return result;
304         memcpy(pkt->data, start_sequence, sizeof(start_sequence));
305         memcpy(pkt->data + sizeof(start_sequence), buf, len);
306         COUNT_NAL_TYPE(data, nal);
307         break;
308
309     case 24:                   // STAP-A (one packet, multiple nals)
310         // consume the STAP-A NAL
311         buf++;
312         len--;
313         result = ff_h264_handle_aggregated_packet(ctx, pkt, buf, len, 0,
314                                                   NAL_COUNTERS, NAL_MASK);
315         break;
316
317     case 25:                   // STAP-B
318     case 26:                   // MTAP-16
319     case 27:                   // MTAP-24
320     case 29:                   // FU-B
321         av_log(ctx, AV_LOG_ERROR,
322                "Unhandled type (%d) (See RFC for implementation details)\n",
323                type);
324         result = AVERROR(ENOSYS);
325         break;
326
327     case 28:                   // FU-A (fragmented nal)
328         result = h264_handle_packet_fu_a(ctx, pkt, buf, len,
329                                          NAL_COUNTERS, NAL_MASK);
330         break;
331
332     case 30:                   // undefined
333     case 31:                   // undefined
334     default:
335         av_log(ctx, AV_LOG_ERROR, "Undefined type (%d)\n", type);
336         result = AVERROR_INVALIDDATA;
337         break;
338     }
339
340     pkt->stream_index = st->index;
341
342     return result;
343 }
344
345 static PayloadContext *h264_new_context(void)
346 {
347     return av_mallocz(sizeof(PayloadContext));
348 }
349
350 static void h264_free_context(PayloadContext *data)
351 {
352 #ifdef DEBUG
353     int ii;
354
355     for (ii = 0; ii < 32; ii++) {
356         if (data->packet_types_received[ii])
357             av_log(NULL, AV_LOG_DEBUG, "Received %d packets of type %d\n",
358                    data->packet_types_received[ii], ii);
359     }
360 #endif
361
362     av_free(data);
363 }
364
365 static av_cold int h264_init(AVFormatContext *s, int st_index,
366                              PayloadContext *data)
367 {
368     if (st_index < 0)
369         return 0;
370     s->streams[st_index]->need_parsing = AVSTREAM_PARSE_FULL;
371     return 0;
372 }
373
374 static int parse_h264_sdp_line(AVFormatContext *s, int st_index,
375                                PayloadContext *h264_data, const char *line)
376 {
377     AVStream *stream;
378     AVCodecContext *codec;
379     const char *p = line;
380
381     if (st_index < 0)
382         return 0;
383
384     stream = s->streams[st_index];
385     codec  = stream->codec;
386
387     if (av_strstart(p, "framesize:", &p)) {
388         char buf1[50];
389         char *dst = buf1;
390
391         // remove the protocol identifier
392         while (*p && *p == ' ')
393             p++;                     // strip spaces.
394         while (*p && *p != ' ')
395             p++;                     // eat protocol identifier
396         while (*p && *p == ' ')
397             p++;                     // strip trailing spaces.
398         while (*p && *p != '-' && (dst - buf1) < sizeof(buf1) - 1)
399             *dst++ = *p++;
400         *dst = '\0';
401
402         // a='framesize:96 320-240'
403         // set our parameters
404         codec->width   = atoi(buf1);
405         codec->height  = atoi(p + 1); // skip the -
406     } else if (av_strstart(p, "fmtp:", &p)) {
407         return ff_parse_fmtp(s, stream, h264_data, p, sdp_parse_fmtp_config_h264);
408     } else if (av_strstart(p, "cliprect:", &p)) {
409         // could use this if we wanted.
410     }
411
412     return 0;
413 }
414
415 RTPDynamicProtocolHandler ff_h264_dynamic_handler = {
416     .enc_name         = "H264",
417     .codec_type       = AVMEDIA_TYPE_VIDEO,
418     .codec_id         = AV_CODEC_ID_H264,
419     .init             = h264_init,
420     .parse_sdp_a_line = parse_h264_sdp_line,
421     .alloc            = h264_new_context,
422     .free             = h264_free_context,
423     .parse_packet     = h264_handle_packet,
424 };