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