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