]> git.sesse.net Git - ffmpeg/blob - libavformat/rtpdec_hevc.c
avformat/utils: Fix division by 0
[ffmpeg] / libavformat / rtpdec_hevc.c
1 /*
2  * RTP parser for HEVC/H.265 payload format (draft version 6)
3  * Copyright (c) 2014 Thomas Volkert <thomas@homer-conferencing.com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  *
21  */
22
23 #include "libavutil/avassert.h"
24 #include "libavutil/avstring.h"
25 #include "libavutil/base64.h"
26
27 #include "avformat.h"
28 #include "rtpdec.h"
29
30 #define RTP_HEVC_PAYLOAD_HEADER_SIZE  2
31 #define RTP_HEVC_FU_HEADER_SIZE       1
32 #define RTP_HEVC_DONL_FIELD_SIZE      2
33 #define HEVC_SPECIFIED_NAL_UNIT_TYPES 48
34
35 /* SDP out-of-band signaling data */
36 struct PayloadContext {
37     int using_donl_field;
38     int profile_id;
39     uint8_t *sps, *pps, *vps, *sei;
40     int sps_size, pps_size, vps_size, sei_size;
41 };
42
43 static const uint8_t start_sequence[] = { 0x00, 0x00, 0x00, 0x01 };
44
45 static av_cold PayloadContext *hevc_new_context(void)
46 {
47     return av_mallocz(sizeof(PayloadContext));
48 }
49
50 static av_cold void hevc_free_context(PayloadContext *data)
51 {
52     av_free(data);
53 }
54
55 static av_cold int hevc_init(AVFormatContext *ctx, int st_index,
56                              PayloadContext *data)
57 {
58     av_dlog(ctx, "hevc_init() for stream %d\n", st_index);
59
60     if (st_index < 0)
61         return 0;
62
63     ctx->streams[st_index]->need_parsing = AVSTREAM_PARSE_FULL;
64
65     return 0;
66 }
67
68 static av_cold int hevc_sdp_parse_fmtp_config(AVFormatContext *s,
69                                               AVStream *stream,
70                                               PayloadContext *hevc_data,
71                                               char *attr, char *value)
72 {
73     /* profile-space: 0-3 */
74     /* profile-id: 0-31 */
75     if (!strcmp(attr, "profile-id")) {
76         hevc_data->profile_id = atoi(value);
77         av_dlog(s, "SDP: found profile-id: %d\n", hevc_data->profile_id);
78     }
79
80     /* tier-flag: 0-1 */
81     /* level-id: 0-255 */
82     /* interop-constraints: [base16] */
83     /* profile-compatibility-indicator: [base16] */
84     /* sprop-sub-layer-id: 0-6, defines highest possible value for TID, default: 6 */
85     /* recv-sub-layer-id: 0-6 */
86     /* max-recv-level-id: 0-255 */
87     /* tx-mode: MSM,SSM */
88     /* sprop-vps: [base64] */
89     /* sprop-sps: [base64] */
90     /* sprop-pps: [base64] */
91     /* sprop-sei: [base64] */
92     if (!strcmp(attr, "sprop-vps") || !strcmp(attr, "sprop-sps") ||
93         !strcmp(attr, "sprop-pps") || !strcmp(attr, "sprop-sei")) {
94         uint8_t **data_ptr;
95         int *size_ptr;
96         if (!strcmp(attr, "sprop-vps")) {
97             data_ptr = &hevc_data->vps;
98             size_ptr = &hevc_data->vps_size;
99         } else if (!strcmp(attr, "sprop-sps")) {
100             data_ptr = &hevc_data->sps;
101             size_ptr = &hevc_data->sps_size;
102         } else if (!strcmp(attr, "sprop-pps")) {
103             data_ptr = &hevc_data->pps;
104             size_ptr = &hevc_data->pps_size;
105         } else if (!strcmp(attr, "sprop-sei")) {
106             data_ptr = &hevc_data->sei;
107             size_ptr = &hevc_data->sei_size;
108         } else
109             av_assert0(0);
110
111         while (*value) {
112             char base64packet[1024];
113             uint8_t decoded_packet[1024];
114             int decoded_packet_size;
115             char *dst = base64packet;
116
117             while (*value && *value != ',' &&
118                    (dst - base64packet) < sizeof(base64packet) - 1) {
119                 *dst++ = *value++;
120             }
121             *dst++ = '\0';
122
123             if (*value == ',')
124                 value++;
125
126             decoded_packet_size = av_base64_decode(decoded_packet, base64packet,
127                                                    sizeof(decoded_packet));
128             if (decoded_packet_size > 0) {
129                 uint8_t *tmp = av_realloc(*data_ptr, decoded_packet_size +
130                                           sizeof(start_sequence) + *size_ptr);
131                 if (!tmp) {
132                     av_log(s, AV_LOG_ERROR,
133                            "Unable to allocate memory for extradata!\n");
134                     return AVERROR(ENOMEM);
135                 }
136                 *data_ptr = tmp;
137
138                 memcpy(*data_ptr + *size_ptr, start_sequence,
139                        sizeof(start_sequence));
140                 memcpy(*data_ptr + *size_ptr + sizeof(start_sequence),
141                        decoded_packet, decoded_packet_size);
142
143                 *size_ptr += sizeof(start_sequence) + decoded_packet_size;
144             }
145         }
146     }
147
148     /* max-lsr, max-lps, max-cpb, max-dpb, max-br, max-tr, max-tc */
149     /* max-fps */
150
151     /* sprop-max-don-diff: 0-32767
152
153          When the RTP stream depends on one or more other RTP
154          streams (in this case tx-mode MUST be equal to "MSM" and
155          MSM is in use), this parameter MUST be present and the
156          value MUST be greater than 0.
157     */
158     if (!strcmp(attr, "sprop-max-don-diff")) {
159         if (atoi(value) > 0)
160             hevc_data->using_donl_field = 1;
161         av_dlog(s, "Found sprop-max-don-diff in SDP, DON field usage is: %d\n",
162                 hevc_data->using_donl_field);
163     }
164
165     /* sprop-depack-buf-nalus: 0-32767 */
166     if (!strcmp(attr, "sprop-depack-buf-nalus")) {
167         if (atoi(value) > 0)
168             hevc_data->using_donl_field = 1;
169         av_dlog(s, "Found sprop-depack-buf-nalus in SDP, DON field usage is: %d\n",
170                 hevc_data->using_donl_field);
171     }
172
173     /* sprop-depack-buf-bytes: 0-4294967295 */
174     /* depack-buf-cap */
175     /* sprop-segmentation-id: 0-3 */
176     /* sprop-spatial-segmentation-idc: [base16] */
177     /* dec-parallel-ca: */
178     /* include-dph */
179
180     return 0;
181 }
182
183 static av_cold int hevc_parse_sdp_line(AVFormatContext *ctx, int st_index,
184                                        PayloadContext *hevc_data, const char *line)
185 {
186     AVStream *current_stream;
187     AVCodecContext *codec;
188     const char *sdp_line_ptr = line;
189
190     if (st_index < 0)
191         return 0;
192
193     current_stream = ctx->streams[st_index];
194     codec  = current_stream->codec;
195
196     if (av_strstart(sdp_line_ptr, "framesize:", &sdp_line_ptr)) {
197         char str_video_width[50];
198         char *str_video_width_ptr = str_video_width;
199
200         /*
201          * parse "a=framesize:96 320-240"
202          */
203
204         /* ignore spaces */
205         while (*sdp_line_ptr && *sdp_line_ptr == ' ')
206             sdp_line_ptr++;
207         /* ignore RTP payload ID */
208         while (*sdp_line_ptr && *sdp_line_ptr != ' ')
209             sdp_line_ptr++;
210         /* ignore spaces */
211         while (*sdp_line_ptr && *sdp_line_ptr == ' ')
212             sdp_line_ptr++;
213         /* extract the actual video resolution description */
214         while (*sdp_line_ptr && *sdp_line_ptr != '-' &&
215                (str_video_width_ptr - str_video_width) < sizeof(str_video_width) - 1)
216             *str_video_width_ptr++ = *sdp_line_ptr++;
217         /* add trailing zero byte */
218         *str_video_width_ptr = '\0';
219
220         /* determine the width value */
221         codec->width   = atoi(str_video_width);
222         /* jump beyond the "-" and determine the height value */
223         codec->height  = atoi(sdp_line_ptr + 1);
224     } else if (av_strstart(sdp_line_ptr, "fmtp:", &sdp_line_ptr)) {
225         int ret = ff_parse_fmtp(ctx, current_stream, hevc_data, sdp_line_ptr,
226                                 hevc_sdp_parse_fmtp_config);
227         if (hevc_data->vps_size || hevc_data->sps_size ||
228             hevc_data->pps_size || hevc_data->sei_size) {
229             av_freep(&codec->extradata);
230             codec->extradata_size = hevc_data->vps_size + hevc_data->sps_size +
231                                     hevc_data->pps_size + hevc_data->sei_size;
232             codec->extradata = av_malloc(codec->extradata_size +
233                                          FF_INPUT_BUFFER_PADDING_SIZE);
234             if (!codec->extradata) {
235                 ret = AVERROR(ENOMEM);
236                 codec->extradata_size = 0;
237             } else {
238                 int pos = 0;
239                 memcpy(codec->extradata + pos, hevc_data->vps, hevc_data->vps_size);
240                 pos += hevc_data->vps_size;
241                 memcpy(codec->extradata + pos, hevc_data->sps, hevc_data->sps_size);
242                 pos += hevc_data->sps_size;
243                 memcpy(codec->extradata + pos, hevc_data->pps, hevc_data->pps_size);
244                 pos += hevc_data->pps_size;
245                 memcpy(codec->extradata + pos, hevc_data->sei, hevc_data->sei_size);
246                 pos += hevc_data->sei_size;
247                 memset(codec->extradata + pos, 0, FF_INPUT_BUFFER_PADDING_SIZE);
248             }
249
250             av_freep(&hevc_data->vps);
251             av_freep(&hevc_data->sps);
252             av_freep(&hevc_data->pps);
253             av_freep(&hevc_data->sei);
254             hevc_data->vps_size = 0;
255             hevc_data->sps_size = 0;
256             hevc_data->pps_size = 0;
257             hevc_data->sei_size = 0;
258         }
259         return ret;
260     }
261
262     return 0;
263 }
264
265 static int hevc_handle_packet(AVFormatContext *ctx, PayloadContext *rtp_hevc_ctx,
266                               AVStream *st, AVPacket *pkt, uint32_t *timestamp,
267                               const uint8_t *buf, int len, uint16_t seq,
268                               int flags)
269 {
270     const uint8_t *rtp_pl = buf;
271     int tid, lid, nal_type;
272     int first_fragment, last_fragment, fu_type;
273     uint8_t new_nal_header[2];
274     int res = 0;
275
276     /* sanity check for size of input packet: 1 byte payload at least */
277     if (len < RTP_HEVC_PAYLOAD_HEADER_SIZE + 1) {
278         av_log(ctx, AV_LOG_ERROR, "Too short RTP/HEVC packet, got %d bytes\n", len);
279         return AVERROR_INVALIDDATA;
280     }
281
282     /*
283       decode the HEVC payload header according to section 4 of draft version 6:
284
285          0                   1
286          0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
287         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
288         |F|   Type    |  LayerId  | TID |
289         +-------------+-----------------+
290
291            Forbidden zero (F): 1 bit
292            NAL unit type (Type): 6 bits
293            NUH layer ID (LayerId): 6 bits
294            NUH temporal ID plus 1 (TID): 3 bits
295     */
296     nal_type =  (buf[0] >> 1) & 0x3f;
297     lid  = ((buf[0] << 5) & 0x20) | ((buf[1] >> 3) & 0x1f);
298     tid  =   buf[1] & 0x07;
299
300     /* sanity check for correct layer ID */
301     if (lid) {
302         /* future scalable or 3D video coding extensions */
303         avpriv_report_missing_feature(ctx, "Multi-layer HEVC coding\n");
304         return AVERROR_PATCHWELCOME;
305     }
306
307     /* sanity check for correct temporal ID */
308     if (!tid) {
309         av_log(ctx, AV_LOG_ERROR, "Illegal temporal ID in RTP/HEVC packet\n");
310         return AVERROR_INVALIDDATA;
311     }
312
313     /* sanity check for correct NAL unit type */
314     if (nal_type > 50) {
315         av_log(ctx, AV_LOG_ERROR, "Unsupported (HEVC) NAL type (%d)\n", nal_type);
316         return AVERROR_INVALIDDATA;
317     }
318
319     switch (nal_type) {
320     /* aggregated packets (AP) */
321     case 48:
322         /* pass the HEVC payload header */
323         buf += RTP_HEVC_PAYLOAD_HEADER_SIZE;
324         len -= RTP_HEVC_PAYLOAD_HEADER_SIZE;
325
326         /* pass the HEVC DONL field */
327         if (rtp_hevc_ctx->using_donl_field) {
328             buf += RTP_HEVC_DONL_FIELD_SIZE;
329             len -= RTP_HEVC_DONL_FIELD_SIZE;
330         }
331
332         /* fall-through */
333     /* video parameter set (VPS) */
334     case 32:
335     /* sequence parameter set (SPS) */
336     case 33:
337     /* picture parameter set (PPS) */
338     case 34:
339     /*  supplemental enhancement information (SEI) */
340     case 39:
341     /* single NAL unit packet */
342     default:
343         /* sanity check for size of input packet: 1 byte payload at least */
344         if (len < 1) {
345             av_log(ctx, AV_LOG_ERROR,
346                    "Too short RTP/HEVC packet, got %d bytes of NAL unit type %d\n",
347                    len, nal_type);
348             return AVERROR_INVALIDDATA;
349         }
350
351         /* create A/V packet */
352         if ((res = av_new_packet(pkt, sizeof(start_sequence) + len)) < 0)
353             return res;
354         /* A/V packet: copy start sequence */
355         memcpy(pkt->data, start_sequence, sizeof(start_sequence));
356         /* A/V packet: copy NAL unit data */
357         memcpy(pkt->data + sizeof(start_sequence), buf, len);
358
359         break;
360     /* fragmentation unit (FU) */
361     case 49:
362         /* pass the HEVC payload header */
363         buf += RTP_HEVC_PAYLOAD_HEADER_SIZE;
364         len -= RTP_HEVC_PAYLOAD_HEADER_SIZE;
365
366         /*
367              decode the FU header
368
369               0 1 2 3 4 5 6 7
370              +-+-+-+-+-+-+-+-+
371              |S|E|  FuType   |
372              +---------------+
373
374                 Start fragment (S): 1 bit
375                 End fragment (E): 1 bit
376                 FuType: 6 bits
377         */
378         first_fragment = buf[0] & 0x80;
379         last_fragment  = buf[0] & 0x40;
380         fu_type        = buf[0] & 0x3f;
381
382         /* pass the HEVC FU header */
383         buf += RTP_HEVC_FU_HEADER_SIZE;
384         len -= RTP_HEVC_FU_HEADER_SIZE;
385
386         /* pass the HEVC DONL field */
387         if (rtp_hevc_ctx->using_donl_field) {
388             buf += RTP_HEVC_DONL_FIELD_SIZE;
389             len -= RTP_HEVC_DONL_FIELD_SIZE;
390         }
391
392         av_dlog(ctx, " FU type %d with %d bytes\n", fu_type, len);
393
394         /* sanity check for size of input packet: 1 byte payload at least */
395         if (len > 0) {
396             new_nal_header[0] = (rtp_pl[0] & 0x81) | (fu_type << 1);
397             new_nal_header[1] = rtp_pl[1];
398
399             /* start fragment vs. subsequent fragments */
400             if (first_fragment) {
401                 if (!last_fragment) {
402                     /* create A/V packet which is big enough */
403                     if ((res = av_new_packet(pkt, sizeof(start_sequence) + sizeof(new_nal_header) + len)) < 0)
404                         return res;
405                     /* A/V packet: copy start sequence */
406                     memcpy(pkt->data, start_sequence, sizeof(start_sequence));
407                     /* A/V packet: copy new NAL header */
408                     memcpy(pkt->data + sizeof(start_sequence), new_nal_header, sizeof(new_nal_header));
409                     /* A/V packet: copy NAL unit data */
410                     memcpy(pkt->data + sizeof(start_sequence) + sizeof(new_nal_header), buf, len);
411                 } else {
412                     av_log(ctx, AV_LOG_ERROR, "Illegal combination of S and E bit in RTP/HEVC packet\n");
413                     res = AVERROR_INVALIDDATA;
414                 }
415             } else {
416                 /* create A/V packet */
417                 if ((res = av_new_packet(pkt, len)) < 0)
418                     return res;
419                 /* A/V packet: copy NAL unit data */
420                 memcpy(pkt->data, buf, len);
421             }
422         } else {
423             if (len < 0) {
424                 av_log(ctx, AV_LOG_ERROR,
425                        "Too short RTP/HEVC packet, got %d bytes of NAL unit type %d\n",
426                        len, nal_type);
427                 res = AVERROR_INVALIDDATA;
428             } else {
429                 res = AVERROR(EAGAIN);
430             }
431         }
432
433         break;
434     /* PACI packet */
435     case 50:
436         /* Temporal scalability control information (TSCI) */
437         avpriv_report_missing_feature(ctx, "PACI packets for RTP/HEVC\n");
438         res = AVERROR_PATCHWELCOME;
439         break;
440     }
441
442     pkt->stream_index = st->index;
443
444     return res;
445 }
446
447 RTPDynamicProtocolHandler ff_hevc_dynamic_handler = {
448     .enc_name         = "H265",
449     .codec_type       = AVMEDIA_TYPE_VIDEO,
450     .codec_id         = AV_CODEC_ID_HEVC,
451     .init             = hevc_init,
452     .parse_sdp_a_line = hevc_parse_sdp_line,
453     .alloc            = hevc_new_context,
454     .free             = hevc_free_context,
455     .parse_packet     = hevc_handle_packet
456 };