OSDN Git Service

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