You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1874 lines
63KB

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