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.

2028 lines
69KB

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