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.

4898 lines
184KB

  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/imgutils.h"
  28. #include "libavutil/opt.h"
  29. #include "internal.h"
  30. #include "cabac.h"
  31. #include "cabac_functions.h"
  32. #include "dsputil.h"
  33. #include "avcodec.h"
  34. #include "mpegvideo.h"
  35. #include "h264.h"
  36. #include "h264data.h"
  37. #include "h264chroma.h"
  38. #include "h264_mvpred.h"
  39. #include "golomb.h"
  40. #include "mathops.h"
  41. #include "rectangle.h"
  42. #include "svq3.h"
  43. #include "thread.h"
  44. #include "vdpau_internal.h"
  45. #include "libavutil/avassert.h"
  46. // #undef NDEBUG
  47. #include <assert.h>
  48. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  49. static const uint8_t rem6[QP_MAX_NUM + 1] = {
  50. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
  51. 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
  52. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
  53. 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
  54. 0, 1, 2, 3,
  55. };
  56. static const uint8_t div6[QP_MAX_NUM + 1] = {
  57. 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
  58. 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
  59. 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
  60. 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
  61. 14,14,14,14,
  62. };
  63. static const enum AVPixelFormat hwaccel_pixfmt_list_h264_420[] = {
  64. #if CONFIG_H264_DXVA2_HWACCEL
  65. AV_PIX_FMT_DXVA2_VLD,
  66. #endif
  67. #if CONFIG_H264_VAAPI_HWACCEL
  68. AV_PIX_FMT_VAAPI_VLD,
  69. #endif
  70. #if CONFIG_H264_VDA_HWACCEL
  71. AV_PIX_FMT_VDA_VLD,
  72. #endif
  73. #if CONFIG_H264_VDPAU_HWACCEL
  74. AV_PIX_FMT_VDPAU,
  75. #endif
  76. AV_PIX_FMT_YUV420P,
  77. AV_PIX_FMT_NONE
  78. };
  79. static const enum AVPixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
  80. #if CONFIG_H264_DXVA2_HWACCEL
  81. AV_PIX_FMT_DXVA2_VLD,
  82. #endif
  83. #if CONFIG_H264_VAAPI_HWACCEL
  84. AV_PIX_FMT_VAAPI_VLD,
  85. #endif
  86. #if CONFIG_H264_VDA_HWACCEL
  87. AV_PIX_FMT_VDA_VLD,
  88. #endif
  89. #if CONFIG_H264_VDPAU_HWACCEL
  90. AV_PIX_FMT_VDPAU,
  91. #endif
  92. AV_PIX_FMT_YUVJ420P,
  93. AV_PIX_FMT_NONE
  94. };
  95. int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
  96. {
  97. H264Context *h = avctx->priv_data;
  98. return h ? h->sps.num_reorder_frames : 0;
  99. }
  100. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  101. int (*mv)[2][4][2],
  102. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  103. {
  104. H264Context *h = opaque;
  105. h->mb_x = mb_x;
  106. h->mb_y = mb_y;
  107. h->mb_xy = mb_x + mb_y * h->mb_stride;
  108. memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
  109. av_assert1(ref >= 0);
  110. /* FIXME: It is possible albeit uncommon that slice references
  111. * differ between slices. We take the easy approach and ignore
  112. * it for now. If this turns out to have any relevance in
  113. * practice then correct remapping should be added. */
  114. if (ref >= h->ref_count[0])
  115. ref = 0;
  116. if (!h->ref_list[0][ref].f.data[0]) {
  117. av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
  118. ref = 0;
  119. }
  120. if ((h->ref_list[0][ref].f.reference&3) != 3) {
  121. av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
  122. return;
  123. }
  124. fill_rectangle(&h->cur_pic.f.ref_index[0][4 * h->mb_xy],
  125. 2, 2, 2, ref, 1);
  126. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  127. fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
  128. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  129. h->mb_mbaff =
  130. h->mb_field_decoding_flag = 0;
  131. ff_h264_hl_decode_mb(h);
  132. }
  133. void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
  134. {
  135. ff_draw_horiz_band(h->avctx, NULL, &h->cur_pic,
  136. h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL,
  137. y, height, h->picture_structure, h->first_field, 0,
  138. h->low_delay, h->mb_height * 16, h->mb_width * 16);
  139. }
  140. static void free_frame_buffer(H264Context *h, Picture *pic)
  141. {
  142. pic->period_since_free = 0;
  143. ff_thread_release_buffer(h->avctx, &pic->f);
  144. av_freep(&pic->f.hwaccel_picture_private);
  145. }
  146. static void free_picture(H264Context *h, Picture *pic)
  147. {
  148. int i;
  149. if (pic->f.data[0])
  150. free_frame_buffer(h, pic);
  151. av_freep(&pic->qscale_table_base);
  152. pic->f.qscale_table = NULL;
  153. av_freep(&pic->mb_type_base);
  154. pic->f.mb_type = NULL;
  155. for (i = 0; i < 2; i++) {
  156. av_freep(&pic->motion_val_base[i]);
  157. av_freep(&pic->f.ref_index[i]);
  158. pic->f.motion_val[i] = NULL;
  159. }
  160. }
  161. static void release_unused_pictures(H264Context *h, int remove_current)
  162. {
  163. int i;
  164. /* release non reference frames */
  165. for (i = 0; i < h->picture_count; i++) {
  166. if (h->DPB[i].f.data[0] && !h->DPB[i].f.reference &&
  167. (!h->DPB[i].owner2 || h->DPB[i].owner2 == h) &&
  168. (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
  169. free_frame_buffer(h, &h->DPB[i]);
  170. }
  171. }
  172. }
  173. static int alloc_scratch_buffers(H264Context *h, int linesize)
  174. {
  175. int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
  176. if (h->bipred_scratchpad)
  177. return 0;
  178. h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
  179. // edge emu needs blocksize + filter length - 1
  180. // (= 21x21 for h264)
  181. h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
  182. h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
  183. if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
  184. av_freep(&h->bipred_scratchpad);
  185. av_freep(&h->edge_emu_buffer);
  186. av_freep(&h->me.scratchpad);
  187. return AVERROR(ENOMEM);
  188. }
  189. h->me.temp = h->me.scratchpad;
  190. return 0;
  191. }
  192. static int alloc_picture(H264Context *h, Picture *pic)
  193. {
  194. const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
  195. const int mb_array_size = h->mb_stride * h->mb_height;
  196. const int b4_stride = h->mb_width * 4 + 1;
  197. const int b4_array_size = b4_stride * h->mb_height * 4;
  198. int i, ret = 0;
  199. av_assert0(!pic->f.data[0]);
  200. if (h->avctx->hwaccel) {
  201. const AVHWAccel *hwaccel = h->avctx->hwaccel;
  202. av_assert0(!pic->f.hwaccel_picture_private);
  203. if (hwaccel->priv_data_size) {
  204. pic->f.hwaccel_picture_private = av_mallocz(hwaccel->priv_data_size);
  205. if (!pic->f.hwaccel_picture_private)
  206. return AVERROR(ENOMEM);
  207. }
  208. }
  209. ret = ff_thread_get_buffer(h->avctx, &pic->f);
  210. if (ret < 0)
  211. goto fail;
  212. h->linesize = pic->f.linesize[0];
  213. h->uvlinesize = pic->f.linesize[1];
  214. if (pic->f.qscale_table == NULL) {
  215. FF_ALLOCZ_OR_GOTO(h->avctx, pic->qscale_table_base,
  216. (big_mb_num + h->mb_stride) * sizeof(uint8_t),
  217. fail)
  218. FF_ALLOCZ_OR_GOTO(h->avctx, pic->mb_type_base,
  219. (big_mb_num + h->mb_stride) * sizeof(uint32_t),
  220. fail)
  221. pic->f.mb_type = pic->mb_type_base + 2 * h->mb_stride + 1;
  222. pic->f.qscale_table = pic->qscale_table_base + 2 * h->mb_stride + 1;
  223. for (i = 0; i < 2; i++) {
  224. FF_ALLOCZ_OR_GOTO(h->avctx, pic->motion_val_base[i],
  225. 2 * (b4_array_size + 4) * sizeof(int16_t),
  226. fail)
  227. pic->f.motion_val[i] = pic->motion_val_base[i] + 4;
  228. FF_ALLOCZ_OR_GOTO(h->avctx, pic->f.ref_index[i],
  229. 4 * mb_array_size * sizeof(uint8_t), fail)
  230. }
  231. pic->f.motion_subsample_log2 = 2;
  232. pic->f.qstride = h->mb_stride;
  233. }
  234. pic->owner2 = h;
  235. return 0;
  236. fail:
  237. free_frame_buffer(h, pic);
  238. return (ret < 0) ? ret : AVERROR(ENOMEM);
  239. }
  240. static inline int pic_is_unused(H264Context *h, Picture *pic)
  241. {
  242. if ( (h->avctx->active_thread_type & FF_THREAD_FRAME)
  243. && pic->f.qscale_table //check if the frame has anything allocated
  244. && pic->period_since_free < h->avctx->thread_count)
  245. return 0;
  246. if (pic->f.data[0] == NULL)
  247. return 1;
  248. if (pic->needs_realloc && !(pic->f.reference & DELAYED_PIC_REF))
  249. if (!pic->owner2 || pic->owner2 == h)
  250. return 1;
  251. return 0;
  252. }
  253. static int find_unused_picture(H264Context *h)
  254. {
  255. int i;
  256. for (i = h->picture_range_start; i < h->picture_range_end; i++) {
  257. if (pic_is_unused(h, &h->DPB[i]))
  258. break;
  259. }
  260. if (i == h->picture_range_end)
  261. return AVERROR_INVALIDDATA;
  262. if (h->DPB[i].needs_realloc) {
  263. h->DPB[i].needs_realloc = 0;
  264. free_picture(h, &h->DPB[i]);
  265. avcodec_get_frame_defaults(&h->DPB[i].f);
  266. }
  267. return i;
  268. }
  269. /**
  270. * Check if the top & left blocks are available if needed and
  271. * change the dc mode so it only uses the available blocks.
  272. */
  273. int ff_h264_check_intra4x4_pred_mode(H264Context *h)
  274. {
  275. static const int8_t top[12] = {
  276. -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
  277. };
  278. static const int8_t left[12] = {
  279. 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
  280. };
  281. int i;
  282. if (!(h->top_samples_available & 0x8000)) {
  283. for (i = 0; i < 4; i++) {
  284. int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
  285. if (status < 0) {
  286. av_log(h->avctx, AV_LOG_ERROR,
  287. "top block unavailable for requested intra4x4 mode %d at %d %d\n",
  288. status, h->mb_x, h->mb_y);
  289. return -1;
  290. } else if (status) {
  291. h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
  292. }
  293. }
  294. }
  295. if ((h->left_samples_available & 0x8888) != 0x8888) {
  296. static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
  297. for (i = 0; i < 4; i++)
  298. if (!(h->left_samples_available & mask[i])) {
  299. int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
  300. if (status < 0) {
  301. av_log(h->avctx, AV_LOG_ERROR,
  302. "left block unavailable for requested intra4x4 mode %d at %d %d\n",
  303. status, h->mb_x, h->mb_y);
  304. return -1;
  305. } else if (status) {
  306. h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
  307. }
  308. }
  309. }
  310. return 0;
  311. } // FIXME cleanup like ff_h264_check_intra_pred_mode
  312. /**
  313. * Check if the top & left blocks are available if needed and
  314. * change the dc mode so it only uses the available blocks.
  315. */
  316. int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
  317. {
  318. static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
  319. static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
  320. if (mode > 6U) {
  321. av_log(h->avctx, AV_LOG_ERROR,
  322. "out of range intra chroma pred mode at %d %d\n",
  323. h->mb_x, h->mb_y);
  324. return -1;
  325. }
  326. if (!(h->top_samples_available & 0x8000)) {
  327. mode = top[mode];
  328. if (mode < 0) {
  329. av_log(h->avctx, AV_LOG_ERROR,
  330. "top block unavailable for requested intra mode at %d %d\n",
  331. h->mb_x, h->mb_y);
  332. return -1;
  333. }
  334. }
  335. if ((h->left_samples_available & 0x8080) != 0x8080) {
  336. mode = left[mode];
  337. if (is_chroma && (h->left_samples_available & 0x8080)) {
  338. // mad cow disease mode, aka MBAFF + constrained_intra_pred
  339. mode = ALZHEIMER_DC_L0T_PRED8x8 +
  340. (!(h->left_samples_available & 0x8000)) +
  341. 2 * (mode == DC_128_PRED8x8);
  342. }
  343. if (mode < 0) {
  344. av_log(h->avctx, AV_LOG_ERROR,
  345. "left block unavailable for requested intra mode at %d %d\n",
  346. h->mb_x, h->mb_y);
  347. return -1;
  348. }
  349. }
  350. return mode;
  351. }
  352. const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
  353. int *dst_length, int *consumed, int length)
  354. {
  355. int i, si, di;
  356. uint8_t *dst;
  357. int bufidx;
  358. // src[0]&0x80; // forbidden bit
  359. h->nal_ref_idc = src[0] >> 5;
  360. h->nal_unit_type = src[0] & 0x1F;
  361. src++;
  362. length--;
  363. #define STARTCODE_TEST \
  364. if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
  365. if (src[i + 2] != 3) { \
  366. /* startcode, so we must be past the end */ \
  367. length = i; \
  368. } \
  369. break; \
  370. }
  371. #if HAVE_FAST_UNALIGNED
  372. #define FIND_FIRST_ZERO \
  373. if (i > 0 && !src[i]) \
  374. i--; \
  375. while (src[i]) \
  376. i++
  377. #if HAVE_FAST_64BIT
  378. for (i = 0; i + 1 < length; i += 9) {
  379. if (!((~AV_RN64A(src + i) &
  380. (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
  381. 0x8000800080008080ULL))
  382. continue;
  383. FIND_FIRST_ZERO;
  384. STARTCODE_TEST;
  385. i -= 7;
  386. }
  387. #else
  388. for (i = 0; i + 1 < length; i += 5) {
  389. if (!((~AV_RN32A(src + i) &
  390. (AV_RN32A(src + i) - 0x01000101U)) &
  391. 0x80008080U))
  392. continue;
  393. FIND_FIRST_ZERO;
  394. STARTCODE_TEST;
  395. i -= 3;
  396. }
  397. #endif
  398. #else
  399. for (i = 0; i + 1 < length; i += 2) {
  400. if (src[i])
  401. continue;
  402. if (i > 0 && src[i - 1] == 0)
  403. i--;
  404. STARTCODE_TEST;
  405. }
  406. #endif
  407. // use second escape buffer for inter data
  408. bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
  409. si = h->rbsp_buffer_size[bufidx];
  410. av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
  411. dst = h->rbsp_buffer[bufidx];
  412. if (dst == NULL)
  413. return NULL;
  414. if(i>=length-1){ //no escaped 0
  415. *dst_length= length;
  416. *consumed= length+1; //+1 for the header
  417. if(h->avctx->flags2 & CODEC_FLAG2_FAST){
  418. return src;
  419. }else{
  420. memcpy(dst, src, length);
  421. return dst;
  422. }
  423. }
  424. memcpy(dst, src, i);
  425. si = di = i;
  426. while (si + 2 < length) {
  427. // remove escapes (very rare 1:2^22)
  428. if (src[si + 2] > 3) {
  429. dst[di++] = src[si++];
  430. dst[di++] = src[si++];
  431. } else if (src[si] == 0 && src[si + 1] == 0) {
  432. if (src[si + 2] == 3) { // escape
  433. dst[di++] = 0;
  434. dst[di++] = 0;
  435. si += 3;
  436. continue;
  437. } else // next start code
  438. goto nsc;
  439. }
  440. dst[di++] = src[si++];
  441. }
  442. while (si < length)
  443. dst[di++] = src[si++];
  444. nsc:
  445. memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  446. *dst_length = di;
  447. *consumed = si + 1; // +1 for the header
  448. /* FIXME store exact number of bits in the getbitcontext
  449. * (it is needed for decoding) */
  450. return dst;
  451. }
  452. /**
  453. * Identify the exact end of the bitstream
  454. * @return the length of the trailing, or 0 if damaged
  455. */
  456. static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
  457. {
  458. int v = *src;
  459. int r;
  460. tprintf(h->avctx, "rbsp trailing %X\n", v);
  461. for (r = 1; r < 9; r++) {
  462. if (v & 1)
  463. return r;
  464. v >>= 1;
  465. }
  466. return 0;
  467. }
  468. static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
  469. int height, int y_offset, int list)
  470. {
  471. int raw_my = h->mv_cache[list][scan8[n]][1];
  472. int filter_height_down = (raw_my & 3) ? 3 : 0;
  473. int full_my = (raw_my >> 2) + y_offset;
  474. int bottom = full_my + filter_height_down + height;
  475. av_assert2(height >= 0);
  476. return FFMAX(0, bottom);
  477. }
  478. static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
  479. int height, int y_offset, int list0,
  480. int list1, int *nrefs)
  481. {
  482. int my;
  483. y_offset += 16 * (h->mb_y >> MB_FIELD);
  484. if (list0) {
  485. int ref_n = h->ref_cache[0][scan8[n]];
  486. Picture *ref = &h->ref_list[0][ref_n];
  487. // Error resilience puts the current picture in the ref list.
  488. // Don't try to wait on these as it will cause a deadlock.
  489. // Fields can wait on each other, though.
  490. if (ref->f.thread_opaque != h->cur_pic.f.thread_opaque ||
  491. (ref->f.reference & 3) != h->picture_structure) {
  492. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
  493. if (refs[0][ref_n] < 0)
  494. nrefs[0] += 1;
  495. refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
  496. }
  497. }
  498. if (list1) {
  499. int ref_n = h->ref_cache[1][scan8[n]];
  500. Picture *ref = &h->ref_list[1][ref_n];
  501. if (ref->f.thread_opaque != h->cur_pic.f.thread_opaque ||
  502. (ref->f.reference & 3) != h->picture_structure) {
  503. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
  504. if (refs[1][ref_n] < 0)
  505. nrefs[1] += 1;
  506. refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
  507. }
  508. }
  509. }
  510. /**
  511. * Wait until all reference frames are available for MC operations.
  512. *
  513. * @param h the H264 context
  514. */
  515. static void await_references(H264Context *h)
  516. {
  517. const int mb_xy = h->mb_xy;
  518. const int mb_type = h->cur_pic.f.mb_type[mb_xy];
  519. int refs[2][48];
  520. int nrefs[2] = { 0 };
  521. int ref, list;
  522. memset(refs, -1, sizeof(refs));
  523. if (IS_16X16(mb_type)) {
  524. get_lowest_part_y(h, refs, 0, 16, 0,
  525. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  526. } else if (IS_16X8(mb_type)) {
  527. get_lowest_part_y(h, refs, 0, 8, 0,
  528. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  529. get_lowest_part_y(h, refs, 8, 8, 8,
  530. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  531. } else if (IS_8X16(mb_type)) {
  532. get_lowest_part_y(h, refs, 0, 16, 0,
  533. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  534. get_lowest_part_y(h, refs, 4, 16, 0,
  535. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  536. } else {
  537. int i;
  538. av_assert2(IS_8X8(mb_type));
  539. for (i = 0; i < 4; i++) {
  540. const int sub_mb_type = h->sub_mb_type[i];
  541. const int n = 4 * i;
  542. int y_offset = (i & 2) << 2;
  543. if (IS_SUB_8X8(sub_mb_type)) {
  544. get_lowest_part_y(h, refs, n, 8, y_offset,
  545. IS_DIR(sub_mb_type, 0, 0),
  546. IS_DIR(sub_mb_type, 0, 1),
  547. nrefs);
  548. } else if (IS_SUB_8X4(sub_mb_type)) {
  549. get_lowest_part_y(h, refs, n, 4, y_offset,
  550. IS_DIR(sub_mb_type, 0, 0),
  551. IS_DIR(sub_mb_type, 0, 1),
  552. nrefs);
  553. get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
  554. IS_DIR(sub_mb_type, 0, 0),
  555. IS_DIR(sub_mb_type, 0, 1),
  556. nrefs);
  557. } else if (IS_SUB_4X8(sub_mb_type)) {
  558. get_lowest_part_y(h, refs, n, 8, y_offset,
  559. IS_DIR(sub_mb_type, 0, 0),
  560. IS_DIR(sub_mb_type, 0, 1),
  561. nrefs);
  562. get_lowest_part_y(h, refs, n + 1, 8, y_offset,
  563. IS_DIR(sub_mb_type, 0, 0),
  564. IS_DIR(sub_mb_type, 0, 1),
  565. nrefs);
  566. } else {
  567. int j;
  568. av_assert2(IS_SUB_4X4(sub_mb_type));
  569. for (j = 0; j < 4; j++) {
  570. int sub_y_offset = y_offset + 2 * (j & 2);
  571. get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
  572. IS_DIR(sub_mb_type, 0, 0),
  573. IS_DIR(sub_mb_type, 0, 1),
  574. nrefs);
  575. }
  576. }
  577. }
  578. }
  579. for (list = h->list_count - 1; list >= 0; list--)
  580. for (ref = 0; ref < 48 && nrefs[list]; ref++) {
  581. int row = refs[list][ref];
  582. if (row >= 0) {
  583. Picture *ref_pic = &h->ref_list[list][ref];
  584. int ref_field = ref_pic->f.reference - 1;
  585. int ref_field_picture = ref_pic->field_picture;
  586. int pic_height = 16 * h->mb_height >> ref_field_picture;
  587. row <<= MB_MBAFF;
  588. nrefs[list]--;
  589. if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
  590. ff_thread_await_progress(&ref_pic->f,
  591. FFMIN((row >> 1) - !(row & 1),
  592. pic_height - 1),
  593. 1);
  594. ff_thread_await_progress(&ref_pic->f,
  595. FFMIN((row >> 1), pic_height - 1),
  596. 0);
  597. } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
  598. ff_thread_await_progress(&ref_pic->f,
  599. FFMIN(row * 2 + ref_field,
  600. pic_height - 1),
  601. 0);
  602. } else if (FIELD_PICTURE) {
  603. ff_thread_await_progress(&ref_pic->f,
  604. FFMIN(row, pic_height - 1),
  605. ref_field);
  606. } else {
  607. ff_thread_await_progress(&ref_pic->f,
  608. FFMIN(row, pic_height - 1),
  609. 0);
  610. }
  611. }
  612. }
  613. }
  614. static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
  615. int n, int square, int height,
  616. int delta, int list,
  617. uint8_t *dest_y, uint8_t *dest_cb,
  618. uint8_t *dest_cr,
  619. int src_x_offset, int src_y_offset,
  620. qpel_mc_func *qpix_op,
  621. h264_chroma_mc_func chroma_op,
  622. int pixel_shift, int chroma_idc)
  623. {
  624. const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
  625. int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
  626. const int luma_xy = (mx & 3) + ((my & 3) << 2);
  627. int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
  628. uint8_t *src_y = pic->f.data[0] + offset;
  629. uint8_t *src_cb, *src_cr;
  630. int extra_width = 0;
  631. int extra_height = 0;
  632. int emu = 0;
  633. const int full_mx = mx >> 2;
  634. const int full_my = my >> 2;
  635. const int pic_width = 16 * h->mb_width;
  636. const int pic_height = 16 * h->mb_height >> MB_FIELD;
  637. int ysh;
  638. if (mx & 7)
  639. extra_width -= 3;
  640. if (my & 7)
  641. extra_height -= 3;
  642. if (full_mx < 0 - extra_width ||
  643. full_my < 0 - extra_height ||
  644. full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
  645. full_my + 16 /*FIXME*/ > pic_height + extra_height) {
  646. h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
  647. src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
  648. h->mb_linesize,
  649. 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
  650. full_my - 2, pic_width, pic_height);
  651. src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  652. emu = 1;
  653. }
  654. qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
  655. if (!square)
  656. qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
  657. if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
  658. return;
  659. if (chroma_idc == 3 /* yuv444 */) {
  660. src_cb = pic->f.data[1] + offset;
  661. if (emu) {
  662. h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
  663. src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
  664. h->mb_linesize,
  665. 16 + 5, 16 + 5 /*FIXME*/,
  666. full_mx - 2, full_my - 2,
  667. pic_width, pic_height);
  668. src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  669. }
  670. qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
  671. if (!square)
  672. qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
  673. src_cr = pic->f.data[2] + offset;
  674. if (emu) {
  675. h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
  676. src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
  677. h->mb_linesize,
  678. 16 + 5, 16 + 5 /*FIXME*/,
  679. full_mx - 2, full_my - 2,
  680. pic_width, pic_height);
  681. src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  682. }
  683. qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
  684. if (!square)
  685. qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
  686. return;
  687. }
  688. ysh = 3 - (chroma_idc == 2 /* yuv422 */);
  689. if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
  690. // chroma offset when predicting from a field of opposite parity
  691. my += 2 * ((h->mb_y & 1) - (pic->f.reference - 1));
  692. emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
  693. }
  694. src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
  695. (my >> ysh) * h->mb_uvlinesize;
  696. src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
  697. (my >> ysh) * h->mb_uvlinesize;
  698. if (emu) {
  699. h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb, h->mb_uvlinesize,
  700. 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
  701. pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
  702. src_cb = h->edge_emu_buffer;
  703. }
  704. chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
  705. height >> (chroma_idc == 1 /* yuv420 */),
  706. mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
  707. if (emu) {
  708. h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr, h->mb_uvlinesize,
  709. 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
  710. pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
  711. src_cr = h->edge_emu_buffer;
  712. }
  713. chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
  714. mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
  715. }
  716. static av_always_inline void mc_part_std(H264Context *h, int n, int square,
  717. int height, int delta,
  718. uint8_t *dest_y, uint8_t *dest_cb,
  719. uint8_t *dest_cr,
  720. int x_offset, int y_offset,
  721. qpel_mc_func *qpix_put,
  722. h264_chroma_mc_func chroma_put,
  723. qpel_mc_func *qpix_avg,
  724. h264_chroma_mc_func chroma_avg,
  725. int list0, int list1,
  726. int pixel_shift, int chroma_idc)
  727. {
  728. qpel_mc_func *qpix_op = qpix_put;
  729. h264_chroma_mc_func chroma_op = chroma_put;
  730. dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  731. if (chroma_idc == 3 /* yuv444 */) {
  732. dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  733. dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  734. } else if (chroma_idc == 2 /* yuv422 */) {
  735. dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  736. dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  737. } else { /* yuv420 */
  738. dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  739. dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  740. }
  741. x_offset += 8 * h->mb_x;
  742. y_offset += 8 * (h->mb_y >> MB_FIELD);
  743. if (list0) {
  744. Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
  745. mc_dir_part(h, ref, n, square, height, delta, 0,
  746. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  747. qpix_op, chroma_op, pixel_shift, chroma_idc);
  748. qpix_op = qpix_avg;
  749. chroma_op = chroma_avg;
  750. }
  751. if (list1) {
  752. Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
  753. mc_dir_part(h, ref, n, square, height, delta, 1,
  754. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  755. qpix_op, chroma_op, pixel_shift, chroma_idc);
  756. }
  757. }
  758. static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
  759. int height, int delta,
  760. uint8_t *dest_y, uint8_t *dest_cb,
  761. uint8_t *dest_cr,
  762. int x_offset, int y_offset,
  763. qpel_mc_func *qpix_put,
  764. h264_chroma_mc_func chroma_put,
  765. h264_weight_func luma_weight_op,
  766. h264_weight_func chroma_weight_op,
  767. h264_biweight_func luma_weight_avg,
  768. h264_biweight_func chroma_weight_avg,
  769. int list0, int list1,
  770. int pixel_shift, int chroma_idc)
  771. {
  772. int chroma_height;
  773. dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  774. if (chroma_idc == 3 /* yuv444 */) {
  775. chroma_height = height;
  776. chroma_weight_avg = luma_weight_avg;
  777. chroma_weight_op = luma_weight_op;
  778. dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  779. dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  780. } else if (chroma_idc == 2 /* yuv422 */) {
  781. chroma_height = height;
  782. dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  783. dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  784. } else { /* yuv420 */
  785. chroma_height = height >> 1;
  786. dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  787. dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  788. }
  789. x_offset += 8 * h->mb_x;
  790. y_offset += 8 * (h->mb_y >> MB_FIELD);
  791. if (list0 && list1) {
  792. /* don't optimize for luma-only case, since B-frames usually
  793. * use implicit weights => chroma too. */
  794. uint8_t *tmp_cb = h->bipred_scratchpad;
  795. uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
  796. uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
  797. int refn0 = h->ref_cache[0][scan8[n]];
  798. int refn1 = h->ref_cache[1][scan8[n]];
  799. mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
  800. dest_y, dest_cb, dest_cr,
  801. x_offset, y_offset, qpix_put, chroma_put,
  802. pixel_shift, chroma_idc);
  803. mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
  804. tmp_y, tmp_cb, tmp_cr,
  805. x_offset, y_offset, qpix_put, chroma_put,
  806. pixel_shift, chroma_idc);
  807. if (h->use_weight == 2) {
  808. int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
  809. int weight1 = 64 - weight0;
  810. luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
  811. height, 5, weight0, weight1, 0);
  812. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
  813. chroma_height, 5, weight0, weight1, 0);
  814. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
  815. chroma_height, 5, weight0, weight1, 0);
  816. } else {
  817. luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
  818. h->luma_log2_weight_denom,
  819. h->luma_weight[refn0][0][0],
  820. h->luma_weight[refn1][1][0],
  821. h->luma_weight[refn0][0][1] +
  822. h->luma_weight[refn1][1][1]);
  823. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
  824. h->chroma_log2_weight_denom,
  825. h->chroma_weight[refn0][0][0][0],
  826. h->chroma_weight[refn1][1][0][0],
  827. h->chroma_weight[refn0][0][0][1] +
  828. h->chroma_weight[refn1][1][0][1]);
  829. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
  830. h->chroma_log2_weight_denom,
  831. h->chroma_weight[refn0][0][1][0],
  832. h->chroma_weight[refn1][1][1][0],
  833. h->chroma_weight[refn0][0][1][1] +
  834. h->chroma_weight[refn1][1][1][1]);
  835. }
  836. } else {
  837. int list = list1 ? 1 : 0;
  838. int refn = h->ref_cache[list][scan8[n]];
  839. Picture *ref = &h->ref_list[list][refn];
  840. mc_dir_part(h, ref, n, square, height, delta, list,
  841. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  842. qpix_put, chroma_put, pixel_shift, chroma_idc);
  843. luma_weight_op(dest_y, h->mb_linesize, height,
  844. h->luma_log2_weight_denom,
  845. h->luma_weight[refn][list][0],
  846. h->luma_weight[refn][list][1]);
  847. if (h->use_weight_chroma) {
  848. chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
  849. h->chroma_log2_weight_denom,
  850. h->chroma_weight[refn][list][0][0],
  851. h->chroma_weight[refn][list][0][1]);
  852. chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
  853. h->chroma_log2_weight_denom,
  854. h->chroma_weight[refn][list][1][0],
  855. h->chroma_weight[refn][list][1][1]);
  856. }
  857. }
  858. }
  859. static av_always_inline void prefetch_motion(H264Context *h, int list,
  860. int pixel_shift, int chroma_idc)
  861. {
  862. /* fetch pixels for estimated mv 4 macroblocks ahead
  863. * optimized for 64byte cache lines */
  864. const int refn = h->ref_cache[list][scan8[0]];
  865. if (refn >= 0) {
  866. const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
  867. const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
  868. uint8_t **src = h->ref_list[list][refn].f.data;
  869. int off = (mx << pixel_shift) +
  870. (my + (h->mb_x & 3) * 4) * h->mb_linesize +
  871. (64 << pixel_shift);
  872. h->vdsp.prefetch(src[0] + off, h->linesize, 4);
  873. if (chroma_idc == 3 /* yuv444 */) {
  874. h->vdsp.prefetch(src[1] + off, h->linesize, 4);
  875. h->vdsp.prefetch(src[2] + off, h->linesize, 4);
  876. } else {
  877. off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
  878. h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
  879. }
  880. }
  881. }
  882. static void free_tables(H264Context *h, int free_rbsp)
  883. {
  884. int i;
  885. H264Context *hx;
  886. av_freep(&h->intra4x4_pred_mode);
  887. av_freep(&h->chroma_pred_mode_table);
  888. av_freep(&h->cbp_table);
  889. av_freep(&h->mvd_table[0]);
  890. av_freep(&h->mvd_table[1]);
  891. av_freep(&h->direct_table);
  892. av_freep(&h->non_zero_count);
  893. av_freep(&h->slice_table_base);
  894. h->slice_table = NULL;
  895. av_freep(&h->list_counts);
  896. av_freep(&h->mb2b_xy);
  897. av_freep(&h->mb2br_xy);
  898. for (i = 0; i < 3; i++)
  899. av_freep(&h->visualization_buffer[i]);
  900. if (free_rbsp) {
  901. for (i = 0; i < h->picture_count && !h->avctx->internal->is_copy; i++)
  902. free_picture(h, &h->DPB[i]);
  903. av_freep(&h->DPB);
  904. h->picture_count = 0;
  905. } else if (h->DPB) {
  906. for (i = 0; i < h->picture_count; i++)
  907. h->DPB[i].needs_realloc = 1;
  908. }
  909. h->cur_pic_ptr = NULL;
  910. for (i = 0; i < MAX_THREADS; i++) {
  911. hx = h->thread_context[i];
  912. if (!hx)
  913. continue;
  914. av_freep(&hx->top_borders[1]);
  915. av_freep(&hx->top_borders[0]);
  916. av_freep(&hx->bipred_scratchpad);
  917. av_freep(&hx->edge_emu_buffer);
  918. av_freep(&hx->dc_val_base);
  919. av_freep(&hx->me.scratchpad);
  920. av_freep(&hx->er.mb_index2xy);
  921. av_freep(&hx->er.error_status_table);
  922. av_freep(&hx->er.er_temp_buffer);
  923. av_freep(&hx->er.mbintra_table);
  924. av_freep(&hx->er.mbskip_table);
  925. if (free_rbsp) {
  926. av_freep(&hx->rbsp_buffer[1]);
  927. av_freep(&hx->rbsp_buffer[0]);
  928. hx->rbsp_buffer_size[0] = 0;
  929. hx->rbsp_buffer_size[1] = 0;
  930. }
  931. if (i)
  932. av_freep(&h->thread_context[i]);
  933. }
  934. }
  935. static void init_dequant8_coeff_table(H264Context *h)
  936. {
  937. int i, j, q, x;
  938. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  939. for (i = 0; i < 6; i++) {
  940. h->dequant8_coeff[i] = h->dequant8_buffer[i];
  941. for (j = 0; j < i; j++)
  942. if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
  943. 64 * sizeof(uint8_t))) {
  944. h->dequant8_coeff[i] = h->dequant8_buffer[j];
  945. break;
  946. }
  947. if (j < i)
  948. continue;
  949. for (q = 0; q < max_qp + 1; q++) {
  950. int shift = div6[q];
  951. int idx = rem6[q];
  952. for (x = 0; x < 64; x++)
  953. h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
  954. ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
  955. h->pps.scaling_matrix8[i][x]) << shift;
  956. }
  957. }
  958. }
  959. static void init_dequant4_coeff_table(H264Context *h)
  960. {
  961. int i, j, q, x;
  962. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  963. for (i = 0; i < 6; i++) {
  964. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  965. for (j = 0; j < i; j++)
  966. if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
  967. 16 * sizeof(uint8_t))) {
  968. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  969. break;
  970. }
  971. if (j < i)
  972. continue;
  973. for (q = 0; q < max_qp + 1; q++) {
  974. int shift = div6[q] + 2;
  975. int idx = rem6[q];
  976. for (x = 0; x < 16; x++)
  977. h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
  978. ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
  979. h->pps.scaling_matrix4[i][x]) << shift;
  980. }
  981. }
  982. }
  983. static void init_dequant_tables(H264Context *h)
  984. {
  985. int i, x;
  986. init_dequant4_coeff_table(h);
  987. if (h->pps.transform_8x8_mode)
  988. init_dequant8_coeff_table(h);
  989. if (h->sps.transform_bypass) {
  990. for (i = 0; i < 6; i++)
  991. for (x = 0; x < 16; x++)
  992. h->dequant4_coeff[i][0][x] = 1 << 6;
  993. if (h->pps.transform_8x8_mode)
  994. for (i = 0; i < 6; i++)
  995. for (x = 0; x < 64; x++)
  996. h->dequant8_coeff[i][0][x] = 1 << 6;
  997. }
  998. }
  999. int ff_h264_alloc_tables(H264Context *h)
  1000. {
  1001. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  1002. const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
  1003. int x, y, i;
  1004. FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  1005. row_mb_num * 8 * sizeof(uint8_t), fail)
  1006. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  1007. big_mb_num * 48 * sizeof(uint8_t), fail)
  1008. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  1009. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  1010. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  1011. big_mb_num * sizeof(uint16_t), fail)
  1012. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  1013. big_mb_num * sizeof(uint8_t), fail)
  1014. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
  1015. 16 * row_mb_num * sizeof(uint8_t), fail);
  1016. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
  1017. 16 * row_mb_num * sizeof(uint8_t), fail);
  1018. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  1019. 4 * big_mb_num * sizeof(uint8_t), fail);
  1020. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  1021. big_mb_num * sizeof(uint8_t), fail)
  1022. memset(h->slice_table_base, -1,
  1023. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  1024. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  1025. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  1026. big_mb_num * sizeof(uint32_t), fail);
  1027. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  1028. big_mb_num * sizeof(uint32_t), fail);
  1029. for (y = 0; y < h->mb_height; y++)
  1030. for (x = 0; x < h->mb_width; x++) {
  1031. const int mb_xy = x + y * h->mb_stride;
  1032. const int b_xy = 4 * x + 4 * y * h->b_stride;
  1033. h->mb2b_xy[mb_xy] = b_xy;
  1034. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  1035. }
  1036. if (!h->dequant4_coeff[0])
  1037. init_dequant_tables(h);
  1038. if (!h->DPB) {
  1039. h->picture_count = MAX_PICTURE_COUNT * FFMAX(1, h->avctx->thread_count);
  1040. h->DPB = av_mallocz_array(h->picture_count, sizeof(*h->DPB));
  1041. if (!h->DPB)
  1042. return AVERROR(ENOMEM);
  1043. for (i = 0; i < h->picture_count; i++)
  1044. avcodec_get_frame_defaults(&h->DPB[i].f);
  1045. avcodec_get_frame_defaults(&h->cur_pic.f);
  1046. }
  1047. return 0;
  1048. fail:
  1049. free_tables(h, 1);
  1050. return -1;
  1051. }
  1052. /**
  1053. * Mimic alloc_tables(), but for every context thread.
  1054. */
  1055. static void clone_tables(H264Context *dst, H264Context *src, int i)
  1056. {
  1057. dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
  1058. dst->non_zero_count = src->non_zero_count;
  1059. dst->slice_table = src->slice_table;
  1060. dst->cbp_table = src->cbp_table;
  1061. dst->mb2b_xy = src->mb2b_xy;
  1062. dst->mb2br_xy = src->mb2br_xy;
  1063. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  1064. dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
  1065. dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
  1066. dst->direct_table = src->direct_table;
  1067. dst->list_counts = src->list_counts;
  1068. dst->DPB = src->DPB;
  1069. dst->cur_pic_ptr = src->cur_pic_ptr;
  1070. dst->cur_pic = src->cur_pic;
  1071. dst->bipred_scratchpad = NULL;
  1072. dst->edge_emu_buffer = NULL;
  1073. dst->me.scratchpad = NULL;
  1074. ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
  1075. src->sps.chroma_format_idc);
  1076. }
  1077. /**
  1078. * Init context
  1079. * Allocate buffers which are not shared amongst multiple threads.
  1080. */
  1081. static int context_init(H264Context *h)
  1082. {
  1083. ERContext *er = &h->er;
  1084. int mb_array_size = h->mb_height * h->mb_stride;
  1085. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  1086. int c_size = h->mb_stride * (h->mb_height + 1);
  1087. int yc_size = y_size + 2 * c_size;
  1088. int x, y, i;
  1089. FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
  1090. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  1091. FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
  1092. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  1093. h->ref_cache[0][scan8[5] + 1] =
  1094. h->ref_cache[0][scan8[7] + 1] =
  1095. h->ref_cache[0][scan8[13] + 1] =
  1096. h->ref_cache[1][scan8[5] + 1] =
  1097. h->ref_cache[1][scan8[7] + 1] =
  1098. h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  1099. /* init ER */
  1100. er->avctx = h->avctx;
  1101. er->dsp = &h->dsp;
  1102. er->decode_mb = h264_er_decode_mb;
  1103. er->opaque = h;
  1104. er->quarter_sample = 1;
  1105. er->mb_num = h->mb_num;
  1106. er->mb_width = h->mb_width;
  1107. er->mb_height = h->mb_height;
  1108. er->mb_stride = h->mb_stride;
  1109. er->b8_stride = h->mb_width * 2 + 1;
  1110. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
  1111. fail); // error ressilience code looks cleaner with this
  1112. for (y = 0; y < h->mb_height; y++)
  1113. for (x = 0; x < h->mb_width; x++)
  1114. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  1115. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  1116. h->mb_stride + h->mb_width;
  1117. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  1118. mb_array_size * sizeof(uint8_t), fail);
  1119. FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
  1120. memset(er->mbintra_table, 1, mb_array_size);
  1121. FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
  1122. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
  1123. fail);
  1124. FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
  1125. er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
  1126. er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
  1127. er->dc_val[2] = er->dc_val[1] + c_size;
  1128. for (i = 0; i < yc_size; i++)
  1129. h->dc_val_base[i] = 1024;
  1130. return 0;
  1131. fail:
  1132. return -1; // free_tables will clean up for us
  1133. }
  1134. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  1135. int parse_extradata);
  1136. static av_cold void common_init(H264Context *h)
  1137. {
  1138. h->width = h->avctx->width;
  1139. h->height = h->avctx->height;
  1140. h->bit_depth_luma = 8;
  1141. h->chroma_format_idc = 1;
  1142. h->avctx->bits_per_raw_sample = 8;
  1143. h->cur_chroma_format_idc = 1;
  1144. ff_h264dsp_init(&h->h264dsp, 8, 1);
  1145. av_assert0(h->sps.bit_depth_chroma == 0);
  1146. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  1147. ff_h264qpel_init(&h->h264qpel, 8);
  1148. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
  1149. h->dequant_coeff_pps = -1;
  1150. h->dsp.dct_bits = 16;
  1151. /* needed so that IDCT permutation is known early */
  1152. ff_dsputil_init(&h->dsp, h->avctx);
  1153. ff_videodsp_init(&h->vdsp, 8);
  1154. memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
  1155. memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
  1156. }
  1157. int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
  1158. {
  1159. AVCodecContext *avctx = h->avctx;
  1160. if (!buf || size <= 0)
  1161. return -1;
  1162. if (buf[0] == 1) {
  1163. int i, cnt, nalsize;
  1164. const unsigned char *p = buf;
  1165. h->is_avc = 1;
  1166. if (size < 7) {
  1167. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  1168. return -1;
  1169. }
  1170. /* sps and pps in the avcC always have length coded with 2 bytes,
  1171. * so put a fake nal_length_size = 2 while parsing them */
  1172. h->nal_length_size = 2;
  1173. // Decode sps from avcC
  1174. cnt = *(p + 5) & 0x1f; // Number of sps
  1175. p += 6;
  1176. for (i = 0; i < cnt; i++) {
  1177. nalsize = AV_RB16(p) + 2;
  1178. if(nalsize > size - (p-buf))
  1179. return -1;
  1180. if (decode_nal_units(h, p, nalsize, 1) < 0) {
  1181. av_log(avctx, AV_LOG_ERROR,
  1182. "Decoding sps %d from avcC failed\n", i);
  1183. return -1;
  1184. }
  1185. p += nalsize;
  1186. }
  1187. // Decode pps from avcC
  1188. cnt = *(p++); // Number of pps
  1189. for (i = 0; i < cnt; i++) {
  1190. nalsize = AV_RB16(p) + 2;
  1191. if(nalsize > size - (p-buf))
  1192. return -1;
  1193. if (decode_nal_units(h, p, nalsize, 1) < 0) {
  1194. av_log(avctx, AV_LOG_ERROR,
  1195. "Decoding pps %d from avcC failed\n", i);
  1196. return -1;
  1197. }
  1198. p += nalsize;
  1199. }
  1200. // Now store right nal length size, that will be used to parse all other nals
  1201. h->nal_length_size = (buf[4] & 0x03) + 1;
  1202. } else {
  1203. h->is_avc = 0;
  1204. if (decode_nal_units(h, buf, size, 1) < 0)
  1205. return -1;
  1206. }
  1207. return size;
  1208. }
  1209. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  1210. {
  1211. H264Context *h = avctx->priv_data;
  1212. int i;
  1213. h->avctx = avctx;
  1214. common_init(h);
  1215. h->picture_structure = PICT_FRAME;
  1216. h->picture_range_start = 0;
  1217. h->picture_range_end = MAX_PICTURE_COUNT;
  1218. h->slice_context_count = 1;
  1219. h->workaround_bugs = avctx->workaround_bugs;
  1220. h->flags = avctx->flags;
  1221. /* set defaults */
  1222. // s->decode_mb = ff_h263_decode_mb;
  1223. if (!avctx->has_b_frames)
  1224. h->low_delay = 1;
  1225. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  1226. ff_h264_decode_init_vlc();
  1227. h->pixel_shift = 0;
  1228. h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
  1229. h->thread_context[0] = h;
  1230. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  1231. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  1232. h->last_pocs[i] = INT_MIN;
  1233. h->prev_poc_msb = 1 << 16;
  1234. h->prev_frame_num = -1;
  1235. h->x264_build = -1;
  1236. ff_h264_reset_sei(h);
  1237. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1238. if (avctx->ticks_per_frame == 1) {
  1239. if(h->avctx->time_base.den < INT_MAX/2) {
  1240. h->avctx->time_base.den *= 2;
  1241. } else
  1242. h->avctx->time_base.num /= 2;
  1243. }
  1244. avctx->ticks_per_frame = 2;
  1245. }
  1246. if (avctx->extradata_size > 0 && avctx->extradata &&
  1247. ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
  1248. ff_h264_free_context(h);
  1249. return -1;
  1250. }
  1251. if (h->sps.bitstream_restriction_flag &&
  1252. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1253. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  1254. h->low_delay = 0;
  1255. }
  1256. ff_init_cabac_states();
  1257. return 0;
  1258. }
  1259. #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
  1260. #undef REBASE_PICTURE
  1261. #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
  1262. ((pic && pic >= old_ctx->DPB && \
  1263. pic < old_ctx->DPB + old_ctx->picture_count) ? \
  1264. &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
  1265. static void copy_picture_range(Picture **to, Picture **from, int count,
  1266. H264Context *new_base,
  1267. H264Context *old_base)
  1268. {
  1269. int i;
  1270. for (i = 0; i < count; i++) {
  1271. assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
  1272. IN_RANGE(from[i], old_base->DPB,
  1273. sizeof(Picture) * old_base->picture_count) ||
  1274. !from[i]));
  1275. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  1276. }
  1277. }
  1278. static void copy_parameter_set(void **to, void **from, int count, int size)
  1279. {
  1280. int i;
  1281. for (i = 0; i < count; i++) {
  1282. if (to[i] && !from[i])
  1283. av_freep(&to[i]);
  1284. else if (from[i] && !to[i])
  1285. to[i] = av_malloc(size);
  1286. if (from[i])
  1287. memcpy(to[i], from[i], size);
  1288. }
  1289. }
  1290. static int decode_init_thread_copy(AVCodecContext *avctx)
  1291. {
  1292. H264Context *h = avctx->priv_data;
  1293. if (!avctx->internal->is_copy)
  1294. return 0;
  1295. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1296. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1297. h->context_initialized = 0;
  1298. return 0;
  1299. }
  1300. #define copy_fields(to, from, start_field, end_field) \
  1301. memcpy(&to->start_field, &from->start_field, \
  1302. (char *)&to->end_field - (char *)&to->start_field)
  1303. static int h264_slice_header_init(H264Context *, int);
  1304. static int h264_set_parameter_from_sps(H264Context *h);
  1305. static int decode_update_thread_context(AVCodecContext *dst,
  1306. const AVCodecContext *src)
  1307. {
  1308. H264Context *h = dst->priv_data, *h1 = src->priv_data;
  1309. int inited = h->context_initialized, err = 0;
  1310. int context_reinitialized = 0;
  1311. int i;
  1312. if (dst == src)
  1313. return 0;
  1314. if (inited &&
  1315. (h->width != h1->width ||
  1316. h->height != h1->height ||
  1317. h->mb_width != h1->mb_width ||
  1318. h->mb_height != h1->mb_height ||
  1319. h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
  1320. h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
  1321. h->sps.colorspace != h1->sps.colorspace)) {
  1322. av_freep(&h->bipred_scratchpad);
  1323. h->width = h1->width;
  1324. h->height = h1->height;
  1325. h->mb_height = h1->mb_height;
  1326. h->mb_width = h1->mb_width;
  1327. h->mb_num = h1->mb_num;
  1328. h->mb_stride = h1->mb_stride;
  1329. h->b_stride = h1->b_stride;
  1330. // SPS/PPS
  1331. copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
  1332. MAX_SPS_COUNT, sizeof(SPS));
  1333. h->sps = h1->sps;
  1334. copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
  1335. MAX_PPS_COUNT, sizeof(PPS));
  1336. h->pps = h1->pps;
  1337. if ((err = h264_slice_header_init(h, 1)) < 0) {
  1338. av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
  1339. return err;
  1340. }
  1341. context_reinitialized = 1;
  1342. #if 0
  1343. h264_set_parameter_from_sps(h);
  1344. //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
  1345. h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
  1346. #endif
  1347. }
  1348. /* update linesize on resize for h264. The h264 decoder doesn't
  1349. * necessarily call ff_MPV_frame_start in the new thread */
  1350. h->linesize = h1->linesize;
  1351. h->uvlinesize = h1->uvlinesize;
  1352. /* copy block_offset since frame_start may not be called */
  1353. memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
  1354. if (!inited) {
  1355. for (i = 0; i < MAX_SPS_COUNT; i++)
  1356. av_freep(h->sps_buffers + i);
  1357. for (i = 0; i < MAX_PPS_COUNT; i++)
  1358. av_freep(h->pps_buffers + i);
  1359. memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
  1360. memcpy(&h->cabac, &h1->cabac,
  1361. sizeof(H264Context) - offsetof(H264Context, cabac));
  1362. av_assert0(&h->cabac == &h->mb_padding + 1);
  1363. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1364. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1365. memset(&h->er, 0, sizeof(h->er));
  1366. memset(&h->me, 0, sizeof(h->me));
  1367. h->avctx = dst;
  1368. h->DPB = NULL;
  1369. if (h1->context_initialized) {
  1370. h->context_initialized = 0;
  1371. h->picture_range_start += MAX_PICTURE_COUNT;
  1372. h->picture_range_end += MAX_PICTURE_COUNT;
  1373. h->cur_pic.f.extended_data = h->cur_pic.f.data;
  1374. if (ff_h264_alloc_tables(h) < 0) {
  1375. av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
  1376. return AVERROR(ENOMEM);
  1377. }
  1378. context_init(h);
  1379. }
  1380. for (i = 0; i < 2; i++) {
  1381. h->rbsp_buffer[i] = NULL;
  1382. h->rbsp_buffer_size[i] = 0;
  1383. }
  1384. h->bipred_scratchpad = NULL;
  1385. h->edge_emu_buffer = NULL;
  1386. h->thread_context[0] = h;
  1387. h->context_initialized = h1->context_initialized;
  1388. }
  1389. h->avctx->coded_height = h1->avctx->coded_height;
  1390. h->avctx->coded_width = h1->avctx->coded_width;
  1391. h->avctx->width = h1->avctx->width;
  1392. h->avctx->height = h1->avctx->height;
  1393. h->coded_picture_number = h1->coded_picture_number;
  1394. h->first_field = h1->first_field;
  1395. h->picture_structure = h1->picture_structure;
  1396. h->qscale = h1->qscale;
  1397. h->droppable = h1->droppable;
  1398. h->data_partitioning = h1->data_partitioning;
  1399. h->low_delay = h1->low_delay;
  1400. memcpy(h->DPB, h1->DPB, h1->picture_count * sizeof(*h1->DPB));
  1401. // reset s->picture[].f.extended_data to s->picture[].f.data
  1402. for (i = 0; i < h->picture_count; i++) {
  1403. h->DPB[i].f.extended_data = h->DPB[i].f.data;
  1404. h->DPB[i].period_since_free ++;
  1405. }
  1406. h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
  1407. h->cur_pic = h1->cur_pic;
  1408. h->cur_pic.f.extended_data = h->cur_pic.f.data;
  1409. h->workaround_bugs = h1->workaround_bugs;
  1410. h->low_delay = h1->low_delay;
  1411. h->droppable = h1->droppable;
  1412. /* frame_start may not be called for the next thread (if it's decoding
  1413. * a bottom field) so this has to be allocated here */
  1414. if (h1->linesize) {
  1415. err = alloc_scratch_buffers(h, h1->linesize);
  1416. if (err < 0)
  1417. return err;
  1418. }
  1419. // extradata/NAL handling
  1420. h->is_avc = h1->is_avc;
  1421. // SPS/PPS
  1422. copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
  1423. MAX_SPS_COUNT, sizeof(SPS));
  1424. h->sps = h1->sps;
  1425. copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
  1426. MAX_PPS_COUNT, sizeof(PPS));
  1427. h->pps = h1->pps;
  1428. // Dequantization matrices
  1429. // FIXME these are big - can they be only copied when PPS changes?
  1430. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  1431. for (i = 0; i < 6; i++)
  1432. h->dequant4_coeff[i] = h->dequant4_buffer[0] +
  1433. (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  1434. for (i = 0; i < 6; i++)
  1435. h->dequant8_coeff[i] = h->dequant8_buffer[0] +
  1436. (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  1437. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  1438. // POC timing
  1439. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  1440. // reference lists
  1441. copy_fields(h, h1, ref_count, list_count);
  1442. copy_fields(h, h1, ref2frm, intra_gb);
  1443. copy_fields(h, h1, short_ref, cabac_init_idc);
  1444. copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
  1445. copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
  1446. copy_picture_range(h->delayed_pic, h1->delayed_pic,
  1447. MAX_DELAYED_PIC_COUNT + 2, h, h1);
  1448. h->last_slice_type = h1->last_slice_type;
  1449. h->sync = h1->sync;
  1450. if (context_reinitialized)
  1451. h264_set_parameter_from_sps(h);
  1452. if (!h->cur_pic_ptr)
  1453. return 0;
  1454. if (!h->droppable) {
  1455. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1456. h->prev_poc_msb = h->poc_msb;
  1457. h->prev_poc_lsb = h->poc_lsb;
  1458. }
  1459. h->prev_frame_num_offset = h->frame_num_offset;
  1460. h->prev_frame_num = h->frame_num;
  1461. h->outputed_poc = h->next_outputed_poc;
  1462. return err;
  1463. }
  1464. int ff_h264_frame_start(H264Context *h)
  1465. {
  1466. Picture *pic;
  1467. int i, ret;
  1468. const int pixel_shift = h->pixel_shift;
  1469. int c[4] = {
  1470. 1<<(h->sps.bit_depth_luma-1),
  1471. 1<<(h->sps.bit_depth_chroma-1),
  1472. 1<<(h->sps.bit_depth_chroma-1),
  1473. -1
  1474. };
  1475. if (!ff_thread_can_start_frame(h->avctx)) {
  1476. av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
  1477. return -1;
  1478. }
  1479. release_unused_pictures(h, 1);
  1480. h->cur_pic_ptr = NULL;
  1481. i = find_unused_picture(h);
  1482. if (i < 0) {
  1483. av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
  1484. return i;
  1485. }
  1486. pic = &h->DPB[i];
  1487. pic->f.reference = h->droppable ? 0 : h->picture_structure;
  1488. pic->f.coded_picture_number = h->coded_picture_number++;
  1489. pic->field_picture = h->picture_structure != PICT_FRAME;
  1490. /*
  1491. * Zero key_frame here; IDR markings per slice in frame or fields are ORed
  1492. * in later.
  1493. * See decode_nal_units().
  1494. */
  1495. pic->f.key_frame = 0;
  1496. pic->sync = 0;
  1497. pic->mmco_reset = 0;
  1498. if ((ret = alloc_picture(h, pic)) < 0)
  1499. return ret;
  1500. if(!h->sync && !h->avctx->hwaccel &&
  1501. !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
  1502. avpriv_color_frame(&pic->f, c);
  1503. h->cur_pic_ptr = pic;
  1504. h->cur_pic = *h->cur_pic_ptr;
  1505. h->cur_pic.f.extended_data = h->cur_pic.f.data;
  1506. ff_er_frame_start(&h->er);
  1507. assert(h->linesize && h->uvlinesize);
  1508. for (i = 0; i < 16; i++) {
  1509. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1510. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1511. }
  1512. for (i = 0; i < 16; i++) {
  1513. h->block_offset[16 + i] =
  1514. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1515. h->block_offset[48 + 16 + i] =
  1516. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1517. }
  1518. /* can't be in alloc_tables because linesize isn't known there.
  1519. * FIXME: redo bipred weight to not require extra buffer? */
  1520. for (i = 0; i < h->slice_context_count; i++)
  1521. if (h->thread_context[i]) {
  1522. ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
  1523. if (ret < 0)
  1524. return ret;
  1525. }
  1526. /* Some macroblocks can be accessed before they're available in case
  1527. * of lost slices, MBAFF or threading. */
  1528. memset(h->slice_table, -1,
  1529. (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
  1530. // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
  1531. // h->cur_pic.f.reference /* || h->contains_intra */ || 1;
  1532. /* We mark the current picture as non-reference after allocating it, so
  1533. * that if we break out due to an error it can be released automatically
  1534. * in the next ff_MPV_frame_start().
  1535. * SVQ3 as well as most other codecs have only last/next/current and thus
  1536. * get released even with set reference, besides SVQ3 and others do not
  1537. * mark frames as reference later "naturally". */
  1538. if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)
  1539. h->cur_pic_ptr->f.reference = 0;
  1540. h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
  1541. h->next_output_pic = NULL;
  1542. assert(h->cur_pic_ptr->long_ref == 0);
  1543. return 0;
  1544. }
  1545. /**
  1546. * Run setup operations that must be run after slice header decoding.
  1547. * This includes finding the next displayed frame.
  1548. *
  1549. * @param h h264 master context
  1550. * @param setup_finished enough NALs have been read that we can call
  1551. * ff_thread_finish_setup()
  1552. */
  1553. static void decode_postinit(H264Context *h, int setup_finished)
  1554. {
  1555. Picture *out = h->cur_pic_ptr;
  1556. Picture *cur = h->cur_pic_ptr;
  1557. int i, pics, out_of_order, out_idx;
  1558. h->cur_pic_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
  1559. h->cur_pic_ptr->f.pict_type = h->pict_type;
  1560. if (h->next_output_pic)
  1561. return;
  1562. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  1563. /* FIXME: if we have two PAFF fields in one packet, we can't start
  1564. * the next thread here. If we have one field per packet, we can.
  1565. * The check in decode_nal_units() is not good enough to find this
  1566. * yet, so we assume the worst for now. */
  1567. // if (setup_finished)
  1568. // ff_thread_finish_setup(h->avctx);
  1569. return;
  1570. }
  1571. cur->f.interlaced_frame = 0;
  1572. cur->f.repeat_pict = 0;
  1573. /* Signal interlacing information externally. */
  1574. /* Prioritize picture timing SEI information over used
  1575. * decoding process if it exists. */
  1576. if (h->sps.pic_struct_present_flag) {
  1577. switch (h->sei_pic_struct) {
  1578. case SEI_PIC_STRUCT_FRAME:
  1579. break;
  1580. case SEI_PIC_STRUCT_TOP_FIELD:
  1581. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1582. cur->f.interlaced_frame = 1;
  1583. break;
  1584. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1585. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1586. if (FIELD_OR_MBAFF_PICTURE)
  1587. cur->f.interlaced_frame = 1;
  1588. else
  1589. // try to flag soft telecine progressive
  1590. cur->f.interlaced_frame = h->prev_interlaced_frame;
  1591. break;
  1592. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1593. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1594. /* Signal the possibility of telecined film externally
  1595. * (pic_struct 5,6). From these hints, let the applications
  1596. * decide if they apply deinterlacing. */
  1597. cur->f.repeat_pict = 1;
  1598. break;
  1599. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1600. cur->f.repeat_pict = 2;
  1601. break;
  1602. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1603. cur->f.repeat_pict = 4;
  1604. break;
  1605. }
  1606. if ((h->sei_ct_type & 3) &&
  1607. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1608. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  1609. } else {
  1610. /* Derive interlacing flag from used decoding process. */
  1611. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  1612. }
  1613. h->prev_interlaced_frame = cur->f.interlaced_frame;
  1614. if (cur->field_poc[0] != cur->field_poc[1]) {
  1615. /* Derive top_field_first from field pocs. */
  1616. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1617. } else {
  1618. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  1619. /* Use picture timing SEI information. Even if it is a
  1620. * information of a past frame, better than nothing. */
  1621. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  1622. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1623. cur->f.top_field_first = 1;
  1624. else
  1625. cur->f.top_field_first = 0;
  1626. } else {
  1627. /* Most likely progressive */
  1628. cur->f.top_field_first = 0;
  1629. }
  1630. }
  1631. cur->mmco_reset = h->mmco_reset;
  1632. h->mmco_reset = 0;
  1633. // FIXME do something with unavailable reference frames
  1634. /* Sort B-frames into display order */
  1635. if (h->sps.bitstream_restriction_flag &&
  1636. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1637. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  1638. h->low_delay = 0;
  1639. }
  1640. if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  1641. !h->sps.bitstream_restriction_flag) {
  1642. h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  1643. h->low_delay = 0;
  1644. }
  1645. for (i = 0; 1; i++) {
  1646. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1647. if(i)
  1648. h->last_pocs[i-1] = cur->poc;
  1649. break;
  1650. } else if(i) {
  1651. h->last_pocs[i-1]= h->last_pocs[i];
  1652. }
  1653. }
  1654. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1655. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  1656. || (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))
  1657. out_of_order = FFMAX(out_of_order, 1);
  1658. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  1659. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  1660. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  1661. h->last_pocs[i] = INT_MIN;
  1662. h->last_pocs[0] = cur->poc;
  1663. cur->mmco_reset = 1;
  1664. } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  1665. av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
  1666. h->avctx->has_b_frames = out_of_order;
  1667. h->low_delay = 0;
  1668. }
  1669. pics = 0;
  1670. while (h->delayed_pic[pics])
  1671. pics++;
  1672. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1673. h->delayed_pic[pics++] = cur;
  1674. if (cur->f.reference == 0)
  1675. cur->f.reference = DELAYED_PIC_REF;
  1676. out = h->delayed_pic[0];
  1677. out_idx = 0;
  1678. for (i = 1; h->delayed_pic[i] &&
  1679. !h->delayed_pic[i]->f.key_frame &&
  1680. !h->delayed_pic[i]->mmco_reset;
  1681. i++)
  1682. if (h->delayed_pic[i]->poc < out->poc) {
  1683. out = h->delayed_pic[i];
  1684. out_idx = i;
  1685. }
  1686. if (h->avctx->has_b_frames == 0 &&
  1687. (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  1688. h->next_outputed_poc = INT_MIN;
  1689. out_of_order = out->poc < h->next_outputed_poc;
  1690. if (out_of_order || pics > h->avctx->has_b_frames) {
  1691. out->f.reference &= ~DELAYED_PIC_REF;
  1692. // for frame threading, the owner must be the second field's thread or
  1693. // else the first thread can release the picture and reuse it unsafely
  1694. out->owner2 = h;
  1695. for (i = out_idx; h->delayed_pic[i]; i++)
  1696. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1697. }
  1698. if (!out_of_order && pics > h->avctx->has_b_frames) {
  1699. h->next_output_pic = out;
  1700. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  1701. h->next_outputed_poc = INT_MIN;
  1702. } else
  1703. h->next_outputed_poc = out->poc;
  1704. } else {
  1705. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1706. }
  1707. if (h->next_output_pic && h->next_output_pic->sync) {
  1708. h->sync |= 2;
  1709. }
  1710. if (setup_finished)
  1711. ff_thread_finish_setup(h->avctx);
  1712. }
  1713. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  1714. uint8_t *src_cb, uint8_t *src_cr,
  1715. int linesize, int uvlinesize,
  1716. int simple)
  1717. {
  1718. uint8_t *top_border;
  1719. int top_idx = 1;
  1720. const int pixel_shift = h->pixel_shift;
  1721. int chroma444 = CHROMA444;
  1722. int chroma422 = CHROMA422;
  1723. src_y -= linesize;
  1724. src_cb -= uvlinesize;
  1725. src_cr -= uvlinesize;
  1726. if (!simple && FRAME_MBAFF) {
  1727. if (h->mb_y & 1) {
  1728. if (!MB_MBAFF) {
  1729. top_border = h->top_borders[0][h->mb_x];
  1730. AV_COPY128(top_border, src_y + 15 * linesize);
  1731. if (pixel_shift)
  1732. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  1733. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1734. if (chroma444) {
  1735. if (pixel_shift) {
  1736. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1737. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  1738. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  1739. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  1740. } else {
  1741. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  1742. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  1743. }
  1744. } else if (chroma422) {
  1745. if (pixel_shift) {
  1746. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1747. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  1748. } else {
  1749. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  1750. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  1751. }
  1752. } else {
  1753. if (pixel_shift) {
  1754. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  1755. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  1756. } else {
  1757. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  1758. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  1759. }
  1760. }
  1761. }
  1762. }
  1763. } else if (MB_MBAFF) {
  1764. top_idx = 0;
  1765. } else
  1766. return;
  1767. }
  1768. top_border = h->top_borders[top_idx][h->mb_x];
  1769. /* There are two lines saved, the line above the top macroblock
  1770. * of a pair, and the line above the bottom macroblock. */
  1771. AV_COPY128(top_border, src_y + 16 * linesize);
  1772. if (pixel_shift)
  1773. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  1774. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1775. if (chroma444) {
  1776. if (pixel_shift) {
  1777. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  1778. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  1779. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  1780. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  1781. } else {
  1782. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  1783. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  1784. }
  1785. } else if (chroma422) {
  1786. if (pixel_shift) {
  1787. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  1788. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  1789. } else {
  1790. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  1791. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  1792. }
  1793. } else {
  1794. if (pixel_shift) {
  1795. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  1796. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  1797. } else {
  1798. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  1799. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  1800. }
  1801. }
  1802. }
  1803. }
  1804. static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
  1805. uint8_t *src_cb, uint8_t *src_cr,
  1806. int linesize, int uvlinesize,
  1807. int xchg, int chroma444,
  1808. int simple, int pixel_shift)
  1809. {
  1810. int deblock_topleft;
  1811. int deblock_top;
  1812. int top_idx = 1;
  1813. uint8_t *top_border_m1;
  1814. uint8_t *top_border;
  1815. if (!simple && FRAME_MBAFF) {
  1816. if (h->mb_y & 1) {
  1817. if (!MB_MBAFF)
  1818. return;
  1819. } else {
  1820. top_idx = MB_MBAFF ? 0 : 1;
  1821. }
  1822. }
  1823. if (h->deblocking_filter == 2) {
  1824. deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
  1825. deblock_top = h->top_type;
  1826. } else {
  1827. deblock_topleft = (h->mb_x > 0);
  1828. deblock_top = (h->mb_y > !!MB_FIELD);
  1829. }
  1830. src_y -= linesize + 1 + pixel_shift;
  1831. src_cb -= uvlinesize + 1 + pixel_shift;
  1832. src_cr -= uvlinesize + 1 + pixel_shift;
  1833. top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
  1834. top_border = h->top_borders[top_idx][h->mb_x];
  1835. #define XCHG(a, b, xchg) \
  1836. if (pixel_shift) { \
  1837. if (xchg) { \
  1838. AV_SWAP64(b + 0, a + 0); \
  1839. AV_SWAP64(b + 8, a + 8); \
  1840. } else { \
  1841. AV_COPY128(b, a); \
  1842. } \
  1843. } else if (xchg) \
  1844. AV_SWAP64(b, a); \
  1845. else \
  1846. AV_COPY64(b, a);
  1847. if (deblock_top) {
  1848. if (deblock_topleft) {
  1849. XCHG(top_border_m1 + (8 << pixel_shift),
  1850. src_y - (7 << pixel_shift), 1);
  1851. }
  1852. XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
  1853. XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
  1854. if (h->mb_x + 1 < h->mb_width) {
  1855. XCHG(h->top_borders[top_idx][h->mb_x + 1],
  1856. src_y + (17 << pixel_shift), 1);
  1857. }
  1858. }
  1859. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1860. if (chroma444) {
  1861. if (deblock_topleft) {
  1862. XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1863. XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1864. }
  1865. XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
  1866. XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
  1867. XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
  1868. XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
  1869. if (h->mb_x + 1 < h->mb_width) {
  1870. XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
  1871. XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
  1872. }
  1873. } else {
  1874. if (deblock_top) {
  1875. if (deblock_topleft) {
  1876. XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1877. XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1878. }
  1879. XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
  1880. XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
  1881. }
  1882. }
  1883. }
  1884. }
  1885. static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
  1886. int index)
  1887. {
  1888. if (high_bit_depth) {
  1889. return AV_RN32A(((int32_t *)mb) + index);
  1890. } else
  1891. return AV_RN16A(mb + index);
  1892. }
  1893. static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
  1894. int index, int value)
  1895. {
  1896. if (high_bit_depth) {
  1897. AV_WN32A(((int32_t *)mb) + index, value);
  1898. } else
  1899. AV_WN16A(mb + index, value);
  1900. }
  1901. static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
  1902. int mb_type, int is_h264,
  1903. int simple,
  1904. int transform_bypass,
  1905. int pixel_shift,
  1906. int *block_offset,
  1907. int linesize,
  1908. uint8_t *dest_y, int p)
  1909. {
  1910. void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
  1911. void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
  1912. int i;
  1913. int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
  1914. block_offset += 16 * p;
  1915. if (IS_INTRA4x4(mb_type)) {
  1916. if (IS_8x8DCT(mb_type)) {
  1917. if (transform_bypass) {
  1918. idct_dc_add =
  1919. idct_add = h->h264dsp.h264_add_pixels8;
  1920. } else {
  1921. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  1922. idct_add = h->h264dsp.h264_idct8_add;
  1923. }
  1924. for (i = 0; i < 16; i += 4) {
  1925. uint8_t *const ptr = dest_y + block_offset[i];
  1926. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1927. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1928. h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1929. } else {
  1930. const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1931. h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
  1932. (h->topright_samples_available << i) & 0x4000, linesize);
  1933. if (nnz) {
  1934. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1935. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1936. else
  1937. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1938. }
  1939. }
  1940. }
  1941. } else {
  1942. if (transform_bypass) {
  1943. idct_dc_add =
  1944. idct_add = h->h264dsp.h264_add_pixels4;
  1945. } else {
  1946. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  1947. idct_add = h->h264dsp.h264_idct_add;
  1948. }
  1949. for (i = 0; i < 16; i++) {
  1950. uint8_t *const ptr = dest_y + block_offset[i];
  1951. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1952. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1953. h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1954. } else {
  1955. uint8_t *topright;
  1956. int nnz, tr;
  1957. uint64_t tr_high;
  1958. if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
  1959. const int topright_avail = (h->topright_samples_available << i) & 0x8000;
  1960. av_assert2(h->mb_y || linesize <= block_offset[i]);
  1961. if (!topright_avail) {
  1962. if (pixel_shift) {
  1963. tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
  1964. topright = (uint8_t *)&tr_high;
  1965. } else {
  1966. tr = ptr[3 - linesize] * 0x01010101u;
  1967. topright = (uint8_t *)&tr;
  1968. }
  1969. } else
  1970. topright = ptr + (4 << pixel_shift) - linesize;
  1971. } else
  1972. topright = NULL;
  1973. h->hpc.pred4x4[dir](ptr, topright, linesize);
  1974. nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1975. if (nnz) {
  1976. if (is_h264) {
  1977. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1978. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1979. else
  1980. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1981. } else if (CONFIG_SVQ3_DECODER)
  1982. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
  1983. }
  1984. }
  1985. }
  1986. }
  1987. } else {
  1988. h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
  1989. if (is_h264) {
  1990. if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
  1991. if (!transform_bypass)
  1992. h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
  1993. h->mb_luma_dc[p],
  1994. h->dequant4_coeff[p][qscale][0]);
  1995. else {
  1996. static const uint8_t dc_mapping[16] = {
  1997. 0 * 16, 1 * 16, 4 * 16, 5 * 16,
  1998. 2 * 16, 3 * 16, 6 * 16, 7 * 16,
  1999. 8 * 16, 9 * 16, 12 * 16, 13 * 16,
  2000. 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
  2001. for (i = 0; i < 16; i++)
  2002. dctcoef_set(h->mb + (p * 256 << pixel_shift),
  2003. pixel_shift, dc_mapping[i],
  2004. dctcoef_get(h->mb_luma_dc[p],
  2005. pixel_shift, i));
  2006. }
  2007. }
  2008. } else if (CONFIG_SVQ3_DECODER)
  2009. ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
  2010. h->mb_luma_dc[p], qscale);
  2011. }
  2012. }
  2013. static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
  2014. int is_h264, int simple,
  2015. int transform_bypass,
  2016. int pixel_shift,
  2017. int *block_offset,
  2018. int linesize,
  2019. uint8_t *dest_y, int p)
  2020. {
  2021. void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
  2022. int i;
  2023. block_offset += 16 * p;
  2024. if (!IS_INTRA4x4(mb_type)) {
  2025. if (is_h264) {
  2026. if (IS_INTRA16x16(mb_type)) {
  2027. if (transform_bypass) {
  2028. if (h->sps.profile_idc == 244 &&
  2029. (h->intra16x16_pred_mode == VERT_PRED8x8 ||
  2030. h->intra16x16_pred_mode == HOR_PRED8x8)) {
  2031. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
  2032. h->mb + (p * 256 << pixel_shift),
  2033. linesize);
  2034. } else {
  2035. for (i = 0; i < 16; i++)
  2036. if (h->non_zero_count_cache[scan8[i + p * 16]] ||
  2037. dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  2038. h->h264dsp.h264_add_pixels4(dest_y + block_offset[i],
  2039. h->mb + (i * 16 + p * 256 << pixel_shift),
  2040. linesize);
  2041. }
  2042. } else {
  2043. h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
  2044. h->mb + (p * 256 << pixel_shift),
  2045. linesize,
  2046. h->non_zero_count_cache + p * 5 * 8);
  2047. }
  2048. } else if (h->cbp & 15) {
  2049. if (transform_bypass) {
  2050. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  2051. idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8
  2052. : h->h264dsp.h264_add_pixels4;
  2053. for (i = 0; i < 16; i += di)
  2054. if (h->non_zero_count_cache[scan8[i + p * 16]])
  2055. idct_add(dest_y + block_offset[i],
  2056. h->mb + (i * 16 + p * 256 << pixel_shift),
  2057. linesize);
  2058. } else {
  2059. if (IS_8x8DCT(mb_type))
  2060. h->h264dsp.h264_idct8_add4(dest_y, block_offset,
  2061. h->mb + (p * 256 << pixel_shift),
  2062. linesize,
  2063. h->non_zero_count_cache + p * 5 * 8);
  2064. else
  2065. h->h264dsp.h264_idct_add16(dest_y, block_offset,
  2066. h->mb + (p * 256 << pixel_shift),
  2067. linesize,
  2068. h->non_zero_count_cache + p * 5 * 8);
  2069. }
  2070. }
  2071. } else if (CONFIG_SVQ3_DECODER) {
  2072. for (i = 0; i < 16; i++)
  2073. if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
  2074. // FIXME benchmark weird rule, & below
  2075. uint8_t *const ptr = dest_y + block_offset[i];
  2076. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
  2077. h->qscale, IS_INTRA(mb_type) ? 1 : 0);
  2078. }
  2079. }
  2080. }
  2081. }
  2082. #define BITS 8
  2083. #define SIMPLE 1
  2084. #include "h264_mb_template.c"
  2085. #undef BITS
  2086. #define BITS 16
  2087. #include "h264_mb_template.c"
  2088. #undef SIMPLE
  2089. #define SIMPLE 0
  2090. #include "h264_mb_template.c"
  2091. void ff_h264_hl_decode_mb(H264Context *h)
  2092. {
  2093. const int mb_xy = h->mb_xy;
  2094. const int mb_type = h->cur_pic.f.mb_type[mb_xy];
  2095. int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || h->qscale == 0;
  2096. if (CHROMA444) {
  2097. if (is_complex || h->pixel_shift)
  2098. hl_decode_mb_444_complex(h);
  2099. else
  2100. hl_decode_mb_444_simple_8(h);
  2101. } else if (is_complex) {
  2102. hl_decode_mb_complex(h);
  2103. } else if (h->pixel_shift) {
  2104. hl_decode_mb_simple_16(h);
  2105. } else
  2106. hl_decode_mb_simple_8(h);
  2107. }
  2108. static int pred_weight_table(H264Context *h)
  2109. {
  2110. int list, i;
  2111. int luma_def, chroma_def;
  2112. h->use_weight = 0;
  2113. h->use_weight_chroma = 0;
  2114. h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
  2115. if (h->sps.chroma_format_idc)
  2116. h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
  2117. luma_def = 1 << h->luma_log2_weight_denom;
  2118. chroma_def = 1 << h->chroma_log2_weight_denom;
  2119. for (list = 0; list < 2; list++) {
  2120. h->luma_weight_flag[list] = 0;
  2121. h->chroma_weight_flag[list] = 0;
  2122. for (i = 0; i < h->ref_count[list]; i++) {
  2123. int luma_weight_flag, chroma_weight_flag;
  2124. luma_weight_flag = get_bits1(&h->gb);
  2125. if (luma_weight_flag) {
  2126. h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
  2127. h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
  2128. if (h->luma_weight[i][list][0] != luma_def ||
  2129. h->luma_weight[i][list][1] != 0) {
  2130. h->use_weight = 1;
  2131. h->luma_weight_flag[list] = 1;
  2132. }
  2133. } else {
  2134. h->luma_weight[i][list][0] = luma_def;
  2135. h->luma_weight[i][list][1] = 0;
  2136. }
  2137. if (h->sps.chroma_format_idc) {
  2138. chroma_weight_flag = get_bits1(&h->gb);
  2139. if (chroma_weight_flag) {
  2140. int j;
  2141. for (j = 0; j < 2; j++) {
  2142. h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
  2143. h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
  2144. if (h->chroma_weight[i][list][j][0] != chroma_def ||
  2145. h->chroma_weight[i][list][j][1] != 0) {
  2146. h->use_weight_chroma = 1;
  2147. h->chroma_weight_flag[list] = 1;
  2148. }
  2149. }
  2150. } else {
  2151. int j;
  2152. for (j = 0; j < 2; j++) {
  2153. h->chroma_weight[i][list][j][0] = chroma_def;
  2154. h->chroma_weight[i][list][j][1] = 0;
  2155. }
  2156. }
  2157. }
  2158. }
  2159. if (h->slice_type_nos != AV_PICTURE_TYPE_B)
  2160. break;
  2161. }
  2162. h->use_weight = h->use_weight || h->use_weight_chroma;
  2163. return 0;
  2164. }
  2165. /**
  2166. * Initialize implicit_weight table.
  2167. * @param field 0/1 initialize the weight for interlaced MBAFF
  2168. * -1 initializes the rest
  2169. */
  2170. static void implicit_weight_table(H264Context *h, int field)
  2171. {
  2172. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  2173. for (i = 0; i < 2; i++) {
  2174. h->luma_weight_flag[i] = 0;
  2175. h->chroma_weight_flag[i] = 0;
  2176. }
  2177. if (field < 0) {
  2178. if (h->picture_structure == PICT_FRAME) {
  2179. cur_poc = h->cur_pic_ptr->poc;
  2180. } else {
  2181. cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
  2182. }
  2183. if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
  2184. h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
  2185. h->use_weight = 0;
  2186. h->use_weight_chroma = 0;
  2187. return;
  2188. }
  2189. ref_start = 0;
  2190. ref_count0 = h->ref_count[0];
  2191. ref_count1 = h->ref_count[1];
  2192. } else {
  2193. cur_poc = h->cur_pic_ptr->field_poc[field];
  2194. ref_start = 16;
  2195. ref_count0 = 16 + 2 * h->ref_count[0];
  2196. ref_count1 = 16 + 2 * h->ref_count[1];
  2197. }
  2198. h->use_weight = 2;
  2199. h->use_weight_chroma = 2;
  2200. h->luma_log2_weight_denom = 5;
  2201. h->chroma_log2_weight_denom = 5;
  2202. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  2203. int poc0 = h->ref_list[0][ref0].poc;
  2204. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  2205. int w = 32;
  2206. if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
  2207. int poc1 = h->ref_list[1][ref1].poc;
  2208. int td = av_clip(poc1 - poc0, -128, 127);
  2209. if (td) {
  2210. int tb = av_clip(cur_poc - poc0, -128, 127);
  2211. int tx = (16384 + (FFABS(td) >> 1)) / td;
  2212. int dist_scale_factor = (tb * tx + 32) >> 8;
  2213. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  2214. w = 64 - dist_scale_factor;
  2215. }
  2216. }
  2217. if (field < 0) {
  2218. h->implicit_weight[ref0][ref1][0] =
  2219. h->implicit_weight[ref0][ref1][1] = w;
  2220. } else {
  2221. h->implicit_weight[ref0][ref1][field] = w;
  2222. }
  2223. }
  2224. }
  2225. }
  2226. /**
  2227. * instantaneous decoder refresh.
  2228. */
  2229. static void idr(H264Context *h)
  2230. {
  2231. int i;
  2232. ff_h264_remove_all_refs(h);
  2233. h->prev_frame_num = 0;
  2234. h->prev_frame_num_offset = 0;
  2235. h->prev_poc_msb = 1<<16;
  2236. h->prev_poc_lsb = 0;
  2237. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  2238. h->last_pocs[i] = INT_MIN;
  2239. }
  2240. /* forget old pics after a seek */
  2241. static void flush_change(H264Context *h)
  2242. {
  2243. int i, j;
  2244. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  2245. h->prev_interlaced_frame = 1;
  2246. idr(h);
  2247. h->prev_frame_num = -1;
  2248. if (h->cur_pic_ptr) {
  2249. h->cur_pic_ptr->f.reference = 0;
  2250. for (j=i=0; h->delayed_pic[i]; i++)
  2251. if (h->delayed_pic[i] != h->cur_pic_ptr)
  2252. h->delayed_pic[j++] = h->delayed_pic[i];
  2253. h->delayed_pic[j] = NULL;
  2254. }
  2255. h->first_field = 0;
  2256. memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
  2257. memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
  2258. memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
  2259. memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
  2260. ff_h264_reset_sei(h);
  2261. h->recovery_frame= -1;
  2262. h->sync= 0;
  2263. h->list_count = 0;
  2264. h->current_slice = 0;
  2265. }
  2266. /* forget old pics after a seek */
  2267. static void flush_dpb(AVCodecContext *avctx)
  2268. {
  2269. H264Context *h = avctx->priv_data;
  2270. int i;
  2271. for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
  2272. if (h->delayed_pic[i])
  2273. h->delayed_pic[i]->f.reference = 0;
  2274. h->delayed_pic[i] = NULL;
  2275. }
  2276. flush_change(h);
  2277. for (i = 0; i < h->picture_count; i++) {
  2278. if (h->DPB[i].f.data[0])
  2279. free_frame_buffer(h, &h->DPB[i]);
  2280. }
  2281. h->cur_pic_ptr = NULL;
  2282. h->mb_x = h->mb_y = 0;
  2283. h->parse_context.state = -1;
  2284. h->parse_context.frame_start_found = 0;
  2285. h->parse_context.overread = 0;
  2286. h->parse_context.overread_index = 0;
  2287. h->parse_context.index = 0;
  2288. h->parse_context.last_index = 0;
  2289. }
  2290. static int init_poc(H264Context *h)
  2291. {
  2292. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2293. int field_poc[2];
  2294. Picture *cur = h->cur_pic_ptr;
  2295. h->frame_num_offset = h->prev_frame_num_offset;
  2296. if (h->frame_num < h->prev_frame_num)
  2297. h->frame_num_offset += max_frame_num;
  2298. if (h->sps.poc_type == 0) {
  2299. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  2300. if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  2301. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  2302. else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  2303. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  2304. else
  2305. h->poc_msb = h->prev_poc_msb;
  2306. field_poc[0] =
  2307. field_poc[1] = h->poc_msb + h->poc_lsb;
  2308. if (h->picture_structure == PICT_FRAME)
  2309. field_poc[1] += h->delta_poc_bottom;
  2310. } else if (h->sps.poc_type == 1) {
  2311. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  2312. int i;
  2313. if (h->sps.poc_cycle_length != 0)
  2314. abs_frame_num = h->frame_num_offset + h->frame_num;
  2315. else
  2316. abs_frame_num = 0;
  2317. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  2318. abs_frame_num--;
  2319. expected_delta_per_poc_cycle = 0;
  2320. for (i = 0; i < h->sps.poc_cycle_length; i++)
  2321. // FIXME integrate during sps parse
  2322. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  2323. if (abs_frame_num > 0) {
  2324. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  2325. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  2326. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  2327. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  2328. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  2329. } else
  2330. expectedpoc = 0;
  2331. if (h->nal_ref_idc == 0)
  2332. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  2333. field_poc[0] = expectedpoc + h->delta_poc[0];
  2334. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  2335. if (h->picture_structure == PICT_FRAME)
  2336. field_poc[1] += h->delta_poc[1];
  2337. } else {
  2338. int poc = 2 * (h->frame_num_offset + h->frame_num);
  2339. if (!h->nal_ref_idc)
  2340. poc--;
  2341. field_poc[0] = poc;
  2342. field_poc[1] = poc;
  2343. }
  2344. if (h->picture_structure != PICT_BOTTOM_FIELD)
  2345. h->cur_pic_ptr->field_poc[0] = field_poc[0];
  2346. if (h->picture_structure != PICT_TOP_FIELD)
  2347. h->cur_pic_ptr->field_poc[1] = field_poc[1];
  2348. cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
  2349. return 0;
  2350. }
  2351. /**
  2352. * initialize scan tables
  2353. */
  2354. static void init_scan_tables(H264Context *h)
  2355. {
  2356. int i;
  2357. for (i = 0; i < 16; i++) {
  2358. #define T(x) (x >> 2) | ((x << 2) & 0xF)
  2359. h->zigzag_scan[i] = T(zigzag_scan[i]);
  2360. h->field_scan[i] = T(field_scan[i]);
  2361. #undef T
  2362. }
  2363. for (i = 0; i < 64; i++) {
  2364. #define T(x) (x >> 3) | ((x & 7) << 3)
  2365. h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
  2366. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  2367. h->field_scan8x8[i] = T(field_scan8x8[i]);
  2368. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  2369. #undef T
  2370. }
  2371. if (h->sps.transform_bypass) { // FIXME same ugly
  2372. memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  2373. memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
  2374. memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  2375. memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
  2376. memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2377. memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2378. } else {
  2379. memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  2380. memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
  2381. memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  2382. memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
  2383. memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2384. memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2385. }
  2386. }
  2387. static int field_end(H264Context *h, int in_setup)
  2388. {
  2389. AVCodecContext *const avctx = h->avctx;
  2390. int err = 0;
  2391. h->mb_y = 0;
  2392. if (!in_setup && !h->droppable)
  2393. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  2394. h->picture_structure == PICT_BOTTOM_FIELD);
  2395. if (CONFIG_H264_VDPAU_DECODER &&
  2396. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2397. ff_vdpau_h264_set_reference_frames(h);
  2398. if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
  2399. if (!h->droppable) {
  2400. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2401. h->prev_poc_msb = h->poc_msb;
  2402. h->prev_poc_lsb = h->poc_lsb;
  2403. }
  2404. h->prev_frame_num_offset = h->frame_num_offset;
  2405. h->prev_frame_num = h->frame_num;
  2406. h->outputed_poc = h->next_outputed_poc;
  2407. }
  2408. if (avctx->hwaccel) {
  2409. if (avctx->hwaccel->end_frame(avctx) < 0)
  2410. av_log(avctx, AV_LOG_ERROR,
  2411. "hardware accelerator failed to decode picture\n");
  2412. }
  2413. if (CONFIG_H264_VDPAU_DECODER &&
  2414. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2415. ff_vdpau_h264_picture_complete(h);
  2416. /*
  2417. * FIXME: Error handling code does not seem to support interlaced
  2418. * when slices span multiple rows
  2419. * The ff_er_add_slice calls don't work right for bottom
  2420. * fields; they cause massive erroneous error concealing
  2421. * Error marking covers both fields (top and bottom).
  2422. * This causes a mismatched s->error_count
  2423. * and a bad error table. Further, the error count goes to
  2424. * INT_MAX when called for bottom field, because mb_y is
  2425. * past end by one (callers fault) and resync_mb_y != 0
  2426. * causes problems for the first MB line, too.
  2427. */
  2428. if (!FIELD_PICTURE && h->current_slice && !h->sps.new) {
  2429. h->er.cur_pic = h->cur_pic_ptr;
  2430. h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
  2431. h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
  2432. ff_er_frame_end(&h->er);
  2433. }
  2434. emms_c();
  2435. h->current_slice = 0;
  2436. return err;
  2437. }
  2438. /**
  2439. * Replicate H264 "master" context to thread contexts.
  2440. */
  2441. static int clone_slice(H264Context *dst, H264Context *src)
  2442. {
  2443. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  2444. dst->cur_pic_ptr = src->cur_pic_ptr;
  2445. dst->cur_pic = src->cur_pic;
  2446. dst->linesize = src->linesize;
  2447. dst->uvlinesize = src->uvlinesize;
  2448. dst->first_field = src->first_field;
  2449. dst->prev_poc_msb = src->prev_poc_msb;
  2450. dst->prev_poc_lsb = src->prev_poc_lsb;
  2451. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  2452. dst->prev_frame_num = src->prev_frame_num;
  2453. dst->short_ref_count = src->short_ref_count;
  2454. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  2455. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  2456. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  2457. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  2458. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  2459. return 0;
  2460. }
  2461. /**
  2462. * Compute profile from profile_idc and constraint_set?_flags.
  2463. *
  2464. * @param sps SPS
  2465. *
  2466. * @return profile as defined by FF_PROFILE_H264_*
  2467. */
  2468. int ff_h264_get_profile(SPS *sps)
  2469. {
  2470. int profile = sps->profile_idc;
  2471. switch (sps->profile_idc) {
  2472. case FF_PROFILE_H264_BASELINE:
  2473. // constraint_set1_flag set to 1
  2474. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  2475. break;
  2476. case FF_PROFILE_H264_HIGH_10:
  2477. case FF_PROFILE_H264_HIGH_422:
  2478. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  2479. // constraint_set3_flag set to 1
  2480. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  2481. break;
  2482. }
  2483. return profile;
  2484. }
  2485. static int h264_set_parameter_from_sps(H264Context *h)
  2486. {
  2487. if (h->flags & CODEC_FLAG_LOW_DELAY ||
  2488. (h->sps.bitstream_restriction_flag &&
  2489. !h->sps.num_reorder_frames)) {
  2490. if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
  2491. av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
  2492. "Reenabling low delay requires a codec flush.\n");
  2493. else
  2494. h->low_delay = 1;
  2495. }
  2496. if (h->avctx->has_b_frames < 2)
  2497. h->avctx->has_b_frames = !h->low_delay;
  2498. if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2499. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  2500. if (h->avctx->codec &&
  2501. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
  2502. (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
  2503. av_log(h->avctx, AV_LOG_ERROR,
  2504. "VDPAU decoding does not support video colorspace.\n");
  2505. return AVERROR_INVALIDDATA;
  2506. }
  2507. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
  2508. h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
  2509. (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
  2510. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  2511. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  2512. h->pixel_shift = h->sps.bit_depth_luma > 8;
  2513. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  2514. h->sps.chroma_format_idc);
  2515. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  2516. ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
  2517. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
  2518. h->sps.chroma_format_idc);
  2519. h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
  2520. ff_dsputil_init(&h->dsp, h->avctx);
  2521. ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
  2522. } else {
  2523. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
  2524. h->sps.bit_depth_luma);
  2525. return AVERROR_INVALIDDATA;
  2526. }
  2527. }
  2528. return 0;
  2529. }
  2530. static enum PixelFormat get_pixel_format(H264Context *h)
  2531. {
  2532. switch (h->sps.bit_depth_luma) {
  2533. case 9:
  2534. if (CHROMA444) {
  2535. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2536. return AV_PIX_FMT_GBRP9;
  2537. } else
  2538. return AV_PIX_FMT_YUV444P9;
  2539. } else if (CHROMA422)
  2540. return AV_PIX_FMT_YUV422P9;
  2541. else
  2542. return AV_PIX_FMT_YUV420P9;
  2543. break;
  2544. case 10:
  2545. if (CHROMA444) {
  2546. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2547. return AV_PIX_FMT_GBRP10;
  2548. } else
  2549. return AV_PIX_FMT_YUV444P10;
  2550. } else if (CHROMA422)
  2551. return AV_PIX_FMT_YUV422P10;
  2552. else
  2553. return AV_PIX_FMT_YUV420P10;
  2554. break;
  2555. case 12:
  2556. if (CHROMA444) {
  2557. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2558. return AV_PIX_FMT_GBRP12;
  2559. } else
  2560. return AV_PIX_FMT_YUV444P12;
  2561. } else if (CHROMA422)
  2562. return AV_PIX_FMT_YUV422P12;
  2563. else
  2564. return AV_PIX_FMT_YUV420P12;
  2565. break;
  2566. case 14:
  2567. if (CHROMA444) {
  2568. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2569. return AV_PIX_FMT_GBRP14;
  2570. } else
  2571. return AV_PIX_FMT_YUV444P14;
  2572. } else if (CHROMA422)
  2573. return AV_PIX_FMT_YUV422P14;
  2574. else
  2575. return AV_PIX_FMT_YUV420P14;
  2576. break;
  2577. case 8:
  2578. if (CHROMA444) {
  2579. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2580. av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
  2581. return AV_PIX_FMT_GBR24P;
  2582. } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
  2583. av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
  2584. }
  2585. return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
  2586. : AV_PIX_FMT_YUV444P;
  2587. } else if (CHROMA422) {
  2588. return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
  2589. : AV_PIX_FMT_YUV422P;
  2590. } else {
  2591. int i;
  2592. const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
  2593. h->avctx->codec->pix_fmts :
  2594. h->avctx->color_range == AVCOL_RANGE_JPEG ?
  2595. hwaccel_pixfmt_list_h264_jpeg_420 :
  2596. hwaccel_pixfmt_list_h264_420;
  2597. for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
  2598. if (fmt[i] == h->avctx->pix_fmt)
  2599. return fmt[i];
  2600. return h->avctx->get_format(h->avctx, fmt);
  2601. }
  2602. break;
  2603. default:
  2604. av_log(h->avctx, AV_LOG_ERROR,
  2605. "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
  2606. return AVERROR_INVALIDDATA;
  2607. }
  2608. }
  2609. static int h264_slice_header_init(H264Context *h, int reinit)
  2610. {
  2611. int nb_slices = (HAVE_THREADS &&
  2612. h->avctx->active_thread_type & FF_THREAD_SLICE) ?
  2613. h->avctx->thread_count : 1;
  2614. int i;
  2615. if( FFALIGN(h->avctx->width , 16 ) == h->width
  2616. && FFALIGN(h->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == h->height
  2617. && !h->sps.crop_right && !h->sps.crop_bottom
  2618. && (h->avctx->width != h->width || h->avctx->height && h->height)
  2619. ) {
  2620. av_log(h->avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
  2621. h->avctx->coded_width = h->width;
  2622. h->avctx->coded_height = h->height;
  2623. } else{
  2624. avcodec_set_dimensions(h->avctx, h->width, h->height);
  2625. h->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
  2626. h->avctx->height -= (1<<h->chroma_y_shift)*FFMIN(h->sps.crop_bottom, (16>>h->chroma_y_shift)-1) * (2 - h->sps.frame_mbs_only_flag);
  2627. }
  2628. h->avctx->sample_aspect_ratio = h->sps.sar;
  2629. av_assert0(h->avctx->sample_aspect_ratio.den);
  2630. av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
  2631. &h->chroma_x_shift, &h->chroma_y_shift);
  2632. if (h->sps.timing_info_present_flag) {
  2633. int64_t den = h->sps.time_scale;
  2634. if (h->x264_build < 44U)
  2635. den *= 2;
  2636. av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
  2637. h->sps.num_units_in_tick, den, 1 << 30);
  2638. }
  2639. h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
  2640. if (reinit)
  2641. free_tables(h, 0);
  2642. h->first_field = 0;
  2643. h->prev_interlaced_frame = 1;
  2644. init_scan_tables(h);
  2645. if (ff_h264_alloc_tables(h) < 0) {
  2646. av_log(h->avctx, AV_LOG_ERROR,
  2647. "Could not allocate memory for h264\n");
  2648. return AVERROR(ENOMEM);
  2649. }
  2650. if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
  2651. int max_slices;
  2652. if (h->mb_height)
  2653. max_slices = FFMIN(MAX_THREADS, h->mb_height);
  2654. else
  2655. max_slices = MAX_THREADS;
  2656. av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
  2657. " reducing to %d\n", nb_slices, max_slices);
  2658. nb_slices = max_slices;
  2659. }
  2660. h->slice_context_count = nb_slices;
  2661. if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
  2662. if (context_init(h) < 0) {
  2663. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2664. return -1;
  2665. }
  2666. } else {
  2667. for (i = 1; i < h->slice_context_count; i++) {
  2668. H264Context *c;
  2669. c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
  2670. c->avctx = h->avctx;
  2671. c->dsp = h->dsp;
  2672. c->vdsp = h->vdsp;
  2673. c->h264dsp = h->h264dsp;
  2674. c->h264qpel = h->h264qpel;
  2675. c->h264chroma = h->h264chroma;
  2676. c->sps = h->sps;
  2677. c->pps = h->pps;
  2678. c->pixel_shift = h->pixel_shift;
  2679. c->cur_chroma_format_idc = h->cur_chroma_format_idc;
  2680. c->width = h->width;
  2681. c->height = h->height;
  2682. c->linesize = h->linesize;
  2683. c->uvlinesize = h->uvlinesize;
  2684. c->chroma_x_shift = h->chroma_x_shift;
  2685. c->chroma_y_shift = h->chroma_y_shift;
  2686. c->qscale = h->qscale;
  2687. c->droppable = h->droppable;
  2688. c->data_partitioning = h->data_partitioning;
  2689. c->low_delay = h->low_delay;
  2690. c->mb_width = h->mb_width;
  2691. c->mb_height = h->mb_height;
  2692. c->mb_stride = h->mb_stride;
  2693. c->mb_num = h->mb_num;
  2694. c->flags = h->flags;
  2695. c->workaround_bugs = h->workaround_bugs;
  2696. c->pict_type = h->pict_type;
  2697. init_scan_tables(c);
  2698. clone_tables(c, h, i);
  2699. c->context_initialized = 1;
  2700. }
  2701. for (i = 0; i < h->slice_context_count; i++)
  2702. if (context_init(h->thread_context[i]) < 0) {
  2703. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2704. return -1;
  2705. }
  2706. }
  2707. h->context_initialized = 1;
  2708. return 0;
  2709. }
  2710. /**
  2711. * Decode a slice header.
  2712. * This will also call ff_MPV_common_init() and frame_start() as needed.
  2713. *
  2714. * @param h h264context
  2715. * @param h0 h264 master context (differs from 'h' when doing sliced based
  2716. * parallel decoding)
  2717. *
  2718. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  2719. */
  2720. static int decode_slice_header(H264Context *h, H264Context *h0)
  2721. {
  2722. unsigned int first_mb_in_slice;
  2723. unsigned int pps_id;
  2724. int num_ref_idx_active_override_flag, ret;
  2725. unsigned int slice_type, tmp, i, j;
  2726. int default_ref_list_done = 0;
  2727. int last_pic_structure, last_pic_droppable;
  2728. int must_reinit;
  2729. int needs_reinit = 0;
  2730. h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
  2731. h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
  2732. first_mb_in_slice = get_ue_golomb_long(&h->gb);
  2733. if (first_mb_in_slice == 0) { // FIXME better field boundary detection
  2734. if (h0->current_slice && FIELD_PICTURE) {
  2735. field_end(h, 1);
  2736. }
  2737. h0->current_slice = 0;
  2738. if (!h0->first_field) {
  2739. if (h->cur_pic_ptr && !h->droppable &&
  2740. h->cur_pic_ptr->owner2 == h) {
  2741. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  2742. h->picture_structure == PICT_BOTTOM_FIELD);
  2743. }
  2744. h->cur_pic_ptr = NULL;
  2745. }
  2746. }
  2747. slice_type = get_ue_golomb_31(&h->gb);
  2748. if (slice_type > 9) {
  2749. av_log(h->avctx, AV_LOG_ERROR,
  2750. "slice type too large (%d) at %d %d\n",
  2751. slice_type, h->mb_x, h->mb_y);
  2752. return -1;
  2753. }
  2754. if (slice_type > 4) {
  2755. slice_type -= 5;
  2756. h->slice_type_fixed = 1;
  2757. } else
  2758. h->slice_type_fixed = 0;
  2759. slice_type = golomb_to_pict_type[slice_type];
  2760. if (slice_type == AV_PICTURE_TYPE_I ||
  2761. (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
  2762. default_ref_list_done = 1;
  2763. }
  2764. h->slice_type = slice_type;
  2765. h->slice_type_nos = slice_type & 3;
  2766. // to make a few old functions happy, it's wrong though
  2767. h->pict_type = h->slice_type;
  2768. pps_id = get_ue_golomb(&h->gb);
  2769. if (pps_id >= MAX_PPS_COUNT) {
  2770. av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
  2771. return -1;
  2772. }
  2773. if (!h0->pps_buffers[pps_id]) {
  2774. av_log(h->avctx, AV_LOG_ERROR,
  2775. "non-existing PPS %u referenced\n",
  2776. pps_id);
  2777. return -1;
  2778. }
  2779. h->pps = *h0->pps_buffers[pps_id];
  2780. if (!h0->sps_buffers[h->pps.sps_id]) {
  2781. av_log(h->avctx, AV_LOG_ERROR,
  2782. "non-existing SPS %u referenced\n",
  2783. h->pps.sps_id);
  2784. return -1;
  2785. }
  2786. if (h->pps.sps_id != h->current_sps_id ||
  2787. h0->sps_buffers[h->pps.sps_id]->new) {
  2788. h0->sps_buffers[h->pps.sps_id]->new = 0;
  2789. h->current_sps_id = h->pps.sps_id;
  2790. h->sps = *h0->sps_buffers[h->pps.sps_id];
  2791. if (h->mb_width != h->sps.mb_width ||
  2792. h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
  2793. h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2794. h->cur_chroma_format_idc != h->sps.chroma_format_idc
  2795. )
  2796. needs_reinit = 1;
  2797. if (h->bit_depth_luma != h->sps.bit_depth_luma ||
  2798. h->chroma_format_idc != h->sps.chroma_format_idc) {
  2799. h->bit_depth_luma = h->sps.bit_depth_luma;
  2800. h->chroma_format_idc = h->sps.chroma_format_idc;
  2801. needs_reinit = 1;
  2802. }
  2803. if ((ret = h264_set_parameter_from_sps(h)) < 0)
  2804. return ret;
  2805. }
  2806. h->avctx->profile = ff_h264_get_profile(&h->sps);
  2807. h->avctx->level = h->sps.level_idc;
  2808. h->avctx->refs = h->sps.ref_frame_count;
  2809. must_reinit = (h->context_initialized &&
  2810. ( 16*h->sps.mb_width != h->avctx->coded_width
  2811. || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
  2812. || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
  2813. || h->cur_chroma_format_idc != h->sps.chroma_format_idc
  2814. || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)));
  2815. if (h0->avctx->pix_fmt != get_pixel_format(h0))
  2816. must_reinit = 1;
  2817. h->mb_width = h->sps.mb_width;
  2818. h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  2819. h->mb_num = h->mb_width * h->mb_height;
  2820. h->mb_stride = h->mb_width + 1;
  2821. h->b_stride = h->mb_width * 4;
  2822. h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  2823. h->width = 16 * h->mb_width;
  2824. h->height = 16 * h->mb_height;
  2825. if (h->sps.video_signal_type_present_flag) {
  2826. h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
  2827. : AVCOL_RANGE_MPEG;
  2828. if (h->sps.colour_description_present_flag) {
  2829. if (h->avctx->colorspace != h->sps.colorspace)
  2830. needs_reinit = 1;
  2831. h->avctx->color_primaries = h->sps.color_primaries;
  2832. h->avctx->color_trc = h->sps.color_trc;
  2833. h->avctx->colorspace = h->sps.colorspace;
  2834. }
  2835. }
  2836. if (h->context_initialized &&
  2837. (
  2838. needs_reinit ||
  2839. must_reinit)) {
  2840. if (h != h0) {
  2841. av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
  2842. "slice %d\n", h0->current_slice + 1);
  2843. return AVERROR_INVALIDDATA;
  2844. }
  2845. flush_change(h);
  2846. if ((ret = get_pixel_format(h)) < 0)
  2847. return ret;
  2848. h->avctx->pix_fmt = ret;
  2849. av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
  2850. "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
  2851. if ((ret = h264_slice_header_init(h, 1)) < 0) {
  2852. av_log(h->avctx, AV_LOG_ERROR,
  2853. "h264_slice_header_init() failed\n");
  2854. return ret;
  2855. }
  2856. }
  2857. if (!h->context_initialized) {
  2858. if (h != h0) {
  2859. av_log(h->avctx, AV_LOG_ERROR,
  2860. "Cannot (re-)initialize context during parallel decoding.\n");
  2861. return -1;
  2862. }
  2863. if ((ret = get_pixel_format(h)) < 0)
  2864. return ret;
  2865. h->avctx->pix_fmt = ret;
  2866. if ((ret = h264_slice_header_init(h, 0)) < 0) {
  2867. av_log(h->avctx, AV_LOG_ERROR,
  2868. "h264_slice_header_init() failed\n");
  2869. return ret;
  2870. }
  2871. }
  2872. if (h == h0 && h->dequant_coeff_pps != pps_id) {
  2873. h->dequant_coeff_pps = pps_id;
  2874. init_dequant_tables(h);
  2875. }
  2876. h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
  2877. h->mb_mbaff = 0;
  2878. h->mb_aff_frame = 0;
  2879. last_pic_structure = h0->picture_structure;
  2880. last_pic_droppable = h0->droppable;
  2881. h->droppable = h->nal_ref_idc == 0;
  2882. if (h->sps.frame_mbs_only_flag) {
  2883. h->picture_structure = PICT_FRAME;
  2884. } else {
  2885. if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
  2886. av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
  2887. return -1;
  2888. }
  2889. if (get_bits1(&h->gb)) { // field_pic_flag
  2890. h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
  2891. } else {
  2892. h->picture_structure = PICT_FRAME;
  2893. h->mb_aff_frame = h->sps.mb_aff;
  2894. }
  2895. }
  2896. h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
  2897. if (h0->current_slice != 0) {
  2898. if (last_pic_structure != h->picture_structure ||
  2899. last_pic_droppable != h->droppable) {
  2900. av_log(h->avctx, AV_LOG_ERROR,
  2901. "Changing field mode (%d -> %d) between slices is not allowed\n",
  2902. last_pic_structure, h->picture_structure);
  2903. h->picture_structure = last_pic_structure;
  2904. h->droppable = last_pic_droppable;
  2905. return AVERROR_INVALIDDATA;
  2906. } else if (!h0->cur_pic_ptr) {
  2907. av_log(h->avctx, AV_LOG_ERROR,
  2908. "unset cur_pic_ptr on %d. slice\n",
  2909. h0->current_slice + 1);
  2910. return AVERROR_INVALIDDATA;
  2911. }
  2912. } else {
  2913. /* Shorten frame num gaps so we don't have to allocate reference
  2914. * frames just to throw them away */
  2915. if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
  2916. int unwrap_prev_frame_num = h->prev_frame_num;
  2917. int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2918. if (unwrap_prev_frame_num > h->frame_num)
  2919. unwrap_prev_frame_num -= max_frame_num;
  2920. if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
  2921. unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
  2922. if (unwrap_prev_frame_num < 0)
  2923. unwrap_prev_frame_num += max_frame_num;
  2924. h->prev_frame_num = unwrap_prev_frame_num;
  2925. }
  2926. }
  2927. /* See if we have a decoded first field looking for a pair...
  2928. * Here, we're using that to see if we should mark previously
  2929. * decode frames as "finished".
  2930. * We have to do that before the "dummy" in-between frame allocation,
  2931. * since that can modify h->cur_pic_ptr. */
  2932. if (h0->first_field) {
  2933. assert(h0->cur_pic_ptr);
  2934. assert(h0->cur_pic_ptr->f.data[0]);
  2935. assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
  2936. /* Mark old field/frame as completed */
  2937. if (!last_pic_droppable && h0->cur_pic_ptr->owner2 == h0) {
  2938. ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
  2939. last_pic_structure == PICT_BOTTOM_FIELD);
  2940. }
  2941. /* figure out if we have a complementary field pair */
  2942. if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
  2943. /* Previous field is unmatched. Don't display it, but let it
  2944. * remain for reference if marked as such. */
  2945. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  2946. ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
  2947. last_pic_structure == PICT_TOP_FIELD);
  2948. }
  2949. } else {
  2950. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  2951. /* This and previous field were reference, but had
  2952. * different frame_nums. Consider this field first in
  2953. * pair. Throw away previous field except for reference
  2954. * purposes. */
  2955. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  2956. ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
  2957. last_pic_structure == PICT_TOP_FIELD);
  2958. }
  2959. } else {
  2960. /* Second field in complementary pair */
  2961. if (!((last_pic_structure == PICT_TOP_FIELD &&
  2962. h->picture_structure == PICT_BOTTOM_FIELD) ||
  2963. (last_pic_structure == PICT_BOTTOM_FIELD &&
  2964. h->picture_structure == PICT_TOP_FIELD))) {
  2965. av_log(h->avctx, AV_LOG_ERROR,
  2966. "Invalid field mode combination %d/%d\n",
  2967. last_pic_structure, h->picture_structure);
  2968. h->picture_structure = last_pic_structure;
  2969. h->droppable = last_pic_droppable;
  2970. return AVERROR_INVALIDDATA;
  2971. } else if (last_pic_droppable != h->droppable) {
  2972. av_log(h->avctx, AV_LOG_ERROR,
  2973. "Cannot combine reference and non-reference fields in the same frame\n");
  2974. av_log_ask_for_sample(h->avctx, NULL);
  2975. h->picture_structure = last_pic_structure;
  2976. h->droppable = last_pic_droppable;
  2977. return AVERROR_PATCHWELCOME;
  2978. }
  2979. /* Take ownership of this buffer. Note that if another thread owned
  2980. * the first field of this buffer, we're not operating on that pointer,
  2981. * so the original thread is still responsible for reporting progress
  2982. * on that first field (or if that was us, we just did that above).
  2983. * By taking ownership, we assign responsibility to ourselves to
  2984. * report progress on the second field. */
  2985. h0->cur_pic_ptr->owner2 = h0;
  2986. }
  2987. }
  2988. }
  2989. while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !h0->first_field &&
  2990. h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
  2991. Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2992. av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  2993. h->frame_num, h->prev_frame_num);
  2994. if (!h->sps.gaps_in_frame_num_allowed_flag)
  2995. for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
  2996. h->last_pocs[i] = INT_MIN;
  2997. if (ff_h264_frame_start(h) < 0)
  2998. return -1;
  2999. h->prev_frame_num++;
  3000. h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
  3001. h->cur_pic_ptr->frame_num = h->prev_frame_num;
  3002. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 0);
  3003. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 1);
  3004. if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
  3005. h->avctx->err_recognition & AV_EF_EXPLODE)
  3006. return ret;
  3007. if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
  3008. (h->avctx->err_recognition & AV_EF_EXPLODE))
  3009. return AVERROR_INVALIDDATA;
  3010. /* Error concealment: if a ref is missing, copy the previous ref in its place.
  3011. * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
  3012. * about there being no actual duplicates.
  3013. * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
  3014. * concealing a lost frame, this probably isn't noticeable by comparison, but it should
  3015. * be fixed. */
  3016. if (h->short_ref_count) {
  3017. if (prev) {
  3018. av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
  3019. (const uint8_t **)prev->f.data, prev->f.linesize,
  3020. h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16);
  3021. h->short_ref[0]->poc = prev->poc + 2;
  3022. }
  3023. h->short_ref[0]->frame_num = h->prev_frame_num;
  3024. }
  3025. }
  3026. /* See if we have a decoded first field looking for a pair...
  3027. * We're using that to see whether to continue decoding in that
  3028. * frame, or to allocate a new one. */
  3029. if (h0->first_field) {
  3030. assert(h0->cur_pic_ptr);
  3031. assert(h0->cur_pic_ptr->f.data[0]);
  3032. assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
  3033. /* figure out if we have a complementary field pair */
  3034. if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
  3035. /* Previous field is unmatched. Don't display it, but let it
  3036. * remain for reference if marked as such. */
  3037. h0->cur_pic_ptr = NULL;
  3038. h0->first_field = FIELD_PICTURE;
  3039. } else {
  3040. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  3041. ff_thread_report_progress((AVFrame*)h0->cur_pic_ptr, INT_MAX,
  3042. h0->picture_structure==PICT_BOTTOM_FIELD);
  3043. /* This and the previous field had different frame_nums.
  3044. * Consider this field first in pair. Throw away previous
  3045. * one except for reference purposes. */
  3046. h0->first_field = 1;
  3047. h0->cur_pic_ptr = NULL;
  3048. } else {
  3049. /* Second field in complementary pair */
  3050. h0->first_field = 0;
  3051. }
  3052. }
  3053. } else {
  3054. /* Frame or first field in a potentially complementary pair */
  3055. h0->first_field = FIELD_PICTURE;
  3056. }
  3057. if (!FIELD_PICTURE || h0->first_field) {
  3058. if (ff_h264_frame_start(h) < 0) {
  3059. h0->first_field = 0;
  3060. return -1;
  3061. }
  3062. } else {
  3063. release_unused_pictures(h, 0);
  3064. }
  3065. }
  3066. if (h != h0 && (ret = clone_slice(h, h0)) < 0)
  3067. return ret;
  3068. h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
  3069. av_assert1(h->mb_num == h->mb_width * h->mb_height);
  3070. if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= h->mb_num ||
  3071. first_mb_in_slice >= h->mb_num) {
  3072. av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  3073. return -1;
  3074. }
  3075. h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
  3076. h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE;
  3077. if (h->picture_structure == PICT_BOTTOM_FIELD)
  3078. h->resync_mb_y = h->mb_y = h->mb_y + 1;
  3079. av_assert1(h->mb_y < h->mb_height);
  3080. if (h->picture_structure == PICT_FRAME) {
  3081. h->curr_pic_num = h->frame_num;
  3082. h->max_pic_num = 1 << h->sps.log2_max_frame_num;
  3083. } else {
  3084. h->curr_pic_num = 2 * h->frame_num + 1;
  3085. h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
  3086. }
  3087. if (h->nal_unit_type == NAL_IDR_SLICE)
  3088. get_ue_golomb(&h->gb); /* idr_pic_id */
  3089. if (h->sps.poc_type == 0) {
  3090. h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
  3091. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  3092. h->delta_poc_bottom = get_se_golomb(&h->gb);
  3093. }
  3094. if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
  3095. h->delta_poc[0] = get_se_golomb(&h->gb);
  3096. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  3097. h->delta_poc[1] = get_se_golomb(&h->gb);
  3098. }
  3099. init_poc(h);
  3100. if (h->pps.redundant_pic_cnt_present)
  3101. h->redundant_pic_count = get_ue_golomb(&h->gb);
  3102. // set defaults, might be overridden a few lines later
  3103. h->ref_count[0] = h->pps.ref_count[0];
  3104. h->ref_count[1] = h->pps.ref_count[1];
  3105. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  3106. unsigned max[2];
  3107. max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
  3108. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  3109. h->direct_spatial_mv_pred = get_bits1(&h->gb);
  3110. num_ref_idx_active_override_flag = get_bits1(&h->gb);
  3111. if (num_ref_idx_active_override_flag) {
  3112. h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
  3113. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3114. h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
  3115. } else
  3116. // full range is spec-ok in this case, even for frames
  3117. h->ref_count[1] = 1;
  3118. }
  3119. if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
  3120. av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", h->ref_count[0]-1, max[0], h->ref_count[1]-1, max[1]);
  3121. h->ref_count[0] = h->ref_count[1] = 1;
  3122. return AVERROR_INVALIDDATA;
  3123. }
  3124. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  3125. h->list_count = 2;
  3126. else
  3127. h->list_count = 1;
  3128. } else
  3129. h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
  3130. if (!default_ref_list_done)
  3131. ff_h264_fill_default_ref_list(h);
  3132. if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
  3133. ff_h264_decode_ref_pic_list_reordering(h) < 0) {
  3134. h->ref_count[1] = h->ref_count[0] = 0;
  3135. return -1;
  3136. }
  3137. if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
  3138. (h->pps.weighted_bipred_idc == 1 &&
  3139. h->slice_type_nos == AV_PICTURE_TYPE_B))
  3140. pred_weight_table(h);
  3141. else if (h->pps.weighted_bipred_idc == 2 &&
  3142. h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3143. implicit_weight_table(h, -1);
  3144. } else {
  3145. h->use_weight = 0;
  3146. for (i = 0; i < 2; i++) {
  3147. h->luma_weight_flag[i] = 0;
  3148. h->chroma_weight_flag[i] = 0;
  3149. }
  3150. }
  3151. // If frame-mt is enabled, only update mmco tables for the first slice
  3152. // in a field. Subsequent slices can temporarily clobber h->mmco_index
  3153. // or h->mmco, which will cause ref list mix-ups and decoding errors
  3154. // further down the line. This may break decoding if the first slice is
  3155. // corrupt, thus we only do this if frame-mt is enabled.
  3156. if (h->nal_ref_idc &&
  3157. ff_h264_decode_ref_pic_marking(h0, &h->gb,
  3158. !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
  3159. h0->current_slice == 0) < 0 &&
  3160. (h->avctx->err_recognition & AV_EF_EXPLODE))
  3161. return AVERROR_INVALIDDATA;
  3162. if (FRAME_MBAFF) {
  3163. ff_h264_fill_mbaff_ref_list(h);
  3164. if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3165. implicit_weight_table(h, 0);
  3166. implicit_weight_table(h, 1);
  3167. }
  3168. }
  3169. if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
  3170. ff_h264_direct_dist_scale_factor(h);
  3171. ff_h264_direct_ref_list_init(h);
  3172. if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
  3173. tmp = get_ue_golomb_31(&h->gb);
  3174. if (tmp > 2) {
  3175. av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  3176. return -1;
  3177. }
  3178. h->cabac_init_idc = tmp;
  3179. }
  3180. h->last_qscale_diff = 0;
  3181. tmp = h->pps.init_qp + get_se_golomb(&h->gb);
  3182. if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
  3183. av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  3184. return -1;
  3185. }
  3186. h->qscale = tmp;
  3187. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  3188. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  3189. // FIXME qscale / qp ... stuff
  3190. if (h->slice_type == AV_PICTURE_TYPE_SP)
  3191. get_bits1(&h->gb); /* sp_for_switch_flag */
  3192. if (h->slice_type == AV_PICTURE_TYPE_SP ||
  3193. h->slice_type == AV_PICTURE_TYPE_SI)
  3194. get_se_golomb(&h->gb); /* slice_qs_delta */
  3195. h->deblocking_filter = 1;
  3196. h->slice_alpha_c0_offset = 52;
  3197. h->slice_beta_offset = 52;
  3198. if (h->pps.deblocking_filter_parameters_present) {
  3199. tmp = get_ue_golomb_31(&h->gb);
  3200. if (tmp > 2) {
  3201. av_log(h->avctx, AV_LOG_ERROR,
  3202. "deblocking_filter_idc %u out of range\n", tmp);
  3203. return -1;
  3204. }
  3205. h->deblocking_filter = tmp;
  3206. if (h->deblocking_filter < 2)
  3207. h->deblocking_filter ^= 1; // 1<->0
  3208. if (h->deblocking_filter) {
  3209. h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
  3210. h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
  3211. if (h->slice_alpha_c0_offset > 104U ||
  3212. h->slice_beta_offset > 104U) {
  3213. av_log(h->avctx, AV_LOG_ERROR,
  3214. "deblocking filter parameters %d %d out of range\n",
  3215. h->slice_alpha_c0_offset, h->slice_beta_offset);
  3216. return -1;
  3217. }
  3218. }
  3219. }
  3220. if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  3221. (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  3222. h->slice_type_nos != AV_PICTURE_TYPE_I) ||
  3223. (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  3224. h->slice_type_nos == AV_PICTURE_TYPE_B) ||
  3225. (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  3226. h->nal_ref_idc == 0))
  3227. h->deblocking_filter = 0;
  3228. if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
  3229. if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
  3230. /* Cheat slightly for speed:
  3231. * Do not bother to deblock across slices. */
  3232. h->deblocking_filter = 2;
  3233. } else {
  3234. h0->max_contexts = 1;
  3235. if (!h0->single_decode_warning) {
  3236. av_log(h->avctx, AV_LOG_INFO,
  3237. "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  3238. h0->single_decode_warning = 1;
  3239. }
  3240. if (h != h0) {
  3241. av_log(h->avctx, AV_LOG_ERROR,
  3242. "Deblocking switched inside frame.\n");
  3243. return 1;
  3244. }
  3245. }
  3246. }
  3247. h->qp_thresh = 15 + 52 -
  3248. FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
  3249. FFMAX3(0,
  3250. h->pps.chroma_qp_index_offset[0],
  3251. h->pps.chroma_qp_index_offset[1]) +
  3252. 6 * (h->sps.bit_depth_luma - 8);
  3253. h0->last_slice_type = slice_type;
  3254. h->slice_num = ++h0->current_slice;
  3255. if (h->slice_num)
  3256. h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
  3257. if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
  3258. && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
  3259. && h->slice_num >= MAX_SLICES) {
  3260. //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
  3261. av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
  3262. }
  3263. for (j = 0; j < 2; j++) {
  3264. int id_list[16];
  3265. int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
  3266. for (i = 0; i < 16; i++) {
  3267. id_list[i] = 60;
  3268. if (h->ref_list[j][i].f.data[0]) {
  3269. int k;
  3270. uint8_t *base = h->ref_list[j][i].f.base[0];
  3271. for (k = 0; k < h->short_ref_count; k++)
  3272. if (h->short_ref[k]->f.base[0] == base) {
  3273. id_list[i] = k;
  3274. break;
  3275. }
  3276. for (k = 0; k < h->long_ref_count; k++)
  3277. if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
  3278. id_list[i] = h->short_ref_count + k;
  3279. break;
  3280. }
  3281. }
  3282. }
  3283. ref2frm[0] =
  3284. ref2frm[1] = -1;
  3285. for (i = 0; i < 16; i++)
  3286. ref2frm[i + 2] = 4 * id_list[i] +
  3287. (h->ref_list[j][i].f.reference & 3);
  3288. ref2frm[18 + 0] =
  3289. ref2frm[18 + 1] = -1;
  3290. for (i = 16; i < 48; i++)
  3291. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  3292. (h->ref_list[j][i].f.reference & 3);
  3293. }
  3294. if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
  3295. av_log(h->avctx, AV_LOG_DEBUG,
  3296. "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
  3297. h->slice_num,
  3298. (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  3299. first_mb_in_slice,
  3300. av_get_picture_type_char(h->slice_type),
  3301. h->slice_type_fixed ? " fix" : "",
  3302. h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  3303. pps_id, h->frame_num,
  3304. h->cur_pic_ptr->field_poc[0],
  3305. h->cur_pic_ptr->field_poc[1],
  3306. h->ref_count[0], h->ref_count[1],
  3307. h->qscale,
  3308. h->deblocking_filter,
  3309. h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
  3310. h->use_weight,
  3311. h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
  3312. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  3313. }
  3314. return 0;
  3315. }
  3316. int ff_h264_get_slice_type(const H264Context *h)
  3317. {
  3318. switch (h->slice_type) {
  3319. case AV_PICTURE_TYPE_P:
  3320. return 0;
  3321. case AV_PICTURE_TYPE_B:
  3322. return 1;
  3323. case AV_PICTURE_TYPE_I:
  3324. return 2;
  3325. case AV_PICTURE_TYPE_SP:
  3326. return 3;
  3327. case AV_PICTURE_TYPE_SI:
  3328. return 4;
  3329. default:
  3330. return -1;
  3331. }
  3332. }
  3333. static av_always_inline void fill_filter_caches_inter(H264Context *h,
  3334. int mb_type, int top_xy,
  3335. int left_xy[LEFT_MBS],
  3336. int top_type,
  3337. int left_type[LEFT_MBS],
  3338. int mb_xy, int list)
  3339. {
  3340. int b_stride = h->b_stride;
  3341. int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
  3342. int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
  3343. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  3344. if (USES_LIST(top_type, list)) {
  3345. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  3346. const int b8_xy = 4 * top_xy + 2;
  3347. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  3348. AV_COPY128(mv_dst - 1 * 8, h->cur_pic.f.motion_val[list][b_xy + 0]);
  3349. ref_cache[0 - 1 * 8] =
  3350. ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 0]];
  3351. ref_cache[2 - 1 * 8] =
  3352. ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 1]];
  3353. } else {
  3354. AV_ZERO128(mv_dst - 1 * 8);
  3355. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3356. }
  3357. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  3358. if (USES_LIST(left_type[LTOP], list)) {
  3359. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  3360. const int b8_xy = 4 * left_xy[LTOP] + 1;
  3361. int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  3362. AV_COPY32(mv_dst - 1 + 0, h->cur_pic.f.motion_val[list][b_xy + b_stride * 0]);
  3363. AV_COPY32(mv_dst - 1 + 8, h->cur_pic.f.motion_val[list][b_xy + b_stride * 1]);
  3364. AV_COPY32(mv_dst - 1 + 16, h->cur_pic.f.motion_val[list][b_xy + b_stride * 2]);
  3365. AV_COPY32(mv_dst - 1 + 24, h->cur_pic.f.motion_val[list][b_xy + b_stride * 3]);
  3366. ref_cache[-1 + 0] =
  3367. ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 0]];
  3368. ref_cache[-1 + 16] =
  3369. ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 1]];
  3370. } else {
  3371. AV_ZERO32(mv_dst - 1 + 0);
  3372. AV_ZERO32(mv_dst - 1 + 8);
  3373. AV_ZERO32(mv_dst - 1 + 16);
  3374. AV_ZERO32(mv_dst - 1 + 24);
  3375. ref_cache[-1 + 0] =
  3376. ref_cache[-1 + 8] =
  3377. ref_cache[-1 + 16] =
  3378. ref_cache[-1 + 24] = LIST_NOT_USED;
  3379. }
  3380. }
  3381. }
  3382. if (!USES_LIST(mb_type, list)) {
  3383. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  3384. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3385. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3386. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3387. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3388. return;
  3389. }
  3390. {
  3391. int8_t *ref = &h->cur_pic.f.ref_index[list][4 * mb_xy];
  3392. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  3393. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
  3394. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
  3395. AV_WN32A(&ref_cache[0 * 8], ref01);
  3396. AV_WN32A(&ref_cache[1 * 8], ref01);
  3397. AV_WN32A(&ref_cache[2 * 8], ref23);
  3398. AV_WN32A(&ref_cache[3 * 8], ref23);
  3399. }
  3400. {
  3401. int16_t(*mv_src)[2] = &h->cur_pic.f.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
  3402. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  3403. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  3404. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  3405. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  3406. }
  3407. }
  3408. /**
  3409. *
  3410. * @return non zero if the loop filter can be skipped
  3411. */
  3412. static int fill_filter_caches(H264Context *h, int mb_type)
  3413. {
  3414. const int mb_xy = h->mb_xy;
  3415. int top_xy, left_xy[LEFT_MBS];
  3416. int top_type, left_type[LEFT_MBS];
  3417. uint8_t *nnz;
  3418. uint8_t *nnz_cache;
  3419. top_xy = mb_xy - (h->mb_stride << MB_FIELD);
  3420. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  3421. * stuff, I can't imagine that these complex rules are worth it. */
  3422. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  3423. if (FRAME_MBAFF) {
  3424. const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.f.mb_type[mb_xy - 1]);
  3425. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  3426. if (h->mb_y & 1) {
  3427. if (left_mb_field_flag != curr_mb_field_flag)
  3428. left_xy[LTOP] -= h->mb_stride;
  3429. } else {
  3430. if (curr_mb_field_flag)
  3431. top_xy += h->mb_stride &
  3432. (((h->cur_pic.f.mb_type[top_xy] >> 7) & 1) - 1);
  3433. if (left_mb_field_flag != curr_mb_field_flag)
  3434. left_xy[LBOT] += h->mb_stride;
  3435. }
  3436. }
  3437. h->top_mb_xy = top_xy;
  3438. h->left_mb_xy[LTOP] = left_xy[LTOP];
  3439. h->left_mb_xy[LBOT] = left_xy[LBOT];
  3440. {
  3441. /* For sufficiently low qp, filtering wouldn't do anything.
  3442. * This is a conservative estimate: could also check beta_offset
  3443. * and more accurate chroma_qp. */
  3444. int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  3445. int qp = h->cur_pic.f.qscale_table[mb_xy];
  3446. if (qp <= qp_thresh &&
  3447. (left_xy[LTOP] < 0 ||
  3448. ((qp + h->cur_pic.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  3449. (top_xy < 0 ||
  3450. ((qp + h->cur_pic.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  3451. if (!FRAME_MBAFF)
  3452. return 1;
  3453. if ((left_xy[LTOP] < 0 ||
  3454. ((qp + h->cur_pic.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  3455. (top_xy < h->mb_stride ||
  3456. ((qp + h->cur_pic.f.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
  3457. return 1;
  3458. }
  3459. }
  3460. top_type = h->cur_pic.f.mb_type[top_xy];
  3461. left_type[LTOP] = h->cur_pic.f.mb_type[left_xy[LTOP]];
  3462. left_type[LBOT] = h->cur_pic.f.mb_type[left_xy[LBOT]];
  3463. if (h->deblocking_filter == 2) {
  3464. if (h->slice_table[top_xy] != h->slice_num)
  3465. top_type = 0;
  3466. if (h->slice_table[left_xy[LBOT]] != h->slice_num)
  3467. left_type[LTOP] = left_type[LBOT] = 0;
  3468. } else {
  3469. if (h->slice_table[top_xy] == 0xFFFF)
  3470. top_type = 0;
  3471. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  3472. left_type[LTOP] = left_type[LBOT] = 0;
  3473. }
  3474. h->top_type = top_type;
  3475. h->left_type[LTOP] = left_type[LTOP];
  3476. h->left_type[LBOT] = left_type[LBOT];
  3477. if (IS_INTRA(mb_type))
  3478. return 0;
  3479. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3480. top_type, left_type, mb_xy, 0);
  3481. if (h->list_count == 2)
  3482. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3483. top_type, left_type, mb_xy, 1);
  3484. nnz = h->non_zero_count[mb_xy];
  3485. nnz_cache = h->non_zero_count_cache;
  3486. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  3487. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  3488. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  3489. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  3490. h->cbp = h->cbp_table[mb_xy];
  3491. if (top_type) {
  3492. nnz = h->non_zero_count[top_xy];
  3493. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  3494. }
  3495. if (left_type[LTOP]) {
  3496. nnz = h->non_zero_count[left_xy[LTOP]];
  3497. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  3498. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  3499. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  3500. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  3501. }
  3502. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  3503. * from what the loop filter needs */
  3504. if (!CABAC && h->pps.transform_8x8_mode) {
  3505. if (IS_8x8DCT(top_type)) {
  3506. nnz_cache[4 + 8 * 0] =
  3507. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  3508. nnz_cache[6 + 8 * 0] =
  3509. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  3510. }
  3511. if (IS_8x8DCT(left_type[LTOP])) {
  3512. nnz_cache[3 + 8 * 1] =
  3513. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  3514. }
  3515. if (IS_8x8DCT(left_type[LBOT])) {
  3516. nnz_cache[3 + 8 * 3] =
  3517. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  3518. }
  3519. if (IS_8x8DCT(mb_type)) {
  3520. nnz_cache[scan8[0]] =
  3521. nnz_cache[scan8[1]] =
  3522. nnz_cache[scan8[2]] =
  3523. nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
  3524. nnz_cache[scan8[0 + 4]] =
  3525. nnz_cache[scan8[1 + 4]] =
  3526. nnz_cache[scan8[2 + 4]] =
  3527. nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
  3528. nnz_cache[scan8[0 + 8]] =
  3529. nnz_cache[scan8[1 + 8]] =
  3530. nnz_cache[scan8[2 + 8]] =
  3531. nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
  3532. nnz_cache[scan8[0 + 12]] =
  3533. nnz_cache[scan8[1 + 12]] =
  3534. nnz_cache[scan8[2 + 12]] =
  3535. nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
  3536. }
  3537. }
  3538. return 0;
  3539. }
  3540. static void loop_filter(H264Context *h, int start_x, int end_x)
  3541. {
  3542. uint8_t *dest_y, *dest_cb, *dest_cr;
  3543. int linesize, uvlinesize, mb_x, mb_y;
  3544. const int end_mb_y = h->mb_y + FRAME_MBAFF;
  3545. const int old_slice_type = h->slice_type;
  3546. const int pixel_shift = h->pixel_shift;
  3547. const int block_h = 16 >> h->chroma_y_shift;
  3548. if (h->deblocking_filter) {
  3549. for (mb_x = start_x; mb_x < end_x; mb_x++)
  3550. for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
  3551. int mb_xy, mb_type;
  3552. mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
  3553. h->slice_num = h->slice_table[mb_xy];
  3554. mb_type = h->cur_pic.f.mb_type[mb_xy];
  3555. h->list_count = h->list_counts[mb_xy];
  3556. if (FRAME_MBAFF)
  3557. h->mb_mbaff =
  3558. h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  3559. h->mb_x = mb_x;
  3560. h->mb_y = mb_y;
  3561. dest_y = h->cur_pic.f.data[0] +
  3562. ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
  3563. dest_cb = h->cur_pic.f.data[1] +
  3564. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3565. mb_y * h->uvlinesize * block_h;
  3566. dest_cr = h->cur_pic.f.data[2] +
  3567. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3568. mb_y * h->uvlinesize * block_h;
  3569. // FIXME simplify above
  3570. if (MB_FIELD) {
  3571. linesize = h->mb_linesize = h->linesize * 2;
  3572. uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
  3573. if (mb_y & 1) { // FIXME move out of this function?
  3574. dest_y -= h->linesize * 15;
  3575. dest_cb -= h->uvlinesize * (block_h - 1);
  3576. dest_cr -= h->uvlinesize * (block_h - 1);
  3577. }
  3578. } else {
  3579. linesize = h->mb_linesize = h->linesize;
  3580. uvlinesize = h->mb_uvlinesize = h->uvlinesize;
  3581. }
  3582. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
  3583. uvlinesize, 0);
  3584. if (fill_filter_caches(h, mb_type))
  3585. continue;
  3586. h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.f.qscale_table[mb_xy]);
  3587. h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.f.qscale_table[mb_xy]);
  3588. if (FRAME_MBAFF) {
  3589. ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  3590. linesize, uvlinesize);
  3591. } else {
  3592. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
  3593. dest_cr, linesize, uvlinesize);
  3594. }
  3595. }
  3596. }
  3597. h->slice_type = old_slice_type;
  3598. h->mb_x = end_x;
  3599. h->mb_y = end_mb_y - FRAME_MBAFF;
  3600. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  3601. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  3602. }
  3603. static void predict_field_decoding_flag(H264Context *h)
  3604. {
  3605. const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
  3606. int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
  3607. h->cur_pic.f.mb_type[mb_xy - 1] :
  3608. (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
  3609. h->cur_pic.f.mb_type[mb_xy - h->mb_stride] : 0;
  3610. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3611. }
  3612. /**
  3613. * Draw edges and report progress for the last MB row.
  3614. */
  3615. static void decode_finish_row(H264Context *h)
  3616. {
  3617. int top = 16 * (h->mb_y >> FIELD_PICTURE);
  3618. int pic_height = 16 * h->mb_height >> FIELD_PICTURE;
  3619. int height = 16 << FRAME_MBAFF;
  3620. int deblock_border = (16 + 4) << FRAME_MBAFF;
  3621. if (h->deblocking_filter) {
  3622. if ((top + height) >= pic_height)
  3623. height += deblock_border;
  3624. top -= deblock_border;
  3625. }
  3626. if (top >= pic_height || (top + height) < 0)
  3627. return;
  3628. height = FFMIN(height, pic_height - top);
  3629. if (top < 0) {
  3630. height = top + height;
  3631. top = 0;
  3632. }
  3633. ff_h264_draw_horiz_band(h, top, height);
  3634. if (h->droppable)
  3635. return;
  3636. ff_thread_report_progress(&h->cur_pic_ptr->f, top + height - 1,
  3637. h->picture_structure == PICT_BOTTOM_FIELD);
  3638. }
  3639. static void er_add_slice(H264Context *h, int startx, int starty,
  3640. int endx, int endy, int status)
  3641. {
  3642. ERContext *er = &h->er;
  3643. er->ref_count = h->ref_count[0];
  3644. ff_er_add_slice(er, startx, starty, endx, endy, status);
  3645. }
  3646. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  3647. {
  3648. H264Context *h = *(void **)arg;
  3649. int lf_x_start = h->mb_x;
  3650. h->mb_skip_run = -1;
  3651. av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
  3652. h->is_complex = FRAME_MBAFF || h->picture_structure != PICT_FRAME ||
  3653. avctx->codec_id != AV_CODEC_ID_H264 ||
  3654. (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
  3655. if (h->pps.cabac) {
  3656. /* realign */
  3657. align_get_bits(&h->gb);
  3658. /* init cabac */
  3659. ff_init_cabac_decoder(&h->cabac,
  3660. h->gb.buffer + get_bits_count(&h->gb) / 8,
  3661. (get_bits_left(&h->gb) + 7) / 8);
  3662. ff_h264_init_cabac_states(h);
  3663. for (;;) {
  3664. // START_TIMER
  3665. int ret = ff_h264_decode_mb_cabac(h);
  3666. int eos;
  3667. // STOP_TIMER("decode_mb_cabac")
  3668. if (ret >= 0)
  3669. ff_h264_hl_decode_mb(h);
  3670. // FIXME optimal? or let mb_decode decode 16x32 ?
  3671. if (ret >= 0 && FRAME_MBAFF) {
  3672. h->mb_y++;
  3673. ret = ff_h264_decode_mb_cabac(h);
  3674. if (ret >= 0)
  3675. ff_h264_hl_decode_mb(h);
  3676. h->mb_y--;
  3677. }
  3678. eos = get_cabac_terminate(&h->cabac);
  3679. if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
  3680. h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3681. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  3682. h->mb_y, ER_MB_END);
  3683. if (h->mb_x >= lf_x_start)
  3684. loop_filter(h, lf_x_start, h->mb_x + 1);
  3685. return 0;
  3686. }
  3687. if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
  3688. av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
  3689. if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
  3690. av_log(h->avctx, AV_LOG_ERROR,
  3691. "error while decoding MB %d %d, bytestream (%td)\n",
  3692. h->mb_x, h->mb_y,
  3693. h->cabac.bytestream_end - h->cabac.bytestream);
  3694. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3695. h->mb_y, ER_MB_ERROR);
  3696. return -1;
  3697. }
  3698. if (++h->mb_x >= h->mb_width) {
  3699. loop_filter(h, lf_x_start, h->mb_x);
  3700. h->mb_x = lf_x_start = 0;
  3701. decode_finish_row(h);
  3702. ++h->mb_y;
  3703. if (FIELD_OR_MBAFF_PICTURE) {
  3704. ++h->mb_y;
  3705. if (FRAME_MBAFF && h->mb_y < h->mb_height)
  3706. predict_field_decoding_flag(h);
  3707. }
  3708. }
  3709. if (eos || h->mb_y >= h->mb_height) {
  3710. tprintf(h->avctx, "slice end %d %d\n",
  3711. get_bits_count(&h->gb), h->gb.size_in_bits);
  3712. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  3713. h->mb_y, ER_MB_END);
  3714. if (h->mb_x > lf_x_start)
  3715. loop_filter(h, lf_x_start, h->mb_x);
  3716. return 0;
  3717. }
  3718. }
  3719. } else {
  3720. for (;;) {
  3721. int ret = ff_h264_decode_mb_cavlc(h);
  3722. if (ret >= 0)
  3723. ff_h264_hl_decode_mb(h);
  3724. // FIXME optimal? or let mb_decode decode 16x32 ?
  3725. if (ret >= 0 && FRAME_MBAFF) {
  3726. h->mb_y++;
  3727. ret = ff_h264_decode_mb_cavlc(h);
  3728. if (ret >= 0)
  3729. ff_h264_hl_decode_mb(h);
  3730. h->mb_y--;
  3731. }
  3732. if (ret < 0) {
  3733. av_log(h->avctx, AV_LOG_ERROR,
  3734. "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
  3735. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3736. h->mb_y, ER_MB_ERROR);
  3737. return -1;
  3738. }
  3739. if (++h->mb_x >= h->mb_width) {
  3740. loop_filter(h, lf_x_start, h->mb_x);
  3741. h->mb_x = lf_x_start = 0;
  3742. decode_finish_row(h);
  3743. ++h->mb_y;
  3744. if (FIELD_OR_MBAFF_PICTURE) {
  3745. ++h->mb_y;
  3746. if (FRAME_MBAFF && h->mb_y < h->mb_height)
  3747. predict_field_decoding_flag(h);
  3748. }
  3749. if (h->mb_y >= h->mb_height) {
  3750. tprintf(h->avctx, "slice end %d %d\n",
  3751. get_bits_count(&h->gb), h->gb.size_in_bits);
  3752. if ( get_bits_left(&h->gb) == 0
  3753. || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
  3754. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3755. h->mb_x - 1, h->mb_y,
  3756. ER_MB_END);
  3757. return 0;
  3758. } else {
  3759. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3760. h->mb_x, h->mb_y,
  3761. ER_MB_END);
  3762. return -1;
  3763. }
  3764. }
  3765. }
  3766. if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
  3767. tprintf(h->avctx, "slice end %d %d\n",
  3768. get_bits_count(&h->gb), h->gb.size_in_bits);
  3769. if (get_bits_left(&h->gb) == 0) {
  3770. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3771. h->mb_x - 1, h->mb_y,
  3772. ER_MB_END);
  3773. if (h->mb_x > lf_x_start)
  3774. loop_filter(h, lf_x_start, h->mb_x);
  3775. return 0;
  3776. } else {
  3777. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3778. h->mb_y, ER_MB_ERROR);
  3779. return -1;
  3780. }
  3781. }
  3782. }
  3783. }
  3784. }
  3785. /**
  3786. * Call decode_slice() for each context.
  3787. *
  3788. * @param h h264 master context
  3789. * @param context_count number of contexts to execute
  3790. */
  3791. static int execute_decode_slices(H264Context *h, int context_count)
  3792. {
  3793. AVCodecContext *const avctx = h->avctx;
  3794. H264Context *hx;
  3795. int i;
  3796. if (h->avctx->hwaccel ||
  3797. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3798. return 0;
  3799. if (context_count == 1) {
  3800. return decode_slice(avctx, &h);
  3801. } else {
  3802. av_assert0(context_count > 0);
  3803. for (i = 1; i < context_count; i++) {
  3804. hx = h->thread_context[i];
  3805. hx->er.error_count = 0;
  3806. hx->x264_build = h->x264_build;
  3807. }
  3808. avctx->execute(avctx, decode_slice, h->thread_context,
  3809. NULL, context_count, sizeof(void *));
  3810. /* pull back stuff from slices to master context */
  3811. hx = h->thread_context[context_count - 1];
  3812. h->mb_x = hx->mb_x;
  3813. h->mb_y = hx->mb_y;
  3814. h->droppable = hx->droppable;
  3815. h->picture_structure = hx->picture_structure;
  3816. for (i = 1; i < context_count; i++)
  3817. h->er.error_count += h->thread_context[i]->er.error_count;
  3818. }
  3819. return 0;
  3820. }
  3821. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  3822. int parse_extradata)
  3823. {
  3824. AVCodecContext *const avctx = h->avctx;
  3825. H264Context *hx; ///< thread context
  3826. int buf_index;
  3827. int context_count;
  3828. int next_avc;
  3829. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  3830. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  3831. int nal_index;
  3832. int idr_cleared=0;
  3833. int first_slice = 0;
  3834. h->nal_unit_type= 0;
  3835. if(!h->slice_context_count)
  3836. h->slice_context_count= 1;
  3837. h->max_contexts = h->slice_context_count;
  3838. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
  3839. h->current_slice = 0;
  3840. if (!h->first_field)
  3841. h->cur_pic_ptr = NULL;
  3842. ff_h264_reset_sei(h);
  3843. }
  3844. if (h->nal_length_size == 4) {
  3845. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  3846. h->is_avc = 0;
  3847. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  3848. h->is_avc = 1;
  3849. }
  3850. for (; pass <= 1; pass++) {
  3851. buf_index = 0;
  3852. context_count = 0;
  3853. next_avc = h->is_avc ? 0 : buf_size;
  3854. nal_index = 0;
  3855. for (;;) {
  3856. int consumed;
  3857. int dst_length;
  3858. int bit_length;
  3859. const uint8_t *ptr;
  3860. int i, nalsize = 0;
  3861. int err;
  3862. if (buf_index >= next_avc) {
  3863. if (buf_index >= buf_size - h->nal_length_size)
  3864. break;
  3865. nalsize = 0;
  3866. for (i = 0; i < h->nal_length_size; i++)
  3867. nalsize = (nalsize << 8) | buf[buf_index++];
  3868. if (nalsize <= 0 || nalsize > buf_size - buf_index) {
  3869. av_log(h->avctx, AV_LOG_ERROR,
  3870. "AVC: nal size %d\n", nalsize);
  3871. break;
  3872. }
  3873. next_avc = buf_index + nalsize;
  3874. } else {
  3875. // start code prefix search
  3876. for (; buf_index + 3 < next_avc; buf_index++)
  3877. // This should always succeed in the first iteration.
  3878. if (buf[buf_index] == 0 &&
  3879. buf[buf_index + 1] == 0 &&
  3880. buf[buf_index + 2] == 1)
  3881. break;
  3882. if (buf_index + 3 >= buf_size) {
  3883. buf_index = buf_size;
  3884. break;
  3885. }
  3886. buf_index += 3;
  3887. if (buf_index >= next_avc)
  3888. continue;
  3889. }
  3890. hx = h->thread_context[context_count];
  3891. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  3892. &consumed, next_avc - buf_index);
  3893. if (ptr == NULL || dst_length < 0) {
  3894. buf_index = -1;
  3895. goto end;
  3896. }
  3897. i = buf_index + consumed;
  3898. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  3899. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  3900. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  3901. h->workaround_bugs |= FF_BUG_TRUNCATED;
  3902. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  3903. while(dst_length > 0 && ptr[dst_length - 1] == 0)
  3904. dst_length--;
  3905. bit_length = !dst_length ? 0
  3906. : (8 * dst_length -
  3907. decode_rbsp_trailing(h, ptr + dst_length - 1));
  3908. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  3909. av_log(h->avctx, AV_LOG_DEBUG, "NAL %d/%d at %d/%d length %d pass %d\n", hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
  3910. if (h->is_avc && (nalsize != consumed) && nalsize)
  3911. av_log(h->avctx, AV_LOG_DEBUG,
  3912. "AVC: Consumed only %d bytes instead of %d\n",
  3913. consumed, nalsize);
  3914. buf_index += consumed;
  3915. nal_index++;
  3916. if (pass == 0) {
  3917. /* packets can sometimes contain multiple PPS/SPS,
  3918. * e.g. two PAFF field pictures in one packet, or a demuxer
  3919. * which splits NALs strangely if so, when frame threading we
  3920. * can't start the next thread until we've read all of them */
  3921. switch (hx->nal_unit_type) {
  3922. case NAL_SPS:
  3923. case NAL_PPS:
  3924. nals_needed = nal_index;
  3925. break;
  3926. case NAL_DPA:
  3927. case NAL_IDR_SLICE:
  3928. case NAL_SLICE:
  3929. init_get_bits(&hx->gb, ptr, bit_length);
  3930. if (!get_ue_golomb(&hx->gb) || !first_slice)
  3931. nals_needed = nal_index;
  3932. if (!first_slice)
  3933. first_slice = hx->nal_unit_type;
  3934. }
  3935. continue;
  3936. }
  3937. if (!first_slice)
  3938. switch (hx->nal_unit_type) {
  3939. case NAL_DPA:
  3940. case NAL_IDR_SLICE:
  3941. case NAL_SLICE:
  3942. first_slice = hx->nal_unit_type;
  3943. }
  3944. // FIXME do not discard SEI id
  3945. if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
  3946. continue;
  3947. again:
  3948. /* Ignore per frame NAL unit type during extradata
  3949. * parsing. Decoding slices is not possible in codec init
  3950. * with frame-mt */
  3951. if (parse_extradata) {
  3952. switch (hx->nal_unit_type) {
  3953. case NAL_IDR_SLICE:
  3954. case NAL_SLICE:
  3955. case NAL_DPA:
  3956. case NAL_DPB:
  3957. case NAL_DPC:
  3958. case NAL_AUXILIARY_SLICE:
  3959. av_log(h->avctx, AV_LOG_WARNING, "Ignoring NAL %d in global header/extradata\n", hx->nal_unit_type);
  3960. hx->nal_unit_type = NAL_FF_IGNORE;
  3961. }
  3962. }
  3963. err = 0;
  3964. switch (hx->nal_unit_type) {
  3965. case NAL_IDR_SLICE:
  3966. if (first_slice != NAL_IDR_SLICE) {
  3967. av_log(h->avctx, AV_LOG_ERROR,
  3968. "Invalid mix of idr and non-idr slices\n");
  3969. buf_index = -1;
  3970. goto end;
  3971. }
  3972. if(!idr_cleared)
  3973. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  3974. idr_cleared = 1;
  3975. case NAL_SLICE:
  3976. init_get_bits(&hx->gb, ptr, bit_length);
  3977. hx->intra_gb_ptr =
  3978. hx->inter_gb_ptr = &hx->gb;
  3979. hx->data_partitioning = 0;
  3980. if ((err = decode_slice_header(hx, h)))
  3981. break;
  3982. if (h->sei_recovery_frame_cnt >= 0 && (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I))
  3983. h->valid_recovery_point = 1;
  3984. if ( h->sei_recovery_frame_cnt >= 0
  3985. && ( h->recovery_frame<0
  3986. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
  3987. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
  3988. (1 << h->sps.log2_max_frame_num);
  3989. if (!h->valid_recovery_point)
  3990. h->recovery_frame = h->frame_num;
  3991. }
  3992. h->cur_pic_ptr->f.key_frame |=
  3993. (hx->nal_unit_type == NAL_IDR_SLICE);
  3994. if (h->recovery_frame == h->frame_num) {
  3995. h->cur_pic_ptr->sync |= 1;
  3996. h->recovery_frame = -1;
  3997. }
  3998. h->sync |= !!h->cur_pic_ptr->f.key_frame;
  3999. h->sync |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
  4000. h->cur_pic_ptr->sync |= h->sync;
  4001. if (h->current_slice == 1) {
  4002. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
  4003. decode_postinit(h, nal_index >= nals_needed);
  4004. if (h->avctx->hwaccel &&
  4005. h->avctx->hwaccel->start_frame(h->avctx, NULL, 0) < 0)
  4006. return -1;
  4007. if (CONFIG_H264_VDPAU_DECODER &&
  4008. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  4009. ff_vdpau_h264_picture_start(h);
  4010. }
  4011. if (hx->redundant_pic_count == 0 &&
  4012. (avctx->skip_frame < AVDISCARD_NONREF ||
  4013. hx->nal_ref_idc) &&
  4014. (avctx->skip_frame < AVDISCARD_BIDIR ||
  4015. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  4016. (avctx->skip_frame < AVDISCARD_NONKEY ||
  4017. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  4018. avctx->skip_frame < AVDISCARD_ALL) {
  4019. if (avctx->hwaccel) {
  4020. if (avctx->hwaccel->decode_slice(avctx,
  4021. &buf[buf_index - consumed],
  4022. consumed) < 0)
  4023. return -1;
  4024. } else if (CONFIG_H264_VDPAU_DECODER &&
  4025. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  4026. static const uint8_t start_code[] = {
  4027. 0x00, 0x00, 0x01 };
  4028. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], start_code,
  4029. sizeof(start_code));
  4030. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], &buf[buf_index - consumed],
  4031. consumed);
  4032. } else
  4033. context_count++;
  4034. }
  4035. break;
  4036. case NAL_DPA:
  4037. init_get_bits(&hx->gb, ptr, bit_length);
  4038. hx->intra_gb_ptr =
  4039. hx->inter_gb_ptr = NULL;
  4040. if ((err = decode_slice_header(hx, h)) < 0)
  4041. break;
  4042. hx->data_partitioning = 1;
  4043. break;
  4044. case NAL_DPB:
  4045. init_get_bits(&hx->intra_gb, ptr, bit_length);
  4046. hx->intra_gb_ptr = &hx->intra_gb;
  4047. break;
  4048. case NAL_DPC:
  4049. init_get_bits(&hx->inter_gb, ptr, bit_length);
  4050. hx->inter_gb_ptr = &hx->inter_gb;
  4051. av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
  4052. break;
  4053. if (hx->redundant_pic_count == 0 &&
  4054. hx->intra_gb_ptr &&
  4055. hx->data_partitioning &&
  4056. h->cur_pic_ptr && h->context_initialized &&
  4057. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  4058. (avctx->skip_frame < AVDISCARD_BIDIR ||
  4059. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  4060. (avctx->skip_frame < AVDISCARD_NONKEY ||
  4061. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  4062. avctx->skip_frame < AVDISCARD_ALL)
  4063. context_count++;
  4064. break;
  4065. case NAL_SEI:
  4066. init_get_bits(&h->gb, ptr, bit_length);
  4067. ff_h264_decode_sei(h);
  4068. break;
  4069. case NAL_SPS:
  4070. init_get_bits(&h->gb, ptr, bit_length);
  4071. if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)) {
  4072. av_log(h->avctx, AV_LOG_DEBUG,
  4073. "SPS decoding failure, trying again with the complete NAL\n");
  4074. if (h->is_avc)
  4075. av_assert0(next_avc - buf_index + consumed == nalsize);
  4076. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  4077. break;
  4078. init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
  4079. 8*(next_avc - buf_index + consumed - 1));
  4080. ff_h264_decode_seq_parameter_set(h);
  4081. }
  4082. break;
  4083. case NAL_PPS:
  4084. init_get_bits(&h->gb, ptr, bit_length);
  4085. ff_h264_decode_picture_parameter_set(h, bit_length);
  4086. break;
  4087. case NAL_AUD:
  4088. case NAL_END_SEQUENCE:
  4089. case NAL_END_STREAM:
  4090. case NAL_FILLER_DATA:
  4091. case NAL_SPS_EXT:
  4092. case NAL_AUXILIARY_SLICE:
  4093. break;
  4094. case NAL_FF_IGNORE:
  4095. break;
  4096. default:
  4097. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  4098. hx->nal_unit_type, bit_length);
  4099. }
  4100. if (context_count == h->max_contexts) {
  4101. execute_decode_slices(h, context_count);
  4102. context_count = 0;
  4103. }
  4104. if (err < 0)
  4105. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  4106. else if (err == 1) {
  4107. /* Slice could not be decoded in parallel mode, copy down
  4108. * NAL unit stuff to context 0 and restart. Note that
  4109. * rbsp_buffer is not transferred, but since we no longer
  4110. * run in parallel mode this should not be an issue. */
  4111. h->nal_unit_type = hx->nal_unit_type;
  4112. h->nal_ref_idc = hx->nal_ref_idc;
  4113. hx = h;
  4114. goto again;
  4115. }
  4116. }
  4117. }
  4118. if (context_count)
  4119. execute_decode_slices(h, context_count);
  4120. end:
  4121. /* clean up */
  4122. if (h->cur_pic_ptr && h->cur_pic_ptr->owner2 == h &&
  4123. !h->droppable) {
  4124. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  4125. h->picture_structure == PICT_BOTTOM_FIELD);
  4126. }
  4127. return buf_index;
  4128. }
  4129. /**
  4130. * Return the number of bytes consumed for building the current frame.
  4131. */
  4132. static int get_consumed_bytes(int pos, int buf_size)
  4133. {
  4134. if (pos == 0)
  4135. pos = 1; // avoid infinite loops (i doubt that is needed but ...)
  4136. if (pos + 10 > buf_size)
  4137. pos = buf_size; // oops ;)
  4138. return pos;
  4139. }
  4140. static int decode_frame(AVCodecContext *avctx, void *data,
  4141. int *got_frame, AVPacket *avpkt)
  4142. {
  4143. const uint8_t *buf = avpkt->data;
  4144. int buf_size = avpkt->size;
  4145. H264Context *h = avctx->priv_data;
  4146. AVFrame *pict = data;
  4147. int buf_index = 0;
  4148. Picture *out;
  4149. int i, out_idx;
  4150. h->flags = avctx->flags;
  4151. /* end of stream, output what is still in the buffers */
  4152. if (buf_size == 0) {
  4153. out:
  4154. h->cur_pic_ptr = NULL;
  4155. h->first_field = 0;
  4156. // FIXME factorize this with the output code below
  4157. out = h->delayed_pic[0];
  4158. out_idx = 0;
  4159. for (i = 1;
  4160. h->delayed_pic[i] &&
  4161. !h->delayed_pic[i]->f.key_frame &&
  4162. !h->delayed_pic[i]->mmco_reset;
  4163. i++)
  4164. if (h->delayed_pic[i]->poc < out->poc) {
  4165. out = h->delayed_pic[i];
  4166. out_idx = i;
  4167. }
  4168. for (i = out_idx; h->delayed_pic[i]; i++)
  4169. h->delayed_pic[i] = h->delayed_pic[i + 1];
  4170. if (out) {
  4171. out->f.reference &= ~DELAYED_PIC_REF;
  4172. *got_frame = 1;
  4173. *pict = out->f;
  4174. }
  4175. return buf_index;
  4176. }
  4177. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  4178. int cnt= buf[5]&0x1f;
  4179. const uint8_t *p= buf+6;
  4180. while(cnt--){
  4181. int nalsize= AV_RB16(p) + 2;
  4182. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  4183. goto not_extra;
  4184. p += nalsize;
  4185. }
  4186. cnt = *(p++);
  4187. if(!cnt)
  4188. goto not_extra;
  4189. while(cnt--){
  4190. int nalsize= AV_RB16(p) + 2;
  4191. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  4192. goto not_extra;
  4193. p += nalsize;
  4194. }
  4195. return ff_h264_decode_extradata(h, buf, buf_size);
  4196. }
  4197. not_extra:
  4198. buf_index = decode_nal_units(h, buf, buf_size, 0);
  4199. if (buf_index < 0)
  4200. return -1;
  4201. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  4202. av_assert0(buf_index <= buf_size);
  4203. goto out;
  4204. }
  4205. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  4206. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  4207. buf_size >= 4 && !memcmp("Q264", buf, 4))
  4208. return buf_size;
  4209. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  4210. return -1;
  4211. }
  4212. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
  4213. (h->mb_y >= h->mb_height && h->mb_height)) {
  4214. if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
  4215. decode_postinit(h, 1);
  4216. field_end(h, 0);
  4217. /* Wait for second field. */
  4218. *got_frame = 0;
  4219. if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
  4220. *got_frame = 1;
  4221. *pict = h->next_output_pic->f;
  4222. }
  4223. }
  4224. assert(pict->data[0] || !*got_frame);
  4225. ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table, h->visualization_buffer, &h->low_delay,
  4226. h->mb_width, h->mb_height, h->mb_stride, 1);
  4227. return get_consumed_bytes(buf_index, buf_size);
  4228. }
  4229. av_cold void ff_h264_free_context(H264Context *h)
  4230. {
  4231. int i;
  4232. free_tables(h, 1); // FIXME cleanup init stuff perhaps
  4233. for (i = 0; i < MAX_SPS_COUNT; i++)
  4234. av_freep(h->sps_buffers + i);
  4235. for (i = 0; i < MAX_PPS_COUNT; i++)
  4236. av_freep(h->pps_buffers + i);
  4237. }
  4238. static av_cold int h264_decode_end(AVCodecContext *avctx)
  4239. {
  4240. H264Context *h = avctx->priv_data;
  4241. int i;
  4242. ff_h264_remove_all_refs(h);
  4243. ff_h264_free_context(h);
  4244. if (h->DPB && !h->avctx->internal->is_copy) {
  4245. for (i = 0; i < h->picture_count; i++) {
  4246. free_picture(h, &h->DPB[i]);
  4247. }
  4248. }
  4249. av_freep(&h->DPB);
  4250. return 0;
  4251. }
  4252. static const AVProfile profiles[] = {
  4253. { FF_PROFILE_H264_BASELINE, "Baseline" },
  4254. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  4255. { FF_PROFILE_H264_MAIN, "Main" },
  4256. { FF_PROFILE_H264_EXTENDED, "Extended" },
  4257. { FF_PROFILE_H264_HIGH, "High" },
  4258. { FF_PROFILE_H264_HIGH_10, "High 10" },
  4259. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  4260. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  4261. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  4262. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  4263. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  4264. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  4265. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  4266. { FF_PROFILE_UNKNOWN },
  4267. };
  4268. static const AVOption h264_options[] = {
  4269. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  4270. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  4271. {NULL}
  4272. };
  4273. static const AVClass h264_class = {
  4274. .class_name = "H264 Decoder",
  4275. .item_name = av_default_item_name,
  4276. .option = h264_options,
  4277. .version = LIBAVUTIL_VERSION_INT,
  4278. };
  4279. static const AVClass h264_vdpau_class = {
  4280. .class_name = "H264 VDPAU Decoder",
  4281. .item_name = av_default_item_name,
  4282. .option = h264_options,
  4283. .version = LIBAVUTIL_VERSION_INT,
  4284. };
  4285. AVCodec ff_h264_decoder = {
  4286. .name = "h264",
  4287. .type = AVMEDIA_TYPE_VIDEO,
  4288. .id = AV_CODEC_ID_H264,
  4289. .priv_data_size = sizeof(H264Context),
  4290. .init = ff_h264_decode_init,
  4291. .close = h264_decode_end,
  4292. .decode = decode_frame,
  4293. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  4294. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  4295. CODEC_CAP_FRAME_THREADS,
  4296. .flush = flush_dpb,
  4297. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  4298. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  4299. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  4300. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4301. .priv_class = &h264_class,
  4302. };
  4303. #if CONFIG_H264_VDPAU_DECODER
  4304. AVCodec ff_h264_vdpau_decoder = {
  4305. .name = "h264_vdpau",
  4306. .type = AVMEDIA_TYPE_VIDEO,
  4307. .id = AV_CODEC_ID_H264,
  4308. .priv_data_size = sizeof(H264Context),
  4309. .init = ff_h264_decode_init,
  4310. .close = h264_decode_end,
  4311. .decode = decode_frame,
  4312. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  4313. .flush = flush_dpb,
  4314. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  4315. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  4316. AV_PIX_FMT_NONE},
  4317. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4318. .priv_class = &h264_vdpau_class,
  4319. };
  4320. #endif