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