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.

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