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