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.

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