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.

2049 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 (is_chroma && (h->left_samples_available & 0x8080)) {
  195. // mad cow disease mode, aka MBAFF + constrained_intra_pred
  196. mode = ALZHEIMER_DC_L0T_PRED8x8 +
  197. (!(h->left_samples_available & 0x8000)) +
  198. 2 * (mode == DC_128_PRED8x8);
  199. }
  200. if (mode < 0) {
  201. av_log(h->avctx, AV_LOG_ERROR,
  202. "left block unavailable for requested intra mode at %d %d\n",
  203. h->mb_x, h->mb_y);
  204. return AVERROR_INVALIDDATA;
  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) { \
  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. si = h->rbsp_buffer_size[bufidx];
  267. av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
  268. dst = h->rbsp_buffer[bufidx];
  269. if (dst == NULL)
  270. return NULL;
  271. if(i>=length-1){ //no escaped 0
  272. *dst_length= length;
  273. *consumed= length+1; //+1 for the header
  274. if(h->avctx->flags2 & CODEC_FLAG2_FAST){
  275. return src;
  276. }else{
  277. memcpy(dst, src, length);
  278. return dst;
  279. }
  280. }
  281. memcpy(dst, src, i);
  282. si = di = i;
  283. while (si + 2 < length) {
  284. // remove escapes (very rare 1:2^22)
  285. if (src[si + 2] > 3) {
  286. dst[di++] = src[si++];
  287. dst[di++] = src[si++];
  288. } else if (src[si] == 0 && src[si + 1] == 0) {
  289. if (src[si + 2] == 3) { // escape
  290. dst[di++] = 0;
  291. dst[di++] = 0;
  292. si += 3;
  293. continue;
  294. } else // next start code
  295. goto nsc;
  296. }
  297. dst[di++] = src[si++];
  298. }
  299. while (si < length)
  300. dst[di++] = src[si++];
  301. nsc:
  302. memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  303. *dst_length = di;
  304. *consumed = si + 1; // +1 for the header
  305. /* FIXME store exact number of bits in the getbitcontext
  306. * (it is needed for decoding) */
  307. return dst;
  308. }
  309. /**
  310. * Identify the exact end of the bitstream
  311. * @return the length of the trailing, or 0 if damaged
  312. */
  313. static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
  314. {
  315. int v = *src;
  316. int r;
  317. tprintf(h->avctx, "rbsp trailing %X\n", v);
  318. for (r = 1; r < 9; r++) {
  319. if (v & 1)
  320. return r;
  321. v >>= 1;
  322. }
  323. return 0;
  324. }
  325. void ff_h264_free_tables(H264Context *h, int free_rbsp)
  326. {
  327. int i;
  328. H264Context *hx;
  329. av_freep(&h->intra4x4_pred_mode);
  330. av_freep(&h->chroma_pred_mode_table);
  331. av_freep(&h->cbp_table);
  332. av_freep(&h->mvd_table[0]);
  333. av_freep(&h->mvd_table[1]);
  334. av_freep(&h->direct_table);
  335. av_freep(&h->non_zero_count);
  336. av_freep(&h->slice_table_base);
  337. h->slice_table = NULL;
  338. av_freep(&h->list_counts);
  339. av_freep(&h->mb2b_xy);
  340. av_freep(&h->mb2br_xy);
  341. av_buffer_pool_uninit(&h->qscale_table_pool);
  342. av_buffer_pool_uninit(&h->mb_type_pool);
  343. av_buffer_pool_uninit(&h->motion_val_pool);
  344. av_buffer_pool_uninit(&h->ref_index_pool);
  345. if (free_rbsp && h->DPB) {
  346. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  347. ff_h264_unref_picture(h, &h->DPB[i]);
  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_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_OR_GOTO(h->avctx, h->mvd_table[0],
  394. 16 * row_mb_num * sizeof(uint8_t), fail);
  395. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
  396. 16 * row_mb_num * 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. return AVERROR(ENOMEM);
  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_OR_GOTO(h->avctx, h->top_borders[0],
  443. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  444. FF_ALLOCZ_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. 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. return;
  727. switch (h->frame_packing_arrangement_type) {
  728. case 0:
  729. stereo->type = AV_STEREO3D_CHECKERBOARD;
  730. break;
  731. case 1:
  732. stereo->type = AV_STEREO3D_LINES;
  733. break;
  734. case 2:
  735. stereo->type = AV_STEREO3D_COLUMNS;
  736. break;
  737. case 3:
  738. if (h->quincunx_subsampling)
  739. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  740. else
  741. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  742. break;
  743. case 4:
  744. stereo->type = AV_STEREO3D_TOPBOTTOM;
  745. break;
  746. case 5:
  747. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  748. break;
  749. case 6:
  750. stereo->type = AV_STEREO3D_2D;
  751. break;
  752. }
  753. if (h->content_interpretation_type == 2)
  754. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  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. return;
  764. av_display_rotation_set((int32_t *)rotation->data, angle);
  765. av_display_matrix_flip((int32_t *)rotation->data,
  766. h->sei_vflip, h->sei_hflip);
  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. luma_def = 1 << h->luma_log2_weight_denom;
  864. chroma_def = 1 << h->chroma_log2_weight_denom;
  865. for (list = 0; list < 2; list++) {
  866. h->luma_weight_flag[list] = 0;
  867. h->chroma_weight_flag[list] = 0;
  868. for (i = 0; i < h->ref_count[list]; i++) {
  869. int luma_weight_flag, chroma_weight_flag;
  870. luma_weight_flag = get_bits1(&h->gb);
  871. if (luma_weight_flag) {
  872. h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
  873. h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
  874. if (h->luma_weight[i][list][0] != luma_def ||
  875. h->luma_weight[i][list][1] != 0) {
  876. h->use_weight = 1;
  877. h->luma_weight_flag[list] = 1;
  878. }
  879. } else {
  880. h->luma_weight[i][list][0] = luma_def;
  881. h->luma_weight[i][list][1] = 0;
  882. }
  883. if (h->sps.chroma_format_idc) {
  884. chroma_weight_flag = get_bits1(&h->gb);
  885. if (chroma_weight_flag) {
  886. int j;
  887. for (j = 0; j < 2; j++) {
  888. h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
  889. h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
  890. if (h->chroma_weight[i][list][j][0] != chroma_def ||
  891. h->chroma_weight[i][list][j][1] != 0) {
  892. h->use_weight_chroma = 1;
  893. h->chroma_weight_flag[list] = 1;
  894. }
  895. }
  896. } else {
  897. int j;
  898. for (j = 0; j < 2; j++) {
  899. h->chroma_weight[i][list][j][0] = chroma_def;
  900. h->chroma_weight[i][list][j][1] = 0;
  901. }
  902. }
  903. }
  904. }
  905. if (h->slice_type_nos != AV_PICTURE_TYPE_B)
  906. break;
  907. }
  908. h->use_weight = h->use_weight || h->use_weight_chroma;
  909. return 0;
  910. }
  911. /**
  912. * instantaneous decoder refresh.
  913. */
  914. static void idr(H264Context *h)
  915. {
  916. int i;
  917. ff_h264_remove_all_refs(h);
  918. h->prev_frame_num =
  919. h->prev_frame_num_offset = 0;
  920. h->prev_poc_msb = 1<<16;
  921. h->prev_poc_lsb = 0;
  922. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  923. h->last_pocs[i] = INT_MIN;
  924. }
  925. /* forget old pics after a seek */
  926. void ff_h264_flush_change(H264Context *h)
  927. {
  928. int i, j;
  929. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  930. h->prev_interlaced_frame = 1;
  931. idr(h);
  932. h->prev_frame_num = -1;
  933. if (h->cur_pic_ptr) {
  934. h->cur_pic_ptr->reference = 0;
  935. for (j=i=0; h->delayed_pic[i]; i++)
  936. if (h->delayed_pic[i] != h->cur_pic_ptr)
  937. h->delayed_pic[j++] = h->delayed_pic[i];
  938. h->delayed_pic[j] = NULL;
  939. }
  940. h->first_field = 0;
  941. memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
  942. memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
  943. memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
  944. memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
  945. ff_h264_reset_sei(h);
  946. h->recovery_frame = -1;
  947. h->frame_recovered = 0;
  948. h->list_count = 0;
  949. h->current_slice = 0;
  950. h->mmco_reset = 1;
  951. }
  952. /* forget old pics after a seek */
  953. static void flush_dpb(AVCodecContext *avctx)
  954. {
  955. H264Context *h = avctx->priv_data;
  956. int i;
  957. for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
  958. if (h->delayed_pic[i])
  959. h->delayed_pic[i]->reference = 0;
  960. h->delayed_pic[i] = NULL;
  961. }
  962. ff_h264_flush_change(h);
  963. if (h->DPB)
  964. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  965. ff_h264_unref_picture(h, &h->DPB[i]);
  966. h->cur_pic_ptr = NULL;
  967. ff_h264_unref_picture(h, &h->cur_pic);
  968. h->mb_x = h->mb_y = 0;
  969. h->parse_context.state = -1;
  970. h->parse_context.frame_start_found = 0;
  971. h->parse_context.overread = 0;
  972. h->parse_context.overread_index = 0;
  973. h->parse_context.index = 0;
  974. h->parse_context.last_index = 0;
  975. ff_h264_free_tables(h, 1);
  976. h->context_initialized = 0;
  977. }
  978. int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
  979. {
  980. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  981. int field_poc[2];
  982. h->frame_num_offset = h->prev_frame_num_offset;
  983. if (h->frame_num < h->prev_frame_num)
  984. h->frame_num_offset += max_frame_num;
  985. if (h->sps.poc_type == 0) {
  986. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  987. if (h->poc_lsb < h->prev_poc_lsb &&
  988. h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  989. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  990. else if (h->poc_lsb > h->prev_poc_lsb &&
  991. h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  992. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  993. else
  994. h->poc_msb = h->prev_poc_msb;
  995. field_poc[0] =
  996. field_poc[1] = h->poc_msb + h->poc_lsb;
  997. if (h->picture_structure == PICT_FRAME)
  998. field_poc[1] += h->delta_poc_bottom;
  999. } else if (h->sps.poc_type == 1) {
  1000. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  1001. int i;
  1002. if (h->sps.poc_cycle_length != 0)
  1003. abs_frame_num = h->frame_num_offset + h->frame_num;
  1004. else
  1005. abs_frame_num = 0;
  1006. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  1007. abs_frame_num--;
  1008. expected_delta_per_poc_cycle = 0;
  1009. for (i = 0; i < h->sps.poc_cycle_length; i++)
  1010. // FIXME integrate during sps parse
  1011. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  1012. if (abs_frame_num > 0) {
  1013. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  1014. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  1015. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1016. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  1017. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  1018. } else
  1019. expectedpoc = 0;
  1020. if (h->nal_ref_idc == 0)
  1021. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1022. field_poc[0] = expectedpoc + h->delta_poc[0];
  1023. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1024. if (h->picture_structure == PICT_FRAME)
  1025. field_poc[1] += h->delta_poc[1];
  1026. } else {
  1027. int poc = 2 * (h->frame_num_offset + h->frame_num);
  1028. if (!h->nal_ref_idc)
  1029. poc--;
  1030. field_poc[0] = poc;
  1031. field_poc[1] = poc;
  1032. }
  1033. if (h->picture_structure != PICT_BOTTOM_FIELD)
  1034. pic_field_poc[0] = field_poc[0];
  1035. if (h->picture_structure != PICT_TOP_FIELD)
  1036. pic_field_poc[1] = field_poc[1];
  1037. *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
  1038. return 0;
  1039. }
  1040. /**
  1041. * Compute profile from profile_idc and constraint_set?_flags.
  1042. *
  1043. * @param sps SPS
  1044. *
  1045. * @return profile as defined by FF_PROFILE_H264_*
  1046. */
  1047. int ff_h264_get_profile(SPS *sps)
  1048. {
  1049. int profile = sps->profile_idc;
  1050. switch (sps->profile_idc) {
  1051. case FF_PROFILE_H264_BASELINE:
  1052. // constraint_set1_flag set to 1
  1053. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  1054. break;
  1055. case FF_PROFILE_H264_HIGH_10:
  1056. case FF_PROFILE_H264_HIGH_422:
  1057. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  1058. // constraint_set3_flag set to 1
  1059. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  1060. break;
  1061. }
  1062. return profile;
  1063. }
  1064. int ff_h264_set_parameter_from_sps(H264Context *h)
  1065. {
  1066. if (h->flags & CODEC_FLAG_LOW_DELAY ||
  1067. (h->sps.bitstream_restriction_flag &&
  1068. !h->sps.num_reorder_frames)) {
  1069. if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
  1070. av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
  1071. "Reenabling low delay requires a codec flush.\n");
  1072. else
  1073. h->low_delay = 1;
  1074. }
  1075. if (h->avctx->has_b_frames < 2)
  1076. h->avctx->has_b_frames = !h->low_delay;
  1077. if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  1078. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  1079. if (h->avctx->codec &&
  1080. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
  1081. (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
  1082. av_log(h->avctx, AV_LOG_ERROR,
  1083. "VDPAU decoding does not support video colorspace.\n");
  1084. return AVERROR_INVALIDDATA;
  1085. }
  1086. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
  1087. h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
  1088. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  1089. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  1090. h->pixel_shift = h->sps.bit_depth_luma > 8;
  1091. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  1092. h->sps.chroma_format_idc);
  1093. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  1094. ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
  1095. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
  1096. h->sps.chroma_format_idc);
  1097. if (CONFIG_ERROR_RESILIENCE)
  1098. ff_me_cmp_init(&h->mecc, h->avctx);
  1099. ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
  1100. } else {
  1101. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
  1102. h->sps.bit_depth_luma);
  1103. return AVERROR_INVALIDDATA;
  1104. }
  1105. }
  1106. return 0;
  1107. }
  1108. int ff_set_ref_count(H264Context *h)
  1109. {
  1110. int ref_count[2], list_count;
  1111. int num_ref_idx_active_override_flag;
  1112. // set defaults, might be overridden a few lines later
  1113. ref_count[0] = h->pps.ref_count[0];
  1114. ref_count[1] = h->pps.ref_count[1];
  1115. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  1116. unsigned max[2];
  1117. max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
  1118. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  1119. h->direct_spatial_mv_pred = get_bits1(&h->gb);
  1120. num_ref_idx_active_override_flag = get_bits1(&h->gb);
  1121. if (num_ref_idx_active_override_flag) {
  1122. ref_count[0] = get_ue_golomb(&h->gb) + 1;
  1123. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  1124. ref_count[1] = get_ue_golomb(&h->gb) + 1;
  1125. } else
  1126. // full range is spec-ok in this case, even for frames
  1127. ref_count[1] = 1;
  1128. }
  1129. if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
  1130. 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]);
  1131. h->ref_count[0] = h->ref_count[1] = 0;
  1132. h->list_count = 0;
  1133. return AVERROR_INVALIDDATA;
  1134. }
  1135. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  1136. list_count = 2;
  1137. else
  1138. list_count = 1;
  1139. } else {
  1140. list_count = 0;
  1141. ref_count[0] = ref_count[1] = 0;
  1142. }
  1143. if (list_count != h->list_count ||
  1144. ref_count[0] != h->ref_count[0] ||
  1145. ref_count[1] != h->ref_count[1]) {
  1146. h->ref_count[0] = ref_count[0];
  1147. h->ref_count[1] = ref_count[1];
  1148. h->list_count = list_count;
  1149. return 1;
  1150. }
  1151. return 0;
  1152. }
  1153. static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
  1154. static int find_start_code(const uint8_t *buf, int buf_size,
  1155. int buf_index, int next_avc)
  1156. {
  1157. // start code prefix search
  1158. for (; buf_index + 3 < next_avc; buf_index++)
  1159. // This should always succeed in the first iteration.
  1160. if (buf[buf_index] == 0 &&
  1161. buf[buf_index + 1] == 0 &&
  1162. buf[buf_index + 2] == 1)
  1163. break;
  1164. buf_index += 3;
  1165. if (buf_index >= buf_size)
  1166. return buf_size;
  1167. return buf_index;
  1168. }
  1169. static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
  1170. int buf_size, int *buf_index)
  1171. {
  1172. int i, nalsize = 0;
  1173. if (*buf_index >= buf_size - h->nal_length_size)
  1174. return -1;
  1175. for (i = 0; i < h->nal_length_size; i++)
  1176. nalsize = (nalsize << 8) | buf[(*buf_index)++];
  1177. if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
  1178. av_log(h->avctx, AV_LOG_ERROR,
  1179. "AVC: nal size %d\n", nalsize);
  1180. return -1;
  1181. }
  1182. return nalsize;
  1183. }
  1184. static int get_bit_length(H264Context *h, const uint8_t *buf,
  1185. const uint8_t *ptr, int dst_length,
  1186. int i, int next_avc)
  1187. {
  1188. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  1189. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  1190. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  1191. h->workaround_bugs |= FF_BUG_TRUNCATED;
  1192. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  1193. while (dst_length > 0 && ptr[dst_length - 1] == 0)
  1194. dst_length--;
  1195. if (!dst_length)
  1196. return 0;
  1197. return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
  1198. }
  1199. static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
  1200. {
  1201. int next_avc = h->is_avc ? 0 : buf_size;
  1202. int nal_index = 0;
  1203. int buf_index = 0;
  1204. int nals_needed = 0;
  1205. int first_slice = 0;
  1206. while(1) {
  1207. int nalsize = 0;
  1208. int dst_length, bit_length, consumed;
  1209. const uint8_t *ptr;
  1210. if (buf_index >= next_avc) {
  1211. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1212. if (nalsize < 0)
  1213. break;
  1214. next_avc = buf_index + nalsize;
  1215. } else {
  1216. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1217. if (buf_index >= buf_size)
  1218. break;
  1219. if (buf_index >= next_avc)
  1220. continue;
  1221. }
  1222. ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
  1223. next_avc - buf_index);
  1224. if (ptr == NULL || dst_length < 0)
  1225. return AVERROR_INVALIDDATA;
  1226. buf_index += consumed;
  1227. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1228. buf_index, next_avc);
  1229. nal_index++;
  1230. /* packets can sometimes contain multiple PPS/SPS,
  1231. * e.g. two PAFF field pictures in one packet, or a demuxer
  1232. * which splits NALs strangely if so, when frame threading we
  1233. * can't start the next thread until we've read all of them */
  1234. switch (h->nal_unit_type) {
  1235. case NAL_SPS:
  1236. case NAL_PPS:
  1237. nals_needed = nal_index;
  1238. break;
  1239. case NAL_DPA:
  1240. case NAL_IDR_SLICE:
  1241. case NAL_SLICE:
  1242. init_get_bits(&h->gb, ptr, bit_length);
  1243. if (!get_ue_golomb(&h->gb) ||
  1244. !first_slice ||
  1245. first_slice != h->nal_unit_type)
  1246. nals_needed = nal_index;
  1247. if (!first_slice)
  1248. first_slice = h->nal_unit_type;
  1249. }
  1250. }
  1251. return nals_needed;
  1252. }
  1253. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  1254. int parse_extradata)
  1255. {
  1256. AVCodecContext *const avctx = h->avctx;
  1257. H264Context *hx; ///< thread context
  1258. int buf_index;
  1259. unsigned context_count;
  1260. int next_avc;
  1261. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  1262. int nal_index;
  1263. int idr_cleared=0;
  1264. int ret = 0;
  1265. h->nal_unit_type= 0;
  1266. if(!h->slice_context_count)
  1267. h->slice_context_count= 1;
  1268. h->max_contexts = h->slice_context_count;
  1269. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
  1270. h->current_slice = 0;
  1271. if (!h->first_field)
  1272. h->cur_pic_ptr = NULL;
  1273. ff_h264_reset_sei(h);
  1274. }
  1275. if (h->nal_length_size == 4) {
  1276. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  1277. h->is_avc = 0;
  1278. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  1279. h->is_avc = 1;
  1280. }
  1281. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1282. nals_needed = get_last_needed_nal(h, buf, buf_size);
  1283. {
  1284. buf_index = 0;
  1285. context_count = 0;
  1286. next_avc = h->is_avc ? 0 : buf_size;
  1287. nal_index = 0;
  1288. for (;;) {
  1289. int consumed;
  1290. int dst_length;
  1291. int bit_length;
  1292. const uint8_t *ptr;
  1293. int nalsize = 0;
  1294. int err;
  1295. if (buf_index >= next_avc) {
  1296. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1297. if (nalsize < 0)
  1298. break;
  1299. next_avc = buf_index + nalsize;
  1300. } else {
  1301. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1302. if (buf_index >= buf_size)
  1303. break;
  1304. if (buf_index >= next_avc)
  1305. continue;
  1306. }
  1307. hx = h->thread_context[context_count];
  1308. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  1309. &consumed, next_avc - buf_index);
  1310. if (ptr == NULL || dst_length < 0) {
  1311. ret = -1;
  1312. goto end;
  1313. }
  1314. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1315. buf_index + consumed, next_avc);
  1316. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  1317. av_log(h->avctx, AV_LOG_DEBUG,
  1318. "NAL %d/%d at %d/%d length %d\n",
  1319. hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length);
  1320. if (h->is_avc && (nalsize != consumed) && nalsize)
  1321. av_log(h->avctx, AV_LOG_DEBUG,
  1322. "AVC: Consumed only %d bytes instead of %d\n",
  1323. consumed, nalsize);
  1324. buf_index += consumed;
  1325. nal_index++;
  1326. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  1327. h->nal_ref_idc == 0 &&
  1328. h->nal_unit_type != NAL_SEI)
  1329. continue;
  1330. again:
  1331. if ( !(avctx->active_thread_type & FF_THREAD_FRAME)
  1332. || nals_needed >= nal_index)
  1333. h->au_pps_id = -1;
  1334. /* Ignore per frame NAL unit type during extradata
  1335. * parsing. Decoding slices is not possible in codec init
  1336. * with frame-mt */
  1337. if (parse_extradata) {
  1338. switch (hx->nal_unit_type) {
  1339. case NAL_IDR_SLICE:
  1340. case NAL_SLICE:
  1341. case NAL_DPA:
  1342. case NAL_DPB:
  1343. case NAL_DPC:
  1344. av_log(h->avctx, AV_LOG_WARNING,
  1345. "Ignoring NAL %d in global header/extradata\n",
  1346. hx->nal_unit_type);
  1347. // fall through to next case
  1348. case NAL_AUXILIARY_SLICE:
  1349. hx->nal_unit_type = NAL_FF_IGNORE;
  1350. }
  1351. }
  1352. err = 0;
  1353. switch (hx->nal_unit_type) {
  1354. case NAL_IDR_SLICE:
  1355. if (h->nal_unit_type != NAL_IDR_SLICE) {
  1356. av_log(h->avctx, AV_LOG_ERROR,
  1357. "Invalid mix of idr and non-idr slices\n");
  1358. ret = -1;
  1359. goto end;
  1360. }
  1361. if(!idr_cleared)
  1362. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  1363. idr_cleared = 1;
  1364. h->has_recovery_point = 1;
  1365. case NAL_SLICE:
  1366. init_get_bits(&hx->gb, ptr, bit_length);
  1367. hx->intra_gb_ptr =
  1368. hx->inter_gb_ptr = &hx->gb;
  1369. hx->data_partitioning = 0;
  1370. if ((err = ff_h264_decode_slice_header(hx, h)))
  1371. break;
  1372. if (h->sei_recovery_frame_cnt >= 0) {
  1373. if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
  1374. h->valid_recovery_point = 1;
  1375. if ( h->recovery_frame < 0
  1376. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
  1377. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
  1378. ((1 << h->sps.log2_max_frame_num) - 1);
  1379. if (!h->valid_recovery_point)
  1380. h->recovery_frame = h->frame_num;
  1381. }
  1382. }
  1383. h->cur_pic_ptr->f.key_frame |=
  1384. (hx->nal_unit_type == NAL_IDR_SLICE);
  1385. if (hx->nal_unit_type == NAL_IDR_SLICE ||
  1386. h->recovery_frame == h->frame_num) {
  1387. h->recovery_frame = -1;
  1388. h->cur_pic_ptr->recovered = 1;
  1389. }
  1390. // If we have an IDR, all frames after it in decoded order are
  1391. // "recovered".
  1392. if (hx->nal_unit_type == NAL_IDR_SLICE)
  1393. h->frame_recovered |= FRAME_RECOVERED_IDR;
  1394. h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
  1395. h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
  1396. #if 1
  1397. h->cur_pic_ptr->recovered |= h->frame_recovered;
  1398. #else
  1399. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  1400. #endif
  1401. if (h->current_slice == 1) {
  1402. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
  1403. decode_postinit(h, nal_index >= nals_needed);
  1404. if (h->avctx->hwaccel &&
  1405. (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
  1406. return ret;
  1407. if (CONFIG_H264_VDPAU_DECODER &&
  1408. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  1409. ff_vdpau_h264_picture_start(h);
  1410. }
  1411. if (hx->redundant_pic_count == 0) {
  1412. if (avctx->hwaccel) {
  1413. ret = avctx->hwaccel->decode_slice(avctx,
  1414. &buf[buf_index - consumed],
  1415. consumed);
  1416. if (ret < 0)
  1417. return ret;
  1418. } else if (CONFIG_H264_VDPAU_DECODER &&
  1419. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  1420. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
  1421. start_code,
  1422. sizeof(start_code));
  1423. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
  1424. &buf[buf_index - consumed],
  1425. consumed);
  1426. } else
  1427. context_count++;
  1428. }
  1429. break;
  1430. case NAL_DPA:
  1431. if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
  1432. av_log(h->avctx, AV_LOG_ERROR,
  1433. "Decoding in chunks is not supported for "
  1434. "partitioned slices.\n");
  1435. return AVERROR(ENOSYS);
  1436. }
  1437. init_get_bits(&hx->gb, ptr, bit_length);
  1438. hx->intra_gb_ptr =
  1439. hx->inter_gb_ptr = NULL;
  1440. if ((err = ff_h264_decode_slice_header(hx, h))) {
  1441. /* make sure data_partitioning is cleared if it was set
  1442. * before, so we don't try decoding a slice without a valid
  1443. * slice header later */
  1444. h->data_partitioning = 0;
  1445. break;
  1446. }
  1447. hx->data_partitioning = 1;
  1448. break;
  1449. case NAL_DPB:
  1450. init_get_bits(&hx->intra_gb, ptr, bit_length);
  1451. hx->intra_gb_ptr = &hx->intra_gb;
  1452. break;
  1453. case NAL_DPC:
  1454. init_get_bits(&hx->inter_gb, ptr, bit_length);
  1455. hx->inter_gb_ptr = &hx->inter_gb;
  1456. av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
  1457. break;
  1458. if (hx->redundant_pic_count == 0 &&
  1459. hx->intra_gb_ptr &&
  1460. hx->data_partitioning &&
  1461. h->cur_pic_ptr && h->context_initialized &&
  1462. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  1463. (avctx->skip_frame < AVDISCARD_BIDIR ||
  1464. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  1465. (avctx->skip_frame < AVDISCARD_NONINTRA ||
  1466. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  1467. avctx->skip_frame < AVDISCARD_ALL)
  1468. context_count++;
  1469. break;
  1470. case NAL_SEI:
  1471. init_get_bits(&h->gb, ptr, bit_length);
  1472. ret = ff_h264_decode_sei(h);
  1473. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1474. goto end;
  1475. break;
  1476. case NAL_SPS:
  1477. init_get_bits(&h->gb, ptr, bit_length);
  1478. if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
  1479. av_log(h->avctx, AV_LOG_DEBUG,
  1480. "SPS decoding failure, trying again with the complete NAL\n");
  1481. if (h->is_avc)
  1482. av_assert0(next_avc - buf_index + consumed == nalsize);
  1483. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  1484. break;
  1485. init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
  1486. 8*(next_avc - buf_index + consumed - 1));
  1487. ff_h264_decode_seq_parameter_set(h);
  1488. }
  1489. break;
  1490. case NAL_PPS:
  1491. init_get_bits(&h->gb, ptr, bit_length);
  1492. ret = ff_h264_decode_picture_parameter_set(h, bit_length);
  1493. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1494. goto end;
  1495. break;
  1496. case NAL_AUD:
  1497. case NAL_END_SEQUENCE:
  1498. case NAL_END_STREAM:
  1499. case NAL_FILLER_DATA:
  1500. case NAL_SPS_EXT:
  1501. case NAL_AUXILIARY_SLICE:
  1502. break;
  1503. case NAL_FF_IGNORE:
  1504. break;
  1505. default:
  1506. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  1507. hx->nal_unit_type, bit_length);
  1508. }
  1509. if (context_count == h->max_contexts) {
  1510. ret = ff_h264_execute_decode_slices(h, context_count);
  1511. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1512. goto end;
  1513. context_count = 0;
  1514. }
  1515. if (err < 0 || err == SLICE_SKIPED) {
  1516. if (err < 0)
  1517. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  1518. h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
  1519. } else if (err == SLICE_SINGLETHREAD) {
  1520. /* Slice could not be decoded in parallel mode, copy down
  1521. * NAL unit stuff to context 0 and restart. Note that
  1522. * rbsp_buffer is not transferred, but since we no longer
  1523. * run in parallel mode this should not be an issue. */
  1524. h->nal_unit_type = hx->nal_unit_type;
  1525. h->nal_ref_idc = hx->nal_ref_idc;
  1526. hx = h;
  1527. goto again;
  1528. }
  1529. }
  1530. }
  1531. if (context_count) {
  1532. ret = ff_h264_execute_decode_slices(h, context_count);
  1533. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1534. goto end;
  1535. }
  1536. ret = 0;
  1537. end:
  1538. /* clean up */
  1539. if (h->cur_pic_ptr && !h->droppable) {
  1540. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1541. h->picture_structure == PICT_BOTTOM_FIELD);
  1542. }
  1543. return (ret < 0) ? ret : buf_index;
  1544. }
  1545. /**
  1546. * Return the number of bytes consumed for building the current frame.
  1547. */
  1548. static int get_consumed_bytes(int pos, int buf_size)
  1549. {
  1550. if (pos == 0)
  1551. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  1552. if (pos + 10 > buf_size)
  1553. pos = buf_size; // oops ;)
  1554. return pos;
  1555. }
  1556. static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
  1557. {
  1558. AVFrame *src = &srcp->f;
  1559. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
  1560. int i;
  1561. int ret = av_frame_ref(dst, src);
  1562. if (ret < 0)
  1563. return ret;
  1564. av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
  1565. if (srcp->sei_recovery_frame_cnt == 0)
  1566. dst->key_frame = 1;
  1567. if (!srcp->crop)
  1568. return 0;
  1569. for (i = 0; i < desc->nb_components; i++) {
  1570. int hshift = (i > 0) ? desc->log2_chroma_w : 0;
  1571. int vshift = (i > 0) ? desc->log2_chroma_h : 0;
  1572. int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
  1573. (srcp->crop_top >> vshift) * dst->linesize[i];
  1574. dst->data[i] += off;
  1575. }
  1576. return 0;
  1577. }
  1578. static int is_extra(const uint8_t *buf, int buf_size)
  1579. {
  1580. int cnt= buf[5]&0x1f;
  1581. const uint8_t *p= buf+6;
  1582. while(cnt--){
  1583. int nalsize= AV_RB16(p) + 2;
  1584. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  1585. return 0;
  1586. p += nalsize;
  1587. }
  1588. cnt = *(p++);
  1589. if(!cnt)
  1590. return 0;
  1591. while(cnt--){
  1592. int nalsize= AV_RB16(p) + 2;
  1593. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  1594. return 0;
  1595. p += nalsize;
  1596. }
  1597. return 1;
  1598. }
  1599. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  1600. int *got_frame, AVPacket *avpkt)
  1601. {
  1602. const uint8_t *buf = avpkt->data;
  1603. int buf_size = avpkt->size;
  1604. H264Context *h = avctx->priv_data;
  1605. AVFrame *pict = data;
  1606. int buf_index = 0;
  1607. H264Picture *out;
  1608. int i, out_idx;
  1609. int ret;
  1610. h->flags = avctx->flags;
  1611. /* reset data partitioning here, to ensure GetBitContexts from previous
  1612. * packets do not get used. */
  1613. h->data_partitioning = 0;
  1614. /* end of stream, output what is still in the buffers */
  1615. if (buf_size == 0) {
  1616. out:
  1617. h->cur_pic_ptr = NULL;
  1618. h->first_field = 0;
  1619. // FIXME factorize this with the output code below
  1620. out = h->delayed_pic[0];
  1621. out_idx = 0;
  1622. for (i = 1;
  1623. h->delayed_pic[i] &&
  1624. !h->delayed_pic[i]->f.key_frame &&
  1625. !h->delayed_pic[i]->mmco_reset;
  1626. i++)
  1627. if (h->delayed_pic[i]->poc < out->poc) {
  1628. out = h->delayed_pic[i];
  1629. out_idx = i;
  1630. }
  1631. for (i = out_idx; h->delayed_pic[i]; i++)
  1632. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1633. if (out) {
  1634. out->reference &= ~DELAYED_PIC_REF;
  1635. ret = output_frame(h, pict, out);
  1636. if (ret < 0)
  1637. return ret;
  1638. *got_frame = 1;
  1639. }
  1640. return buf_index;
  1641. }
  1642. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  1643. if (is_extra(buf, buf_size))
  1644. return ff_h264_decode_extradata(h, buf, buf_size);
  1645. }
  1646. buf_index = decode_nal_units(h, buf, buf_size, 0);
  1647. if (buf_index < 0)
  1648. return AVERROR_INVALIDDATA;
  1649. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  1650. av_assert0(buf_index <= buf_size);
  1651. goto out;
  1652. }
  1653. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  1654. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  1655. buf_size >= 4 && !memcmp("Q264", buf, 4))
  1656. return buf_size;
  1657. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  1658. return AVERROR_INVALIDDATA;
  1659. }
  1660. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
  1661. (h->mb_y >= h->mb_height && h->mb_height)) {
  1662. if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
  1663. decode_postinit(h, 1);
  1664. ff_h264_field_end(h, 0);
  1665. /* Wait for second field. */
  1666. *got_frame = 0;
  1667. if (h->next_output_pic && (
  1668. h->next_output_pic->recovered)) {
  1669. if (!h->next_output_pic->recovered)
  1670. h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
  1671. ret = output_frame(h, pict, h->next_output_pic);
  1672. if (ret < 0)
  1673. return ret;
  1674. *got_frame = 1;
  1675. if (CONFIG_MPEGVIDEO) {
  1676. ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table,
  1677. h->next_output_pic->mb_type,
  1678. h->next_output_pic->qscale_table,
  1679. h->next_output_pic->motion_val,
  1680. &h->low_delay,
  1681. h->mb_width, h->mb_height, h->mb_stride, 1);
  1682. }
  1683. }
  1684. }
  1685. assert(pict->buf[0] || !*got_frame);
  1686. return get_consumed_bytes(buf_index, buf_size);
  1687. }
  1688. av_cold void ff_h264_free_context(H264Context *h)
  1689. {
  1690. int i;
  1691. ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
  1692. for (i = 0; i < MAX_SPS_COUNT; i++)
  1693. av_freep(h->sps_buffers + i);
  1694. for (i = 0; i < MAX_PPS_COUNT; i++)
  1695. av_freep(h->pps_buffers + i);
  1696. }
  1697. static av_cold int h264_decode_end(AVCodecContext *avctx)
  1698. {
  1699. H264Context *h = avctx->priv_data;
  1700. ff_h264_remove_all_refs(h);
  1701. ff_h264_free_context(h);
  1702. ff_h264_unref_picture(h, &h->cur_pic);
  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. static const AVClass h264_vdpau_class = {
  1733. .class_name = "H264 VDPAU Decoder",
  1734. .item_name = av_default_item_name,
  1735. .option = h264_options,
  1736. .version = LIBAVUTIL_VERSION_INT,
  1737. };
  1738. AVCodec ff_h264_decoder = {
  1739. .name = "h264",
  1740. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  1741. .type = AVMEDIA_TYPE_VIDEO,
  1742. .id = AV_CODEC_ID_H264,
  1743. .priv_data_size = sizeof(H264Context),
  1744. .init = ff_h264_decode_init,
  1745. .close = h264_decode_end,
  1746. .decode = h264_decode_frame,
  1747. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  1748. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  1749. CODEC_CAP_FRAME_THREADS,
  1750. .flush = flush_dpb,
  1751. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1752. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  1753. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  1754. .priv_class = &h264_class,
  1755. };
  1756. #if CONFIG_H264_VDPAU_DECODER
  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