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.

2047 lines
70KB

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