OSDN Git Service

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