94fe1a8a14ad26de20842429cbd442163c52ce58
[libav.git] / libavcodec / h264.c
1 /*
2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
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 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
26 */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/display.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/stereo3d.h"
33 #include "libavutil/timer.h"
34 #include "internal.h"
35 #include "bytestream.h"
36 #include "cabac.h"
37 #include "cabac_functions.h"
38 #include "error_resilience.h"
39 #include "avcodec.h"
40 #include "h264.h"
41 #include "h2645_parse.h"
42 #include "h264data.h"
43 #include "h264chroma.h"
44 #include "h264_mvpred.h"
45 #include "golomb.h"
46 #include "mathops.h"
47 #include "me_cmp.h"
48 #include "mpegutils.h"
49 #include "profiles.h"
50 #include "rectangle.h"
51 #include "thread.h"
52
53 #include <assert.h>
54
55 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
56
57 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
58 int (*mv)[2][4][2],
59 int mb_x, int mb_y, int mb_intra, int mb_skipped)
60 {
61 H264Context *h = opaque;
62 H264SliceContext *sl = &h->slice_ctx[0];
63
64 sl->mb_x = mb_x;
65 sl->mb_y = mb_y;
66 sl->mb_xy = mb_x + mb_y * h->mb_stride;
67 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
68 assert(ref >= 0);
69 /* FIXME: It is possible albeit uncommon that slice references
70 * differ between slices. We take the easy approach and ignore
71 * it for now. If this turns out to have any relevance in
72 * practice then correct remapping should be added. */
73 if (ref >= sl->ref_count[0])
74 ref = 0;
75 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
76 2, 2, 2, ref, 1);
77 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
78 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
79 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
80 assert(!FRAME_MBAFF(h));
81 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
82 }
83
84 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
85 int y, int height)
86 {
87 AVCodecContext *avctx = h->avctx;
88 const AVFrame *src = h->cur_pic.f;
89 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
90 int vshift = desc->log2_chroma_h;
91 const int field_pic = h->picture_structure != PICT_FRAME;
92 if (field_pic) {
93 height <<= 1;
94 y <<= 1;
95 }
96
97 height = FFMIN(height, avctx->height - y);
98
99 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
100 return;
101
102 if (avctx->draw_horiz_band) {
103 int offset[AV_NUM_DATA_POINTERS];
104 int i;
105
106 offset[0] = y * src->linesize[0];
107 offset[1] =
108 offset[2] = (y >> vshift) * src->linesize[1];
109 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
110 offset[i] = 0;
111
112 emms_c();
113
114 avctx->draw_horiz_band(avctx, src, offset,
115 y, h->picture_structure, height);
116 }
117 }
118
119 const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
120 const uint8_t *src,
121 int *dst_length, int *consumed, int length)
122 {
123 int i, si, di;
124 uint8_t *dst;
125
126 // src[0]&0x80; // forbidden bit
127 h->nal_ref_idc = src[0] >> 5;
128 h->nal_unit_type = src[0] & 0x1F;
129
130 src++;
131 length--;
132
133 #define STARTCODE_TEST \
134 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
135 if (src[i + 2] != 3) { \
136 /* startcode, so we must be past the end */ \
137 length = i; \
138 } \
139 break; \
140 }
141
142 #if HAVE_FAST_UNALIGNED
143 #define FIND_FIRST_ZERO \
144 if (i > 0 && !src[i]) \
145 i--; \
146 while (src[i]) \
147 i++
148
149 #if HAVE_FAST_64BIT
150 for (i = 0; i + 1 < length; i += 9) {
151 if (!((~AV_RN64A(src + i) &
152 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
153 0x8000800080008080ULL))
154 continue;
155 FIND_FIRST_ZERO;
156 STARTCODE_TEST;
157 i -= 7;
158 }
159 #else
160 for (i = 0; i + 1 < length; i += 5) {
161 if (!((~AV_RN32A(src + i) &
162 (AV_RN32A(src + i) - 0x01000101U)) &
163 0x80008080U))
164 continue;
165 FIND_FIRST_ZERO;
166 STARTCODE_TEST;
167 i -= 3;
168 }
169 #endif
170 #else
171 for (i = 0; i + 1 < length; i += 2) {
172 if (src[i])
173 continue;
174 if (i > 0 && src[i - 1] == 0)
175 i--;
176 STARTCODE_TEST;
177 }
178 #endif
179
180 if (i >= length - 1) { // no escaped 0
181 *dst_length = length;
182 *consumed = length + 1; // +1 for the header
183 return src;
184 }
185
186 av_fast_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size,
187 length + AV_INPUT_BUFFER_PADDING_SIZE);
188 dst = sl->rbsp_buffer;
189
190 if (!dst)
191 return NULL;
192
193 memcpy(dst, src, i);
194 si = di = i;
195 while (si + 2 < length) {
196 // remove escapes (very rare 1:2^22)
197 if (src[si + 2] > 3) {
198 dst[di++] = src[si++];
199 dst[di++] = src[si++];
200 } else if (src[si] == 0 && src[si + 1] == 0) {
201 if (src[si + 2] == 3) { // escape
202 dst[di++] = 0;
203 dst[di++] = 0;
204 si += 3;
205 continue;
206 } else // next start code
207 goto nsc;
208 }
209
210 dst[di++] = src[si++];
211 }
212 while (si < length)
213 dst[di++] = src[si++];
214
215 nsc:
216 memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
217
218 *dst_length = di;
219 *consumed = si + 1; // +1 for the header
220 /* FIXME store exact number of bits in the getbitcontext
221 * (it is needed for decoding) */
222 return dst;
223 }
224
225 void ff_h264_free_tables(H264Context *h)
226 {
227 int i;
228
229 av_freep(&h->intra4x4_pred_mode);
230 av_freep(&h->chroma_pred_mode_table);
231 av_freep(&h->cbp_table);
232 av_freep(&h->mvd_table[0]);
233 av_freep(&h->mvd_table[1]);
234 av_freep(&h->direct_table);
235 av_freep(&h->non_zero_count);
236 av_freep(&h->slice_table_base);
237 h->slice_table = NULL;
238 av_freep(&h->list_counts);
239
240 av_freep(&h->mb2b_xy);
241 av_freep(&h->mb2br_xy);
242
243 av_buffer_pool_uninit(&h->qscale_table_pool);
244 av_buffer_pool_uninit(&h->mb_type_pool);
245 av_buffer_pool_uninit(&h->motion_val_pool);
246 av_buffer_pool_uninit(&h->ref_index_pool);
247
248 for (i = 0; i < h->nb_slice_ctx; i++) {
249 H264SliceContext *sl = &h->slice_ctx[i];
250
251 av_freep(&sl->dc_val_base);
252 av_freep(&sl->er.mb_index2xy);
253 av_freep(&sl->er.error_status_table);
254 av_freep(&sl->er.er_temp_buffer);
255
256 av_freep(&sl->bipred_scratchpad);
257 av_freep(&sl->edge_emu_buffer);
258 av_freep(&sl->top_borders[0]);
259 av_freep(&sl->top_borders[1]);
260
261 sl->bipred_scratchpad_allocated = 0;
262 sl->edge_emu_buffer_allocated = 0;
263 sl->top_borders_allocated[0] = 0;
264 sl->top_borders_allocated[1] = 0;
265 }
266 }
267
268 int ff_h264_alloc_tables(H264Context *h)
269 {
270 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
271 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
272 int x, y;
273
274 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
275 row_mb_num * 8 * sizeof(uint8_t), fail)
276 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
277
278 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
279 big_mb_num * 48 * sizeof(uint8_t), fail)
280 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
281 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
282 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
283 big_mb_num * sizeof(uint16_t), fail)
284 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
285 big_mb_num * sizeof(uint8_t), fail)
286 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
287 16 * row_mb_num * sizeof(uint8_t), fail);
288 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
289 16 * row_mb_num * sizeof(uint8_t), fail);
290 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
291 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
292
293 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
294 4 * big_mb_num * sizeof(uint8_t), fail);
295 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
296 big_mb_num * sizeof(uint8_t), fail)
297
298 memset(h->slice_table_base, -1,
299 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
300 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
301
302 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
303 big_mb_num * sizeof(uint32_t), fail);
304 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
305 big_mb_num * sizeof(uint32_t), fail);
306 for (y = 0; y < h->mb_height; y++)
307 for (x = 0; x < h->mb_width; x++) {
308 const int mb_xy = x + y * h->mb_stride;
309 const int b_xy = 4 * x + 4 * y * h->b_stride;
310
311 h->mb2b_xy[mb_xy] = b_xy;
312 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
313 }
314
315 if (!h->dequant4_coeff[0])
316 h264_init_dequant_tables(h);
317
318 return 0;
319
320 fail:
321 ff_h264_free_tables(h);
322 return AVERROR(ENOMEM);
323 }
324
325 /**
326 * Init context
327 * Allocate buffers which are not shared amongst multiple threads.
328 */
329 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
330 {
331 ERContext *er = &sl->er;
332 int mb_array_size = h->mb_height * h->mb_stride;
333 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
334 int c_size = h->mb_stride * (h->mb_height + 1);
335 int yc_size = y_size + 2 * c_size;
336 int x, y, i;
337
338 sl->ref_cache[0][scan8[5] + 1] =
339 sl->ref_cache[0][scan8[7] + 1] =
340 sl->ref_cache[0][scan8[13] + 1] =
341 sl->ref_cache[1][scan8[5] + 1] =
342 sl->ref_cache[1][scan8[7] + 1] =
343 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
344
345 if (CONFIG_ERROR_RESILIENCE) {
346 /* init ER */
347 er->avctx = h->avctx;
348 er->decode_mb = h264_er_decode_mb;
349 er->opaque = h;
350 er->quarter_sample = 1;
351
352 er->mb_num = h->mb_num;
353 er->mb_width = h->mb_width;
354 er->mb_height = h->mb_height;
355 er->mb_stride = h->mb_stride;
356 er->b8_stride = h->mb_width * 2 + 1;
357
358 // error resilience code looks cleaner with this
359 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
360 (h->mb_num + 1) * sizeof(int), fail);
361
362 for (y = 0; y < h->mb_height; y++)
363 for (x = 0; x < h->mb_width; x++)
364 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
365
366 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
367 h->mb_stride + h->mb_width;
368
369 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
370 mb_array_size * sizeof(uint8_t), fail);
371
372 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
373 h->mb_height * h->mb_stride, fail);
374
375 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
376 yc_size * sizeof(int16_t), fail);
377 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
378 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
379 er->dc_val[2] = er->dc_val[1] + c_size;
380 for (i = 0; i < yc_size; i++)
381 sl->dc_val_base[i] = 1024;
382 }
383
384 return 0;
385
386 fail:
387 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
388 }
389
390 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
391 int parse_extradata);
392
393 /* There are (invalid) samples in the wild with mp4-style extradata, where the
394 * parameter sets are stored unescaped (i.e. as RBSP).
395 * This function catches the parameter set decoding failure and tries again
396 * after escaping it */
397 static int decode_extradata_ps_mp4(H264Context *h, const uint8_t *buf, int buf_size)
398 {
399 int ret;
400
401 ret = decode_nal_units(h, buf, buf_size, 1);
402 if (ret < 0 && !(h->avctx->err_recognition & AV_EF_EXPLODE)) {
403 GetByteContext gbc;
404 PutByteContext pbc;
405 uint8_t *escaped_buf;
406 int escaped_buf_size;
407
408 av_log(h->avctx, AV_LOG_WARNING,
409 "SPS decoding failure, trying again after escaping the NAL\n");
410
411 if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
412 return AVERROR(ERANGE);
413 escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
414 escaped_buf = av_mallocz(escaped_buf_size);
415 if (!escaped_buf)
416 return AVERROR(ENOMEM);
417
418 bytestream2_init(&gbc, buf, buf_size);
419 bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
420
421 while (bytestream2_get_bytes_left(&gbc)) {
422 if (bytestream2_get_bytes_left(&gbc) >= 3 &&
423 bytestream2_peek_be24(&gbc) <= 3) {
424 bytestream2_put_be24(&pbc, 3);
425 bytestream2_skip(&gbc, 2);
426 } else
427 bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
428 }
429
430 escaped_buf_size = bytestream2_tell_p(&pbc);
431 AV_WB16(escaped_buf, escaped_buf_size - 2);
432
433 ret = decode_nal_units(h, escaped_buf, escaped_buf_size, 1);
434 av_freep(&escaped_buf);
435 if (ret < 0)
436 return ret;
437 }
438
439 return 0;
440 }
441
442 int ff_h264_decode_extradata(H264Context *h)
443 {
444 AVCodecContext *avctx = h->avctx;
445 int ret;
446
447 if (avctx->extradata[0] == 1) {
448 int i, cnt, nalsize;
449 unsigned char *p = avctx->extradata;
450
451 h->is_avc = 1;
452
453 if (avctx->extradata_size < 7) {
454 av_log(avctx, AV_LOG_ERROR,
455 "avcC %d too short\n", avctx->extradata_size);
456 return AVERROR_INVALIDDATA;
457 }
458 /* sps and pps in the avcC always have length coded with 2 bytes,
459 * so put a fake nal_length_size = 2 while parsing them */
460 h->nal_length_size = 2;
461 // Decode sps from avcC
462 cnt = *(p + 5) & 0x1f; // Number of sps
463 p += 6;
464 for (i = 0; i < cnt; i++) {
465 nalsize = AV_RB16(p) + 2;
466 if (p - avctx->extradata + nalsize > avctx->extradata_size)
467 return AVERROR_INVALIDDATA;
468 ret = decode_extradata_ps_mp4(h, p, nalsize);
469 if (ret < 0) {
470 av_log(avctx, AV_LOG_ERROR,
471 "Decoding sps %d from avcC failed\n", i);
472 return ret;
473 }
474 p += nalsize;
475 }
476 // Decode pps from avcC
477 cnt = *(p++); // Number of pps
478 for (i = 0; i < cnt; i++) {
479 nalsize = AV_RB16(p) + 2;
480 if (p - avctx->extradata + nalsize > avctx->extradata_size)
481 return AVERROR_INVALIDDATA;
482 ret = decode_extradata_ps_mp4(h, p, nalsize);
483 if (ret < 0) {
484 av_log(avctx, AV_LOG_ERROR,
485 "Decoding pps %d from avcC failed\n", i);
486 return ret;
487 }
488 p += nalsize;
489 }
490 // Store right nal length size that will be used to parse all other nals
491 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
492 } else {
493 h->is_avc = 0;
494 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
495 if (ret < 0)
496 return ret;
497 }
498 return 0;
499 }
500
501 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
502 {
503 int i;
504
505 h->avctx = avctx;
506 h->dequant_coeff_pps = -1;
507
508 h->picture_structure = PICT_FRAME;
509 h->slice_context_count = 1;
510 h->workaround_bugs = avctx->workaround_bugs;
511 h->flags = avctx->flags;
512 h->prev_poc_msb = 1 << 16;
513 h->x264_build = -1;
514 h->recovery_frame = -1;
515 h->frame_recovered = 0;
516
517 h->next_outputed_poc = INT_MIN;
518 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
519 h->last_pocs[i] = INT_MIN;
520
521 ff_h264_reset_sei(h);
522
523 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
524
525 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
526 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
527 if (!h->slice_ctx) {
528 h->nb_slice_ctx = 0;
529 return AVERROR(ENOMEM);
530 }
531
532 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
533 h->DPB[i].f = av_frame_alloc();
534 if (!h->DPB[i].f)
535 return AVERROR(ENOMEM);
536 }
537
538 h->cur_pic.f = av_frame_alloc();
539 if (!h->cur_pic.f)
540 return AVERROR(ENOMEM);
541
542 for (i = 0; i < h->nb_slice_ctx; i++)
543 h->slice_ctx[i].h264 = h;
544
545 return 0;
546 }
547
548 static AVOnce h264_vlc_init = AV_ONCE_INIT;
549
550 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
551 {
552 H264Context *h = avctx->priv_data;
553 int ret;
554
555 ret = h264_init_context(avctx, h);
556 if (ret < 0)
557 return ret;
558
559 /* set defaults */
560 if (!avctx->has_b_frames)
561 h->low_delay = 1;
562
563 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
564 if (ret != 0) {
565 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
566 return AVERROR_UNKNOWN;
567 }
568
569 if (avctx->codec_id == AV_CODEC_ID_H264) {
570 if (avctx->ticks_per_frame == 1)
571 h->avctx->framerate.num *= 2;
572 avctx->ticks_per_frame = 2;
573 }
574
575 if (avctx->extradata_size > 0 && avctx->extradata) {
576 ret = ff_h264_decode_extradata(h);
577 if (ret < 0) {
578 ff_h264_free_context(h);
579 return ret;
580 }
581 }
582
583 if (h->sps.bitstream_restriction_flag &&
584 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
585 h->avctx->has_b_frames = h->sps.num_reorder_frames;
586 h->low_delay = 0;
587 }
588
589 avctx->internal->allocate_progress = 1;
590
591 if (h->enable_er) {
592 av_log(avctx, AV_LOG_WARNING,
593 "Error resilience is enabled. It is unsafe and unsupported and may crash. "
594 "Use it at your own risk\n");
595 }
596
597 return 0;
598 }
599
600 static int decode_init_thread_copy(AVCodecContext *avctx)
601 {
602 H264Context *h = avctx->priv_data;
603 int ret;
604
605 if (!avctx->internal->is_copy)
606 return 0;
607
608 memset(h, 0, sizeof(*h));
609
610 ret = h264_init_context(avctx, h);
611 if (ret < 0)
612 return ret;
613
614 h->context_initialized = 0;
615
616 return 0;
617 }
618
619 /**
620 * Run setup operations that must be run after slice header decoding.
621 * This includes finding the next displayed frame.
622 *
623 * @param h h264 master context
624 * @param setup_finished enough NALs have been read that we can call
625 * ff_thread_finish_setup()
626 */
627 static void decode_postinit(H264Context *h, int setup_finished)
628 {
629 H264Picture *out = h->cur_pic_ptr;
630 H264Picture *cur = h->cur_pic_ptr;
631 int i, pics, out_of_order, out_idx;
632 int invalid = 0, cnt = 0;
633
634 h->cur_pic_ptr->f->pict_type = h->pict_type;
635
636 if (h->next_output_pic)
637 return;
638
639 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
640 /* FIXME: if we have two PAFF fields in one packet, we can't start
641 * the next thread here. If we have one field per packet, we can.
642 * The check in decode_nal_units() is not good enough to find this
643 * yet, so we assume the worst for now. */
644 // if (setup_finished)
645 // ff_thread_finish_setup(h->avctx);
646 return;
647 }
648
649 cur->f->interlaced_frame = 0;
650 cur->f->repeat_pict = 0;
651
652 /* Signal interlacing information externally. */
653 /* Prioritize picture timing SEI information over used
654 * decoding process if it exists. */
655
656 if (h->sps.pic_struct_present_flag) {
657 switch (h->sei_pic_struct) {
658 case SEI_PIC_STRUCT_FRAME:
659 break;
660 case SEI_PIC_STRUCT_TOP_FIELD:
661 case SEI_PIC_STRUCT_BOTTOM_FIELD:
662 cur->f->interlaced_frame = 1;
663 break;
664 case SEI_PIC_STRUCT_TOP_BOTTOM:
665 case SEI_PIC_STRUCT_BOTTOM_TOP:
666 if (FIELD_OR_MBAFF_PICTURE(h))
667 cur->f->interlaced_frame = 1;
668 else
669 // try to flag soft telecine progressive
670 cur->f->interlaced_frame = h->prev_interlaced_frame;
671 break;
672 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
673 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
674 /* Signal the possibility of telecined film externally
675 * (pic_struct 5,6). From these hints, let the applications
676 * decide if they apply deinterlacing. */
677 cur->f->repeat_pict = 1;
678 break;
679 case SEI_PIC_STRUCT_FRAME_DOUBLING:
680 cur->f->repeat_pict = 2;
681 break;
682 case SEI_PIC_STRUCT_FRAME_TRIPLING:
683 cur->f->repeat_pict = 4;
684 break;
685 }
686
687 if ((h->sei_ct_type & 3) &&
688 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
689 cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
690 } else {
691 /* Derive interlacing flag from used decoding process. */
692 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
693 }
694 h->prev_interlaced_frame = cur->f->interlaced_frame;
695
696 if (cur->field_poc[0] != cur->field_poc[1]) {
697 /* Derive top_field_first from field pocs. */
698 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
699 } else {
700 if (cur->f->interlaced_frame || h->sps.pic_struct_present_flag) {
701 /* Use picture timing SEI information. Even if it is a
702 * information of a past frame, better than nothing. */
703 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
704 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
705 cur->f->top_field_first = 1;
706 else
707 cur->f->top_field_first = 0;
708 } else {
709 /* Most likely progressive */
710 cur->f->top_field_first = 0;
711 }
712 }
713
714 if (h->sei_frame_packing_present &&
715 h->frame_packing_arrangement_type >= 0 &&
716 h->frame_packing_arrangement_type <= 6 &&
717 h->content_interpretation_type > 0 &&
718 h->content_interpretation_type < 3) {
719 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
720 if (!stereo)
721 return;
722
723 switch (h->frame_packing_arrangement_type) {
724 case 0:
725 stereo->type = AV_STEREO3D_CHECKERBOARD;
726 break;
727 case 1:
728 stereo->type = AV_STEREO3D_COLUMNS;
729 break;
730 case 2:
731 stereo->type = AV_STEREO3D_LINES;
732 break;
733 case 3:
734 if (h->quincunx_subsampling)
735 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
736 else
737 stereo->type = AV_STEREO3D_SIDEBYSIDE;
738 break;
739 case 4:
740 stereo->type = AV_STEREO3D_TOPBOTTOM;
741 break;
742 case 5:
743 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
744 break;
745 case 6:
746 stereo->type = AV_STEREO3D_2D;
747 break;
748 }
749
750 if (h->content_interpretation_type == 2)
751 stereo->flags = AV_STEREO3D_FLAG_INVERT;
752 }
753
754 if (h->sei_display_orientation_present &&
755 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
756 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
757 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
758 AV_FRAME_DATA_DISPLAYMATRIX,
759 sizeof(int32_t) * 9);
760 if (!rotation)
761 return;
762
763 av_display_rotation_set((int32_t *)rotation->data, angle);
764 av_display_matrix_flip((int32_t *)rotation->data,
765 h->sei_hflip, h->sei_vflip);
766 }
767
768 if (h->sei_reguserdata_afd_present) {
769 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
770 sizeof(uint8_t));
771 if (!sd)
772 return;
773
774 *sd->data = h->active_format_description;
775 h->sei_reguserdata_afd_present = 0;
776 }
777
778 if (h->a53_caption) {
779 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
780 AV_FRAME_DATA_A53_CC,
781 h->a53_caption_size);
782 if (!sd)
783 return;
784
785 memcpy(sd->data, h->a53_caption, h->a53_caption_size);
786 av_freep(&h->a53_caption);
787 h->a53_caption_size = 0;
788 }
789
790 // FIXME do something with unavailable reference frames
791
792 /* Sort B-frames into display order */
793 if (h->sps.bitstream_restriction_flag ||
794 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
795 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
796 }
797 h->low_delay = !h->avctx->has_b_frames;
798
799 pics = 0;
800 while (h->delayed_pic[pics])
801 pics++;
802
803 assert(pics <= MAX_DELAYED_PIC_COUNT);
804
805 h->delayed_pic[pics++] = cur;
806 if (cur->reference == 0)
807 cur->reference = DELAYED_PIC_REF;
808
809 /* Frame reordering. This code takes pictures from coding order and sorts
810 * them by their incremental POC value into display order. It supports POC
811 * gaps, MMCO reset codes and random resets.
812 * A "display group" can start either with a IDR frame (f.key_frame = 1),
813 * and/or can be closed down with a MMCO reset code. In sequences where
814 * there is no delay, we can't detect that (since the frame was already
815 * output to the user), so we also set h->mmco_reset to detect the MMCO
816 * reset code.
817 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
818 * we increase the delay between input and output. All frames affected by
819 * the lag (e.g. those that should have been output before another frame
820 * that we already returned to the user) will be dropped. This is a bug
821 * that we will fix later. */
822 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
823 cnt += out->poc < h->last_pocs[i];
824 invalid += out->poc == INT_MIN;
825 }
826 if (!h->mmco_reset && !cur->f->key_frame &&
827 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
828 h->mmco_reset = 2;
829 if (pics > 1)
830 h->delayed_pic[pics - 2]->mmco_reset = 2;
831 }
832 if (h->mmco_reset || cur->f->key_frame) {
833 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
834 h->last_pocs[i] = INT_MIN;
835 cnt = 0;
836 invalid = MAX_DELAYED_PIC_COUNT;
837 }
838 out = h->delayed_pic[0];
839 out_idx = 0;
840 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
841 h->delayed_pic[i] &&
842 !h->delayed_pic[i - 1]->mmco_reset &&
843 !h->delayed_pic[i]->f->key_frame;
844 i++)
845 if (h->delayed_pic[i]->poc < out->poc) {
846 out = h->delayed_pic[i];
847 out_idx = i;
848 }
849 if (h->avctx->has_b_frames == 0 &&
850 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
851 h->next_outputed_poc = INT_MIN;
852 out_of_order = !out->f->key_frame && !h->mmco_reset &&
853 (out->poc < h->next_outputed_poc);
854
855 if (h->sps.bitstream_restriction_flag &&
856 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
857 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
858 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
859 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
860 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
861 }
862 h->low_delay = 0;
863 } else if (h->low_delay &&
864 ((h->next_outputed_poc != INT_MIN &&
865 out->poc > h->next_outputed_poc + 2) ||
866 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
867 h->low_delay = 0;
868 h->avctx->has_b_frames++;
869 }
870
871 if (pics > h->avctx->has_b_frames) {
872 out->reference &= ~DELAYED_PIC_REF;
873 // for frame threading, the owner must be the second field's thread or
874 // else the first thread can release the picture and reuse it unsafely
875 for (i = out_idx; h->delayed_pic[i]; i++)
876 h->delayed_pic[i] = h->delayed_pic[i + 1];
877 }
878 memmove(h->last_pocs, &h->last_pocs[1],
879 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
880 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
881 if (!out_of_order && pics > h->avctx->has_b_frames) {
882 h->next_output_pic = out;
883 if (out->mmco_reset) {
884 if (out_idx > 0) {
885 h->next_outputed_poc = out->poc;
886 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
887 } else {
888 h->next_outputed_poc = INT_MIN;
889 }
890 } else {
891 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
892 h->next_outputed_poc = INT_MIN;
893 } else {
894 h->next_outputed_poc = out->poc;
895 }
896 }
897 h->mmco_reset = 0;
898 } else {
899 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
900 }
901
902 if (h->next_output_pic) {
903 if (h->next_output_pic->recovered) {
904 // We have reached an recovery point and all frames after it in
905 // display order are "recovered".
906 h->frame_recovered |= FRAME_RECOVERED_SEI;
907 }
908 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
909 }
910
911 if (setup_finished && !h->avctx->hwaccel) {
912 ff_thread_finish_setup(h->avctx);
913
914 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
915 h->setup_finished = 1;
916 }
917 }
918
919 /**
920 * instantaneous decoder refresh.
921 */
922 static void idr(H264Context *h)
923 {
924 ff_h264_remove_all_refs(h);
925 h->prev_frame_num =
926 h->prev_frame_num_offset =
927 h->prev_poc_msb =
928 h->prev_poc_lsb = 0;
929 }
930
931 /* forget old pics after a seek */
932 void ff_h264_flush_change(H264Context *h)
933 {
934 int i;
935 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
936 h->last_pocs[i] = INT_MIN;
937 h->next_outputed_poc = INT_MIN;
938 h->prev_interlaced_frame = 1;
939 idr(h);
940 if (h->cur_pic_ptr)
941 h->cur_pic_ptr->reference = 0;
942 h->first_field = 0;
943 ff_h264_reset_sei(h);
944 h->recovery_frame = -1;
945 h->frame_recovered = 0;
946 }
947
948 /* forget old pics after a seek */
949 static void flush_dpb(AVCodecContext *avctx)
950 {
951 H264Context *h = avctx->priv_data;
952 int i;
953
954 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
955
956 ff_h264_flush_change(h);
957
958 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
959 ff_h264_unref_picture(h, &h->DPB[i]);
960 h->cur_pic_ptr = NULL;
961 ff_h264_unref_picture(h, &h->cur_pic);
962
963 h->mb_y = 0;
964
965 ff_h264_free_tables(h);
966 h->context_initialized = 0;
967 }
968
969 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
970 {
971 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
972 int field_poc[2];
973
974 h->frame_num_offset = h->prev_frame_num_offset;
975 if (h->frame_num < h->prev_frame_num)
976 h->frame_num_offset += max_frame_num;
977
978 if (h->sps.poc_type == 0) {
979 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
980
981 if (h->poc_lsb < h->prev_poc_lsb &&
982 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
983 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
984 else if (h->poc_lsb > h->prev_poc_lsb &&
985 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
986 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
987 else
988 h->poc_msb = h->prev_poc_msb;
989 field_poc[0] =
990 field_poc[1] = h->poc_msb + h->poc_lsb;
991 if (h->picture_structure == PICT_FRAME)
992 field_poc[1] += h->delta_poc_bottom;
993 } else if (h->sps.poc_type == 1) {
994 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
995 int i;
996
997 if (h->sps.poc_cycle_length != 0)
998 abs_frame_num = h->frame_num_offset + h->frame_num;
999 else
1000 abs_frame_num = 0;
1001
1002 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1003 abs_frame_num--;
1004
1005 expected_delta_per_poc_cycle = 0;
1006 for (i = 0; i < h->sps.poc_cycle_length; i++)
1007 // FIXME integrate during sps parse
1008 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1009
1010 if (abs_frame_num > 0) {
1011 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1012 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1013
1014 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1015 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1016 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1017 } else
1018 expectedpoc = 0;
1019
1020 if (h->nal_ref_idc == 0)
1021 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1022
1023 field_poc[0] = expectedpoc + h->delta_poc[0];
1024 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1025
1026 if (h->picture_structure == PICT_FRAME)
1027 field_poc[1] += h->delta_poc[1];
1028 } else {
1029 int poc = 2 * (h->frame_num_offset + h->frame_num);
1030
1031 if (!h->nal_ref_idc)
1032 poc--;
1033
1034 field_poc[0] = poc;
1035 field_poc[1] = poc;
1036 }
1037
1038 if (h->picture_structure != PICT_BOTTOM_FIELD)
1039 pic_field_poc[0] = field_poc[0];
1040 if (h->picture_structure != PICT_TOP_FIELD)
1041 pic_field_poc[1] = field_poc[1];
1042 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1043
1044 return 0;
1045 }
1046
1047 /**
1048 * Compute profile from profile_idc and constraint_set?_flags.
1049 *
1050 * @param sps SPS
1051 *
1052 * @return profile as defined by FF_PROFILE_H264_*
1053 */
1054 int ff_h264_get_profile(SPS *sps)
1055 {
1056 int profile = sps->profile_idc;
1057
1058 switch (sps->profile_idc) {
1059 case FF_PROFILE_H264_BASELINE:
1060 // constraint_set1_flag set to 1
1061 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1062 break;
1063 case FF_PROFILE_H264_HIGH_10:
1064 case FF_PROFILE_H264_HIGH_422:
1065 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1066 // constraint_set3_flag set to 1
1067 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1068 break;
1069 }
1070
1071 return profile;
1072 }
1073
1074 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1075 {
1076 int ref_count[2], list_count;
1077 int num_ref_idx_active_override_flag, max_refs;
1078
1079 // set defaults, might be overridden a few lines later
1080 ref_count[0] = h->pps.ref_count[0];
1081 ref_count[1] = h->pps.ref_count[1];
1082
1083 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1084 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1085 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1086 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1087
1088 if (num_ref_idx_active_override_flag) {
1089 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1090 if (ref_count[0] < 1)
1091 return AVERROR_INVALIDDATA;
1092 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1093 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1094 if (ref_count[1] < 1)
1095 return AVERROR_INVALIDDATA;
1096 }
1097 }
1098
1099 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1100 list_count = 2;
1101 else
1102 list_count = 1;
1103 } else {
1104 list_count = 0;
1105 ref_count[0] = ref_count[1] = 0;
1106 }
1107
1108 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1109
1110 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1111 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1112 sl->ref_count[0] = sl->ref_count[1] = 0;
1113 return AVERROR_INVALIDDATA;
1114 }
1115
1116 if (list_count != sl->list_count ||
1117 ref_count[0] != sl->ref_count[0] ||
1118 ref_count[1] != sl->ref_count[1]) {
1119 sl->ref_count[0] = ref_count[0];
1120 sl->ref_count[1] = ref_count[1];
1121 sl->list_count = list_count;
1122 return 1;
1123 }
1124
1125 return 0;
1126 }
1127
1128 static int get_last_needed_nal(H264Context *h)
1129 {
1130 int nals_needed = 0;
1131 int i;
1132
1133 for (i = 0; i < h->pkt.nb_nals; i++) {
1134 H2645NAL *nal = &h->pkt.nals[i];
1135 GetBitContext gb;
1136
1137 /* packets can sometimes contain multiple PPS/SPS,
1138 * e.g. two PAFF field pictures in one packet, or a demuxer
1139 * which splits NALs strangely if so, when frame threading we
1140 * can't start the next thread until we've read all of them */
1141 switch (nal->type) {
1142 case NAL_SPS:
1143 case NAL_PPS:
1144 nals_needed = i;
1145 break;
1146 case NAL_DPA:
1147 case NAL_IDR_SLICE:
1148 case NAL_SLICE:
1149 init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
1150 if (!get_ue_golomb(&gb))
1151 nals_needed = i;
1152 }
1153 }
1154
1155 return nals_needed;
1156 }
1157
1158 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1159 int parse_extradata)
1160 {
1161 AVCodecContext *const avctx = h->avctx;
1162 unsigned context_count = 0;
1163 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1164 int i, ret = 0;
1165
1166 h->max_contexts = h->slice_context_count;
1167 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1168 h->current_slice = 0;
1169 if (!h->first_field)
1170 h->cur_pic_ptr = NULL;
1171 ff_h264_reset_sei(h);
1172 }
1173
1174 ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
1175 h->nal_length_size, avctx->codec_id);
1176 if (ret < 0) {
1177 av_log(avctx, AV_LOG_ERROR,
1178 "Error splitting the input into NAL units.\n");
1179 return ret;
1180 }
1181
1182 if (avctx->active_thread_type & FF_THREAD_FRAME)
1183 nals_needed = get_last_needed_nal(h);
1184
1185 for (i = 0; i < h->pkt.nb_nals; i++) {
1186 H2645NAL *nal = &h->pkt.nals[i];
1187 H264SliceContext *sl = &h->slice_ctx[context_count];
1188 int err;
1189
1190 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1191 nal->ref_idc == 0 && nal->type != NAL_SEI)
1192 continue;
1193
1194 again:
1195 /* Ignore every NAL unit type except PPS and SPS during extradata
1196 * parsing. Decoding slices is not possible in codec init
1197 * with frame-mt */
1198 if (parse_extradata && HAVE_THREADS &&
1199 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1200 (nal->type != NAL_PPS && nal->type != NAL_SPS)) {
1201 if (nal->type < NAL_AUD || nal->type > NAL_AUXILIARY_SLICE)
1202 av_log(avctx, AV_LOG_INFO,
1203 "Ignoring NAL unit %d during extradata parsing\n",
1204 nal->type);
1205 nal->type = NAL_FF_IGNORE;
1206 }
1207
1208 // FIXME these should stop being context-global variables
1209 h->nal_ref_idc = nal->ref_idc;
1210 h->nal_unit_type = nal->type;
1211
1212 err = 0;
1213 switch (nal->type) {
1214 case NAL_IDR_SLICE:
1215 if (nal->type != NAL_IDR_SLICE) {
1216 av_log(h->avctx, AV_LOG_ERROR,
1217 "Invalid mix of idr and non-idr slices\n");
1218 ret = -1;
1219 goto end;
1220 }
1221 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1222 case NAL_SLICE:
1223 sl->gb = nal->gb;
1224
1225 if ((err = ff_h264_decode_slice_header(h, sl)))
1226 break;
1227
1228 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1229 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1230 ((1 << h->sps.log2_max_frame_num) - 1);
1231 }
1232
1233 h->cur_pic_ptr->f->key_frame |=
1234 (nal->type == NAL_IDR_SLICE) || (h->sei_recovery_frame_cnt >= 0);
1235
1236 if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->frame_num) {
1237 h->recovery_frame = -1;
1238 h->cur_pic_ptr->recovered = 1;
1239 }
1240 // If we have an IDR, all frames after it in decoded order are
1241 // "recovered".
1242 if (nal->type == NAL_IDR_SLICE)
1243 h->frame_recovered |= FRAME_RECOVERED_IDR;
1244 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1245
1246 if (h->current_slice == 1) {
1247 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1248 decode_postinit(h, i >= nals_needed);
1249
1250 if (h->avctx->hwaccel &&
1251 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1252 return ret;
1253 }
1254
1255 if (sl->redundant_pic_count == 0 &&
1256 (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
1257 (avctx->skip_frame < AVDISCARD_BIDIR ||
1258 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1259 (avctx->skip_frame < AVDISCARD_NONKEY ||
1260 h->cur_pic_ptr->f->key_frame) &&
1261 avctx->skip_frame < AVDISCARD_ALL) {
1262 if (avctx->hwaccel) {
1263 ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
1264 if (ret < 0)
1265 return ret;
1266 } else
1267 context_count++;
1268 }
1269 break;
1270 case NAL_DPA:
1271 case NAL_DPB:
1272 case NAL_DPC:
1273 avpriv_request_sample(avctx, "data partitioning");
1274 ret = AVERROR(ENOSYS);
1275 goto end;
1276 break;
1277 case NAL_SEI:
1278 h->gb = nal->gb;
1279 ret = ff_h264_decode_sei(h);
1280 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1281 goto end;
1282 break;
1283 case NAL_SPS:
1284 h->gb = nal->gb;
1285 ret = ff_h264_decode_seq_parameter_set(h);
1286 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1287 goto end;
1288 break;
1289 case NAL_PPS:
1290 h->gb = nal->gb;
1291 ret = ff_h264_decode_picture_parameter_set(h, nal->size_bits);
1292 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1293 goto end;
1294 break;
1295 case NAL_AUD:
1296 case NAL_END_SEQUENCE:
1297 case NAL_END_STREAM:
1298 case NAL_FILLER_DATA:
1299 case NAL_SPS_EXT:
1300 case NAL_AUXILIARY_SLICE:
1301 break;
1302 case NAL_FF_IGNORE:
1303 break;
1304 default:
1305 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1306 nal->type, nal->size_bits);
1307 }
1308
1309 if (context_count == h->max_contexts) {
1310 ret = ff_h264_execute_decode_slices(h, context_count);
1311 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1312 goto end;
1313 context_count = 0;
1314 }
1315
1316 if (err < 0) {
1317 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1318 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1319 } else if (err == 1) {
1320 /* Slice could not be decoded in parallel mode, restart. Note
1321 * that rbsp_buffer is not transferred, but since we no longer
1322 * run in parallel mode this should not be an issue. */
1323 sl = &h->slice_ctx[0];
1324 goto again;
1325 }
1326 }
1327 if (context_count) {
1328 ret = ff_h264_execute_decode_slices(h, context_count);
1329 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1330 goto end;
1331 }
1332
1333 ret = 0;
1334 end:
1335 /* clean up */
1336 if (h->cur_pic_ptr && !h->droppable) {
1337 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1338 h->picture_structure == PICT_BOTTOM_FIELD);
1339 }
1340
1341 return (ret < 0) ? ret : buf_size;
1342 }
1343
1344 /**
1345 * Return the number of bytes consumed for building the current frame.
1346 */
1347 static int get_consumed_bytes(int pos, int buf_size)
1348 {
1349 if (pos == 0)
1350 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1351 if (pos + 10 > buf_size)
1352 pos = buf_size; // oops ;)
1353
1354 return pos;
1355 }
1356
1357 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1358 {
1359 int i;
1360 int ret = av_frame_ref(dst, src);
1361 if (ret < 0)
1362 return ret;
1363
1364 if (!h->sps.crop)
1365 return 0;
1366
1367 for (i = 0; i < 3; i++) {
1368 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1369 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1370 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1371 (h->sps.crop_top >> vshift) * dst->linesize[i];
1372 dst->data[i] += off;
1373 }
1374 return 0;
1375 }
1376
1377 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1378 int *got_frame, AVPacket *avpkt)
1379 {
1380 const uint8_t *buf = avpkt->data;
1381 int buf_size = avpkt->size;
1382 H264Context *h = avctx->priv_data;
1383 AVFrame *pict = data;
1384 int buf_index = 0;
1385 int ret;
1386
1387 h->flags = avctx->flags;
1388 h->setup_finished = 0;
1389
1390 /* end of stream, output what is still in the buffers */
1391 out:
1392 if (buf_size == 0) {
1393 H264Picture *out;
1394 int i, out_idx;
1395
1396 h->cur_pic_ptr = NULL;
1397
1398 // FIXME factorize this with the output code below
1399 out = h->delayed_pic[0];
1400 out_idx = 0;
1401 for (i = 1;
1402 h->delayed_pic[i] &&
1403 !h->delayed_pic[i]->f->key_frame &&
1404 !h->delayed_pic[i]->mmco_reset;
1405 i++)
1406 if (h->delayed_pic[i]->poc < out->poc) {
1407 out = h->delayed_pic[i];
1408 out_idx = i;
1409 }
1410
1411 for (i = out_idx; h->delayed_pic[i]; i++)
1412 h->delayed_pic[i] = h->delayed_pic[i + 1];
1413
1414 if (out) {
1415 ret = output_frame(h, pict, out->f);
1416 if (ret < 0)
1417 return ret;
1418 *got_frame = 1;
1419 }
1420
1421 return buf_index;
1422 }
1423
1424 buf_index = decode_nal_units(h, buf, buf_size, 0);
1425 if (buf_index < 0)
1426 return AVERROR_INVALIDDATA;
1427
1428 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1429 buf_size = 0;
1430 goto out;
1431 }
1432
1433 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1434 if (avctx->skip_frame >= AVDISCARD_NONREF)
1435 return 0;
1436 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1437 return AVERROR_INVALIDDATA;
1438 }
1439
1440 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1441 (h->mb_y >= h->mb_height && h->mb_height)) {
1442 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1443 decode_postinit(h, 1);
1444
1445 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1446
1447 *got_frame = 0;
1448 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1449 h->next_output_pic->recovered)) {
1450 if (!h->next_output_pic->recovered)
1451 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1452
1453 ret = output_frame(h, pict, h->next_output_pic->f);
1454 if (ret < 0)
1455 return ret;
1456 *got_frame = 1;
1457 }
1458 }
1459
1460 assert(pict->buf[0] || !*got_frame);
1461
1462 return get_consumed_bytes(buf_index, buf_size);
1463 }
1464
1465 av_cold void ff_h264_free_context(H264Context *h)
1466 {
1467 int i;
1468
1469 ff_h264_free_tables(h);
1470
1471 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1472 ff_h264_unref_picture(h, &h->DPB[i]);
1473 av_frame_free(&h->DPB[i].f);
1474 }
1475
1476 h->cur_pic_ptr = NULL;
1477
1478 for (i = 0; i < h->nb_slice_ctx; i++)
1479 av_freep(&h->slice_ctx[i].rbsp_buffer);
1480 av_freep(&h->slice_ctx);
1481 h->nb_slice_ctx = 0;
1482
1483 for (i = 0; i < MAX_SPS_COUNT; i++)
1484 av_freep(h->sps_buffers + i);
1485
1486 for (i = 0; i < MAX_PPS_COUNT; i++)
1487 av_freep(h->pps_buffers + i);
1488
1489 ff_h2645_packet_uninit(&h->pkt);
1490 }
1491
1492 static av_cold int h264_decode_end(AVCodecContext *avctx)
1493 {
1494 H264Context *h = avctx->priv_data;
1495
1496 ff_h264_free_context(h);
1497
1498 ff_h264_unref_picture(h, &h->cur_pic);
1499 av_frame_free(&h->cur_pic.f);
1500
1501 return 0;
1502 }
1503
1504 #define OFFSET(x) offsetof(H264Context, x)
1505 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1506 static const AVOption h264_options[] = {
1507 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1508 { NULL },
1509 };
1510
1511 static const AVClass h264_class = {
1512 .class_name = "h264",
1513 .item_name = av_default_item_name,
1514 .option = h264_options,
1515 .version = LIBAVUTIL_VERSION_INT,
1516 };
1517
1518 AVCodec ff_h264_decoder = {
1519 .name = "h264",
1520 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1521 .type = AVMEDIA_TYPE_VIDEO,
1522 .id = AV_CODEC_ID_H264,
1523 .priv_data_size = sizeof(H264Context),
1524 .init = ff_h264_decode_init,
1525 .close = h264_decode_end,
1526 .decode = h264_decode_frame,
1527 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1528 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1529 AV_CODEC_CAP_FRAME_THREADS,
1530 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1531 .flush = flush_dpb,
1532 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1533 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1534 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1535 .priv_class = &h264_class,
1536 };