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.

4894 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. // extradata/NAL handling
  1413. h->is_avc = h1->is_avc;
  1414. // SPS/PPS
  1415. copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
  1416. MAX_SPS_COUNT, sizeof(SPS));
  1417. h->sps = h1->sps;
  1418. copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
  1419. MAX_PPS_COUNT, sizeof(PPS));
  1420. h->pps = h1->pps;
  1421. // Dequantization matrices
  1422. // FIXME these are big - can they be only copied when PPS changes?
  1423. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  1424. for (i = 0; i < 6; i++)
  1425. h->dequant4_coeff[i] = h->dequant4_buffer[0] +
  1426. (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  1427. for (i = 0; i < 6; i++)
  1428. h->dequant8_coeff[i] = h->dequant8_buffer[0] +
  1429. (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  1430. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  1431. // POC timing
  1432. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  1433. // reference lists
  1434. copy_fields(h, h1, ref_count, list_count);
  1435. copy_fields(h, h1, ref2frm, intra_gb);
  1436. copy_fields(h, h1, short_ref, cabac_init_idc);
  1437. copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
  1438. copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
  1439. copy_picture_range(h->delayed_pic, h1->delayed_pic,
  1440. MAX_DELAYED_PIC_COUNT + 2, h, h1);
  1441. h->last_slice_type = h1->last_slice_type;
  1442. h->sync = h1->sync;
  1443. memcpy(h->last_ref_count, h1->last_ref_count, sizeof(h->last_ref_count));
  1444. if (context_reinitialized)
  1445. h264_set_parameter_from_sps(h);
  1446. if (!h->cur_pic_ptr)
  1447. return 0;
  1448. if (!h->droppable) {
  1449. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1450. h->prev_poc_msb = h->poc_msb;
  1451. h->prev_poc_lsb = h->poc_lsb;
  1452. }
  1453. h->prev_frame_num_offset = h->frame_num_offset;
  1454. h->prev_frame_num = h->frame_num;
  1455. h->outputed_poc = h->next_outputed_poc;
  1456. return err;
  1457. }
  1458. int ff_h264_frame_start(H264Context *h)
  1459. {
  1460. Picture *pic;
  1461. int i, ret;
  1462. const int pixel_shift = h->pixel_shift;
  1463. int c[4] = {
  1464. 1<<(h->sps.bit_depth_luma-1),
  1465. 1<<(h->sps.bit_depth_chroma-1),
  1466. 1<<(h->sps.bit_depth_chroma-1),
  1467. -1
  1468. };
  1469. if (!ff_thread_can_start_frame(h->avctx)) {
  1470. av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
  1471. return -1;
  1472. }
  1473. release_unused_pictures(h, 1);
  1474. h->cur_pic_ptr = NULL;
  1475. i = find_unused_picture(h);
  1476. if (i < 0) {
  1477. av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
  1478. return i;
  1479. }
  1480. pic = &h->DPB[i];
  1481. pic->f.reference = h->droppable ? 0 : h->picture_structure;
  1482. pic->f.coded_picture_number = h->coded_picture_number++;
  1483. pic->field_picture = h->picture_structure != PICT_FRAME;
  1484. /*
  1485. * Zero key_frame here; IDR markings per slice in frame or fields are ORed
  1486. * in later.
  1487. * See decode_nal_units().
  1488. */
  1489. pic->f.key_frame = 0;
  1490. pic->sync = 0;
  1491. pic->mmco_reset = 0;
  1492. if ((ret = alloc_picture(h, pic)) < 0)
  1493. return ret;
  1494. if(!h->sync && !h->avctx->hwaccel &&
  1495. !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
  1496. avpriv_color_frame(&pic->f, c);
  1497. h->cur_pic_ptr = pic;
  1498. h->cur_pic = *h->cur_pic_ptr;
  1499. h->cur_pic.f.extended_data = h->cur_pic.f.data;
  1500. ff_er_frame_start(&h->er);
  1501. assert(h->linesize && h->uvlinesize);
  1502. for (i = 0; i < 16; i++) {
  1503. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1504. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1505. }
  1506. for (i = 0; i < 16; i++) {
  1507. h->block_offset[16 + i] =
  1508. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1509. h->block_offset[48 + 16 + i] =
  1510. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1511. }
  1512. /* Some macroblocks can be accessed before they're available in case
  1513. * of lost slices, MBAFF or threading. */
  1514. memset(h->slice_table, -1,
  1515. (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
  1516. // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
  1517. // h->cur_pic.f.reference /* || h->contains_intra */ || 1;
  1518. /* We mark the current picture as non-reference after allocating it, so
  1519. * that if we break out due to an error it can be released automatically
  1520. * in the next ff_MPV_frame_start().
  1521. * SVQ3 as well as most other codecs have only last/next/current and thus
  1522. * get released even with set reference, besides SVQ3 and others do not
  1523. * mark frames as reference later "naturally". */
  1524. if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)
  1525. h->cur_pic_ptr->f.reference = 0;
  1526. h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
  1527. h->next_output_pic = NULL;
  1528. assert(h->cur_pic_ptr->long_ref == 0);
  1529. return 0;
  1530. }
  1531. /**
  1532. * Run setup operations that must be run after slice header decoding.
  1533. * This includes finding the next displayed frame.
  1534. *
  1535. * @param h h264 master context
  1536. * @param setup_finished enough NALs have been read that we can call
  1537. * ff_thread_finish_setup()
  1538. */
  1539. static void decode_postinit(H264Context *h, int setup_finished)
  1540. {
  1541. Picture *out = h->cur_pic_ptr;
  1542. Picture *cur = h->cur_pic_ptr;
  1543. int i, pics, out_of_order, out_idx;
  1544. h->cur_pic_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
  1545. h->cur_pic_ptr->f.pict_type = h->pict_type;
  1546. if (h->next_output_pic)
  1547. return;
  1548. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  1549. /* FIXME: if we have two PAFF fields in one packet, we can't start
  1550. * the next thread here. If we have one field per packet, we can.
  1551. * The check in decode_nal_units() is not good enough to find this
  1552. * yet, so we assume the worst for now. */
  1553. // if (setup_finished)
  1554. // ff_thread_finish_setup(h->avctx);
  1555. return;
  1556. }
  1557. cur->f.interlaced_frame = 0;
  1558. cur->f.repeat_pict = 0;
  1559. /* Signal interlacing information externally. */
  1560. /* Prioritize picture timing SEI information over used
  1561. * decoding process if it exists. */
  1562. if (h->sps.pic_struct_present_flag) {
  1563. switch (h->sei_pic_struct) {
  1564. case SEI_PIC_STRUCT_FRAME:
  1565. break;
  1566. case SEI_PIC_STRUCT_TOP_FIELD:
  1567. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1568. cur->f.interlaced_frame = 1;
  1569. break;
  1570. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1571. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1572. if (FIELD_OR_MBAFF_PICTURE)
  1573. cur->f.interlaced_frame = 1;
  1574. else
  1575. // try to flag soft telecine progressive
  1576. cur->f.interlaced_frame = h->prev_interlaced_frame;
  1577. break;
  1578. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1579. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1580. /* Signal the possibility of telecined film externally
  1581. * (pic_struct 5,6). From these hints, let the applications
  1582. * decide if they apply deinterlacing. */
  1583. cur->f.repeat_pict = 1;
  1584. break;
  1585. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1586. cur->f.repeat_pict = 2;
  1587. break;
  1588. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1589. cur->f.repeat_pict = 4;
  1590. break;
  1591. }
  1592. if ((h->sei_ct_type & 3) &&
  1593. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1594. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  1595. } else {
  1596. /* Derive interlacing flag from used decoding process. */
  1597. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  1598. }
  1599. h->prev_interlaced_frame = cur->f.interlaced_frame;
  1600. if (cur->field_poc[0] != cur->field_poc[1]) {
  1601. /* Derive top_field_first from field pocs. */
  1602. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1603. } else {
  1604. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  1605. /* Use picture timing SEI information. Even if it is a
  1606. * information of a past frame, better than nothing. */
  1607. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  1608. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1609. cur->f.top_field_first = 1;
  1610. else
  1611. cur->f.top_field_first = 0;
  1612. } else {
  1613. /* Most likely progressive */
  1614. cur->f.top_field_first = 0;
  1615. }
  1616. }
  1617. cur->mmco_reset = h->mmco_reset;
  1618. h->mmco_reset = 0;
  1619. // FIXME do something with unavailable reference frames
  1620. /* Sort B-frames into display order */
  1621. if (h->sps.bitstream_restriction_flag &&
  1622. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1623. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  1624. h->low_delay = 0;
  1625. }
  1626. if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  1627. !h->sps.bitstream_restriction_flag) {
  1628. h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  1629. h->low_delay = 0;
  1630. }
  1631. for (i = 0; 1; i++) {
  1632. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1633. if(i)
  1634. h->last_pocs[i-1] = cur->poc;
  1635. break;
  1636. } else if(i) {
  1637. h->last_pocs[i-1]= h->last_pocs[i];
  1638. }
  1639. }
  1640. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1641. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  1642. || (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))
  1643. out_of_order = FFMAX(out_of_order, 1);
  1644. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  1645. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  1646. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  1647. h->last_pocs[i] = INT_MIN;
  1648. h->last_pocs[0] = cur->poc;
  1649. cur->mmco_reset = 1;
  1650. } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  1651. av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
  1652. h->avctx->has_b_frames = out_of_order;
  1653. h->low_delay = 0;
  1654. }
  1655. pics = 0;
  1656. while (h->delayed_pic[pics])
  1657. pics++;
  1658. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1659. h->delayed_pic[pics++] = cur;
  1660. if (cur->f.reference == 0)
  1661. cur->f.reference = DELAYED_PIC_REF;
  1662. out = h->delayed_pic[0];
  1663. out_idx = 0;
  1664. for (i = 1; h->delayed_pic[i] &&
  1665. !h->delayed_pic[i]->f.key_frame &&
  1666. !h->delayed_pic[i]->mmco_reset;
  1667. i++)
  1668. if (h->delayed_pic[i]->poc < out->poc) {
  1669. out = h->delayed_pic[i];
  1670. out_idx = i;
  1671. }
  1672. if (h->avctx->has_b_frames == 0 &&
  1673. (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  1674. h->next_outputed_poc = INT_MIN;
  1675. out_of_order = out->poc < h->next_outputed_poc;
  1676. if (out_of_order || pics > h->avctx->has_b_frames) {
  1677. out->f.reference &= ~DELAYED_PIC_REF;
  1678. // for frame threading, the owner must be the second field's thread or
  1679. // else the first thread can release the picture and reuse it unsafely
  1680. out->owner2 = h;
  1681. for (i = out_idx; h->delayed_pic[i]; i++)
  1682. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1683. }
  1684. if (!out_of_order && pics > h->avctx->has_b_frames) {
  1685. h->next_output_pic = out;
  1686. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  1687. h->next_outputed_poc = INT_MIN;
  1688. } else
  1689. h->next_outputed_poc = out->poc;
  1690. } else {
  1691. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1692. }
  1693. if (h->next_output_pic && h->next_output_pic->sync) {
  1694. h->sync |= 2;
  1695. }
  1696. if (setup_finished)
  1697. ff_thread_finish_setup(h->avctx);
  1698. }
  1699. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  1700. uint8_t *src_cb, uint8_t *src_cr,
  1701. int linesize, int uvlinesize,
  1702. int simple)
  1703. {
  1704. uint8_t *top_border;
  1705. int top_idx = 1;
  1706. const int pixel_shift = h->pixel_shift;
  1707. int chroma444 = CHROMA444;
  1708. int chroma422 = CHROMA422;
  1709. src_y -= linesize;
  1710. src_cb -= uvlinesize;
  1711. src_cr -= uvlinesize;
  1712. if (!simple && FRAME_MBAFF) {
  1713. if (h->mb_y & 1) {
  1714. if (!MB_MBAFF) {
  1715. top_border = h->top_borders[0][h->mb_x];
  1716. AV_COPY128(top_border, src_y + 15 * linesize);
  1717. if (pixel_shift)
  1718. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  1719. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1720. if (chroma444) {
  1721. if (pixel_shift) {
  1722. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1723. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  1724. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  1725. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  1726. } else {
  1727. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  1728. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  1729. }
  1730. } else if (chroma422) {
  1731. if (pixel_shift) {
  1732. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1733. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  1734. } else {
  1735. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  1736. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  1737. }
  1738. } else {
  1739. if (pixel_shift) {
  1740. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  1741. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  1742. } else {
  1743. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  1744. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  1745. }
  1746. }
  1747. }
  1748. }
  1749. } else if (MB_MBAFF) {
  1750. top_idx = 0;
  1751. } else
  1752. return;
  1753. }
  1754. top_border = h->top_borders[top_idx][h->mb_x];
  1755. /* There are two lines saved, the line above the top macroblock
  1756. * of a pair, and the line above the bottom macroblock. */
  1757. AV_COPY128(top_border, src_y + 16 * linesize);
  1758. if (pixel_shift)
  1759. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  1760. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1761. if (chroma444) {
  1762. if (pixel_shift) {
  1763. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  1764. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  1765. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  1766. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  1767. } else {
  1768. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  1769. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  1770. }
  1771. } else if (chroma422) {
  1772. if (pixel_shift) {
  1773. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  1774. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  1775. } else {
  1776. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  1777. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  1778. }
  1779. } else {
  1780. if (pixel_shift) {
  1781. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  1782. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  1783. } else {
  1784. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  1785. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  1786. }
  1787. }
  1788. }
  1789. }
  1790. static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
  1791. uint8_t *src_cb, uint8_t *src_cr,
  1792. int linesize, int uvlinesize,
  1793. int xchg, int chroma444,
  1794. int simple, int pixel_shift)
  1795. {
  1796. int deblock_topleft;
  1797. int deblock_top;
  1798. int top_idx = 1;
  1799. uint8_t *top_border_m1;
  1800. uint8_t *top_border;
  1801. if (!simple && FRAME_MBAFF) {
  1802. if (h->mb_y & 1) {
  1803. if (!MB_MBAFF)
  1804. return;
  1805. } else {
  1806. top_idx = MB_MBAFF ? 0 : 1;
  1807. }
  1808. }
  1809. if (h->deblocking_filter == 2) {
  1810. deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
  1811. deblock_top = h->top_type;
  1812. } else {
  1813. deblock_topleft = (h->mb_x > 0);
  1814. deblock_top = (h->mb_y > !!MB_FIELD);
  1815. }
  1816. src_y -= linesize + 1 + pixel_shift;
  1817. src_cb -= uvlinesize + 1 + pixel_shift;
  1818. src_cr -= uvlinesize + 1 + pixel_shift;
  1819. top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
  1820. top_border = h->top_borders[top_idx][h->mb_x];
  1821. #define XCHG(a, b, xchg) \
  1822. if (pixel_shift) { \
  1823. if (xchg) { \
  1824. AV_SWAP64(b + 0, a + 0); \
  1825. AV_SWAP64(b + 8, a + 8); \
  1826. } else { \
  1827. AV_COPY128(b, a); \
  1828. } \
  1829. } else if (xchg) \
  1830. AV_SWAP64(b, a); \
  1831. else \
  1832. AV_COPY64(b, a);
  1833. if (deblock_top) {
  1834. if (deblock_topleft) {
  1835. XCHG(top_border_m1 + (8 << pixel_shift),
  1836. src_y - (7 << pixel_shift), 1);
  1837. }
  1838. XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
  1839. XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
  1840. if (h->mb_x + 1 < h->mb_width) {
  1841. XCHG(h->top_borders[top_idx][h->mb_x + 1],
  1842. src_y + (17 << pixel_shift), 1);
  1843. }
  1844. }
  1845. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1846. if (chroma444) {
  1847. if (deblock_topleft) {
  1848. XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1849. XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1850. }
  1851. XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
  1852. XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
  1853. XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
  1854. XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
  1855. if (h->mb_x + 1 < h->mb_width) {
  1856. XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
  1857. XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
  1858. }
  1859. } else {
  1860. if (deblock_top) {
  1861. if (deblock_topleft) {
  1862. XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1863. XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1864. }
  1865. XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
  1866. XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
  1867. }
  1868. }
  1869. }
  1870. }
  1871. static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
  1872. int index)
  1873. {
  1874. if (high_bit_depth) {
  1875. return AV_RN32A(((int32_t *)mb) + index);
  1876. } else
  1877. return AV_RN16A(mb + index);
  1878. }
  1879. static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
  1880. int index, int value)
  1881. {
  1882. if (high_bit_depth) {
  1883. AV_WN32A(((int32_t *)mb) + index, value);
  1884. } else
  1885. AV_WN16A(mb + index, value);
  1886. }
  1887. static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
  1888. int mb_type, int is_h264,
  1889. int simple,
  1890. int transform_bypass,
  1891. int pixel_shift,
  1892. int *block_offset,
  1893. int linesize,
  1894. uint8_t *dest_y, int p)
  1895. {
  1896. void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
  1897. void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
  1898. int i;
  1899. int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
  1900. block_offset += 16 * p;
  1901. if (IS_INTRA4x4(mb_type)) {
  1902. if (IS_8x8DCT(mb_type)) {
  1903. if (transform_bypass) {
  1904. idct_dc_add =
  1905. idct_add = h->h264dsp.h264_add_pixels8_clear;
  1906. } else {
  1907. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  1908. idct_add = h->h264dsp.h264_idct8_add;
  1909. }
  1910. for (i = 0; i < 16; i += 4) {
  1911. uint8_t *const ptr = dest_y + block_offset[i];
  1912. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1913. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1914. h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1915. } else {
  1916. const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1917. h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
  1918. (h->topright_samples_available << i) & 0x4000, linesize);
  1919. if (nnz) {
  1920. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1921. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1922. else
  1923. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1924. }
  1925. }
  1926. }
  1927. } else {
  1928. if (transform_bypass) {
  1929. idct_dc_add =
  1930. idct_add = h->h264dsp.h264_add_pixels4_clear;
  1931. } else {
  1932. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  1933. idct_add = h->h264dsp.h264_idct_add;
  1934. }
  1935. for (i = 0; i < 16; i++) {
  1936. uint8_t *const ptr = dest_y + block_offset[i];
  1937. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1938. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1939. h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1940. } else {
  1941. uint8_t *topright;
  1942. int nnz, tr;
  1943. uint64_t tr_high;
  1944. if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
  1945. const int topright_avail = (h->topright_samples_available << i) & 0x8000;
  1946. av_assert2(h->mb_y || linesize <= block_offset[i]);
  1947. if (!topright_avail) {
  1948. if (pixel_shift) {
  1949. tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
  1950. topright = (uint8_t *)&tr_high;
  1951. } else {
  1952. tr = ptr[3 - linesize] * 0x01010101u;
  1953. topright = (uint8_t *)&tr;
  1954. }
  1955. } else
  1956. topright = ptr + (4 << pixel_shift) - linesize;
  1957. } else
  1958. topright = NULL;
  1959. h->hpc.pred4x4[dir](ptr, topright, linesize);
  1960. nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1961. if (nnz) {
  1962. if (is_h264) {
  1963. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1964. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1965. else
  1966. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1967. } else if (CONFIG_SVQ3_DECODER)
  1968. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
  1969. }
  1970. }
  1971. }
  1972. }
  1973. } else {
  1974. h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
  1975. if (is_h264) {
  1976. if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
  1977. if (!transform_bypass)
  1978. h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
  1979. h->mb_luma_dc[p],
  1980. h->dequant4_coeff[p][qscale][0]);
  1981. else {
  1982. static const uint8_t dc_mapping[16] = {
  1983. 0 * 16, 1 * 16, 4 * 16, 5 * 16,
  1984. 2 * 16, 3 * 16, 6 * 16, 7 * 16,
  1985. 8 * 16, 9 * 16, 12 * 16, 13 * 16,
  1986. 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
  1987. for (i = 0; i < 16; i++)
  1988. dctcoef_set(h->mb + (p * 256 << pixel_shift),
  1989. pixel_shift, dc_mapping[i],
  1990. dctcoef_get(h->mb_luma_dc[p],
  1991. pixel_shift, i));
  1992. }
  1993. }
  1994. } else if (CONFIG_SVQ3_DECODER)
  1995. ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
  1996. h->mb_luma_dc[p], qscale);
  1997. }
  1998. }
  1999. static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
  2000. int is_h264, int simple,
  2001. int transform_bypass,
  2002. int pixel_shift,
  2003. int *block_offset,
  2004. int linesize,
  2005. uint8_t *dest_y, int p)
  2006. {
  2007. void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
  2008. int i;
  2009. block_offset += 16 * p;
  2010. if (!IS_INTRA4x4(mb_type)) {
  2011. if (is_h264) {
  2012. if (IS_INTRA16x16(mb_type)) {
  2013. if (transform_bypass) {
  2014. if (h->sps.profile_idc == 244 &&
  2015. (h->intra16x16_pred_mode == VERT_PRED8x8 ||
  2016. h->intra16x16_pred_mode == HOR_PRED8x8)) {
  2017. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
  2018. h->mb + (p * 256 << pixel_shift),
  2019. linesize);
  2020. } else {
  2021. for (i = 0; i < 16; i++)
  2022. if (h->non_zero_count_cache[scan8[i + p * 16]] ||
  2023. dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  2024. h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
  2025. h->mb + (i * 16 + p * 256 << pixel_shift),
  2026. linesize);
  2027. }
  2028. } else {
  2029. h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
  2030. h->mb + (p * 256 << pixel_shift),
  2031. linesize,
  2032. h->non_zero_count_cache + p * 5 * 8);
  2033. }
  2034. } else if (h->cbp & 15) {
  2035. if (transform_bypass) {
  2036. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  2037. idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
  2038. : h->h264dsp.h264_add_pixels4_clear;
  2039. for (i = 0; i < 16; i += di)
  2040. if (h->non_zero_count_cache[scan8[i + p * 16]])
  2041. idct_add(dest_y + block_offset[i],
  2042. h->mb + (i * 16 + p * 256 << pixel_shift),
  2043. linesize);
  2044. } else {
  2045. if (IS_8x8DCT(mb_type))
  2046. h->h264dsp.h264_idct8_add4(dest_y, block_offset,
  2047. h->mb + (p * 256 << pixel_shift),
  2048. linesize,
  2049. h->non_zero_count_cache + p * 5 * 8);
  2050. else
  2051. h->h264dsp.h264_idct_add16(dest_y, block_offset,
  2052. h->mb + (p * 256 << pixel_shift),
  2053. linesize,
  2054. h->non_zero_count_cache + p * 5 * 8);
  2055. }
  2056. }
  2057. } else if (CONFIG_SVQ3_DECODER) {
  2058. for (i = 0; i < 16; i++)
  2059. if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
  2060. // FIXME benchmark weird rule, & below
  2061. uint8_t *const ptr = dest_y + block_offset[i];
  2062. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
  2063. h->qscale, IS_INTRA(mb_type) ? 1 : 0);
  2064. }
  2065. }
  2066. }
  2067. }
  2068. #define BITS 8
  2069. #define SIMPLE 1
  2070. #include "h264_mb_template.c"
  2071. #undef BITS
  2072. #define BITS 16
  2073. #include "h264_mb_template.c"
  2074. #undef SIMPLE
  2075. #define SIMPLE 0
  2076. #include "h264_mb_template.c"
  2077. void ff_h264_hl_decode_mb(H264Context *h)
  2078. {
  2079. const int mb_xy = h->mb_xy;
  2080. const int mb_type = h->cur_pic.f.mb_type[mb_xy];
  2081. int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || h->qscale == 0;
  2082. if (CHROMA444) {
  2083. if (is_complex || h->pixel_shift)
  2084. hl_decode_mb_444_complex(h);
  2085. else
  2086. hl_decode_mb_444_simple_8(h);
  2087. } else if (is_complex) {
  2088. hl_decode_mb_complex(h);
  2089. } else if (h->pixel_shift) {
  2090. hl_decode_mb_simple_16(h);
  2091. } else
  2092. hl_decode_mb_simple_8(h);
  2093. }
  2094. static int pred_weight_table(H264Context *h)
  2095. {
  2096. int list, i;
  2097. int luma_def, chroma_def;
  2098. h->use_weight = 0;
  2099. h->use_weight_chroma = 0;
  2100. h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
  2101. if (h->sps.chroma_format_idc)
  2102. h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
  2103. luma_def = 1 << h->luma_log2_weight_denom;
  2104. chroma_def = 1 << h->chroma_log2_weight_denom;
  2105. for (list = 0; list < 2; list++) {
  2106. h->luma_weight_flag[list] = 0;
  2107. h->chroma_weight_flag[list] = 0;
  2108. for (i = 0; i < h->ref_count[list]; i++) {
  2109. int luma_weight_flag, chroma_weight_flag;
  2110. luma_weight_flag = get_bits1(&h->gb);
  2111. if (luma_weight_flag) {
  2112. h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
  2113. h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
  2114. if (h->luma_weight[i][list][0] != luma_def ||
  2115. h->luma_weight[i][list][1] != 0) {
  2116. h->use_weight = 1;
  2117. h->luma_weight_flag[list] = 1;
  2118. }
  2119. } else {
  2120. h->luma_weight[i][list][0] = luma_def;
  2121. h->luma_weight[i][list][1] = 0;
  2122. }
  2123. if (h->sps.chroma_format_idc) {
  2124. chroma_weight_flag = get_bits1(&h->gb);
  2125. if (chroma_weight_flag) {
  2126. int j;
  2127. for (j = 0; j < 2; j++) {
  2128. h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
  2129. h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
  2130. if (h->chroma_weight[i][list][j][0] != chroma_def ||
  2131. h->chroma_weight[i][list][j][1] != 0) {
  2132. h->use_weight_chroma = 1;
  2133. h->chroma_weight_flag[list] = 1;
  2134. }
  2135. }
  2136. } else {
  2137. int j;
  2138. for (j = 0; j < 2; j++) {
  2139. h->chroma_weight[i][list][j][0] = chroma_def;
  2140. h->chroma_weight[i][list][j][1] = 0;
  2141. }
  2142. }
  2143. }
  2144. }
  2145. if (h->slice_type_nos != AV_PICTURE_TYPE_B)
  2146. break;
  2147. }
  2148. h->use_weight = h->use_weight || h->use_weight_chroma;
  2149. return 0;
  2150. }
  2151. /**
  2152. * Initialize implicit_weight table.
  2153. * @param field 0/1 initialize the weight for interlaced MBAFF
  2154. * -1 initializes the rest
  2155. */
  2156. static void implicit_weight_table(H264Context *h, int field)
  2157. {
  2158. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  2159. for (i = 0; i < 2; i++) {
  2160. h->luma_weight_flag[i] = 0;
  2161. h->chroma_weight_flag[i] = 0;
  2162. }
  2163. if (field < 0) {
  2164. if (h->picture_structure == PICT_FRAME) {
  2165. cur_poc = h->cur_pic_ptr->poc;
  2166. } else {
  2167. cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
  2168. }
  2169. if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
  2170. h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
  2171. h->use_weight = 0;
  2172. h->use_weight_chroma = 0;
  2173. return;
  2174. }
  2175. ref_start = 0;
  2176. ref_count0 = h->ref_count[0];
  2177. ref_count1 = h->ref_count[1];
  2178. } else {
  2179. cur_poc = h->cur_pic_ptr->field_poc[field];
  2180. ref_start = 16;
  2181. ref_count0 = 16 + 2 * h->ref_count[0];
  2182. ref_count1 = 16 + 2 * h->ref_count[1];
  2183. }
  2184. h->use_weight = 2;
  2185. h->use_weight_chroma = 2;
  2186. h->luma_log2_weight_denom = 5;
  2187. h->chroma_log2_weight_denom = 5;
  2188. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  2189. int poc0 = h->ref_list[0][ref0].poc;
  2190. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  2191. int w = 32;
  2192. if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
  2193. int poc1 = h->ref_list[1][ref1].poc;
  2194. int td = av_clip(poc1 - poc0, -128, 127);
  2195. if (td) {
  2196. int tb = av_clip(cur_poc - poc0, -128, 127);
  2197. int tx = (16384 + (FFABS(td) >> 1)) / td;
  2198. int dist_scale_factor = (tb * tx + 32) >> 8;
  2199. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  2200. w = 64 - dist_scale_factor;
  2201. }
  2202. }
  2203. if (field < 0) {
  2204. h->implicit_weight[ref0][ref1][0] =
  2205. h->implicit_weight[ref0][ref1][1] = w;
  2206. } else {
  2207. h->implicit_weight[ref0][ref1][field] = w;
  2208. }
  2209. }
  2210. }
  2211. }
  2212. /**
  2213. * instantaneous decoder refresh.
  2214. */
  2215. static void idr(H264Context *h)
  2216. {
  2217. int i;
  2218. ff_h264_remove_all_refs(h);
  2219. h->prev_frame_num = 0;
  2220. h->prev_frame_num_offset = 0;
  2221. h->prev_poc_msb = 1<<16;
  2222. h->prev_poc_lsb = 0;
  2223. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  2224. h->last_pocs[i] = INT_MIN;
  2225. }
  2226. /* forget old pics after a seek */
  2227. static void flush_change(H264Context *h)
  2228. {
  2229. int i, j;
  2230. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  2231. h->prev_interlaced_frame = 1;
  2232. idr(h);
  2233. h->prev_frame_num = -1;
  2234. if (h->cur_pic_ptr) {
  2235. h->cur_pic_ptr->f.reference = 0;
  2236. for (j=i=0; h->delayed_pic[i]; i++)
  2237. if (h->delayed_pic[i] != h->cur_pic_ptr)
  2238. h->delayed_pic[j++] = h->delayed_pic[i];
  2239. h->delayed_pic[j] = NULL;
  2240. }
  2241. h->first_field = 0;
  2242. memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
  2243. memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
  2244. memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
  2245. memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
  2246. ff_h264_reset_sei(h);
  2247. h->recovery_frame= -1;
  2248. h->sync= 0;
  2249. h->list_count = 0;
  2250. h->current_slice = 0;
  2251. }
  2252. /* forget old pics after a seek */
  2253. static void flush_dpb(AVCodecContext *avctx)
  2254. {
  2255. H264Context *h = avctx->priv_data;
  2256. int i;
  2257. for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
  2258. if (h->delayed_pic[i])
  2259. h->delayed_pic[i]->f.reference = 0;
  2260. h->delayed_pic[i] = NULL;
  2261. }
  2262. flush_change(h);
  2263. for (i = 0; i < h->picture_count; i++) {
  2264. if (h->DPB[i].f.data[0])
  2265. free_frame_buffer(h, &h->DPB[i]);
  2266. }
  2267. h->cur_pic_ptr = NULL;
  2268. h->mb_x = h->mb_y = 0;
  2269. h->parse_context.state = -1;
  2270. h->parse_context.frame_start_found = 0;
  2271. h->parse_context.overread = 0;
  2272. h->parse_context.overread_index = 0;
  2273. h->parse_context.index = 0;
  2274. h->parse_context.last_index = 0;
  2275. }
  2276. static int init_poc(H264Context *h)
  2277. {
  2278. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2279. int field_poc[2];
  2280. Picture *cur = h->cur_pic_ptr;
  2281. h->frame_num_offset = h->prev_frame_num_offset;
  2282. if (h->frame_num < h->prev_frame_num)
  2283. h->frame_num_offset += max_frame_num;
  2284. if (h->sps.poc_type == 0) {
  2285. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  2286. if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  2287. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  2288. else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  2289. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  2290. else
  2291. h->poc_msb = h->prev_poc_msb;
  2292. field_poc[0] =
  2293. field_poc[1] = h->poc_msb + h->poc_lsb;
  2294. if (h->picture_structure == PICT_FRAME)
  2295. field_poc[1] += h->delta_poc_bottom;
  2296. } else if (h->sps.poc_type == 1) {
  2297. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  2298. int i;
  2299. if (h->sps.poc_cycle_length != 0)
  2300. abs_frame_num = h->frame_num_offset + h->frame_num;
  2301. else
  2302. abs_frame_num = 0;
  2303. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  2304. abs_frame_num--;
  2305. expected_delta_per_poc_cycle = 0;
  2306. for (i = 0; i < h->sps.poc_cycle_length; i++)
  2307. // FIXME integrate during sps parse
  2308. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  2309. if (abs_frame_num > 0) {
  2310. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  2311. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  2312. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  2313. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  2314. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  2315. } else
  2316. expectedpoc = 0;
  2317. if (h->nal_ref_idc == 0)
  2318. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  2319. field_poc[0] = expectedpoc + h->delta_poc[0];
  2320. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  2321. if (h->picture_structure == PICT_FRAME)
  2322. field_poc[1] += h->delta_poc[1];
  2323. } else {
  2324. int poc = 2 * (h->frame_num_offset + h->frame_num);
  2325. if (!h->nal_ref_idc)
  2326. poc--;
  2327. field_poc[0] = poc;
  2328. field_poc[1] = poc;
  2329. }
  2330. if (h->picture_structure != PICT_BOTTOM_FIELD)
  2331. h->cur_pic_ptr->field_poc[0] = field_poc[0];
  2332. if (h->picture_structure != PICT_TOP_FIELD)
  2333. h->cur_pic_ptr->field_poc[1] = field_poc[1];
  2334. cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
  2335. return 0;
  2336. }
  2337. /**
  2338. * initialize scan tables
  2339. */
  2340. static void init_scan_tables(H264Context *h)
  2341. {
  2342. int i;
  2343. for (i = 0; i < 16; i++) {
  2344. #define T(x) (x >> 2) | ((x << 2) & 0xF)
  2345. h->zigzag_scan[i] = T(zigzag_scan[i]);
  2346. h->field_scan[i] = T(field_scan[i]);
  2347. #undef T
  2348. }
  2349. for (i = 0; i < 64; i++) {
  2350. #define T(x) (x >> 3) | ((x & 7) << 3)
  2351. h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
  2352. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  2353. h->field_scan8x8[i] = T(field_scan8x8[i]);
  2354. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  2355. #undef T
  2356. }
  2357. if (h->sps.transform_bypass) { // FIXME same ugly
  2358. memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  2359. memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
  2360. memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  2361. memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
  2362. memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2363. memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2364. } else {
  2365. memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  2366. memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
  2367. memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  2368. memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
  2369. memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2370. memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2371. }
  2372. }
  2373. static int field_end(H264Context *h, int in_setup)
  2374. {
  2375. AVCodecContext *const avctx = h->avctx;
  2376. int err = 0;
  2377. h->mb_y = 0;
  2378. if (!in_setup && !h->droppable)
  2379. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  2380. h->picture_structure == PICT_BOTTOM_FIELD);
  2381. if (CONFIG_H264_VDPAU_DECODER &&
  2382. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2383. ff_vdpau_h264_set_reference_frames(h);
  2384. if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
  2385. if (!h->droppable) {
  2386. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2387. h->prev_poc_msb = h->poc_msb;
  2388. h->prev_poc_lsb = h->poc_lsb;
  2389. }
  2390. h->prev_frame_num_offset = h->frame_num_offset;
  2391. h->prev_frame_num = h->frame_num;
  2392. h->outputed_poc = h->next_outputed_poc;
  2393. }
  2394. if (avctx->hwaccel) {
  2395. if (avctx->hwaccel->end_frame(avctx) < 0)
  2396. av_log(avctx, AV_LOG_ERROR,
  2397. "hardware accelerator failed to decode picture\n");
  2398. }
  2399. if (CONFIG_H264_VDPAU_DECODER &&
  2400. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2401. ff_vdpau_h264_picture_complete(h);
  2402. /*
  2403. * FIXME: Error handling code does not seem to support interlaced
  2404. * when slices span multiple rows
  2405. * The ff_er_add_slice calls don't work right for bottom
  2406. * fields; they cause massive erroneous error concealing
  2407. * Error marking covers both fields (top and bottom).
  2408. * This causes a mismatched s->error_count
  2409. * and a bad error table. Further, the error count goes to
  2410. * INT_MAX when called for bottom field, because mb_y is
  2411. * past end by one (callers fault) and resync_mb_y != 0
  2412. * causes problems for the first MB line, too.
  2413. */
  2414. if (!FIELD_PICTURE && h->current_slice && !h->sps.new) {
  2415. h->er.cur_pic = h->cur_pic_ptr;
  2416. h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
  2417. h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
  2418. ff_er_frame_end(&h->er);
  2419. }
  2420. emms_c();
  2421. h->current_slice = 0;
  2422. return err;
  2423. }
  2424. /**
  2425. * Replicate H264 "master" context to thread contexts.
  2426. */
  2427. static int clone_slice(H264Context *dst, H264Context *src)
  2428. {
  2429. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  2430. dst->cur_pic_ptr = src->cur_pic_ptr;
  2431. dst->cur_pic = src->cur_pic;
  2432. dst->linesize = src->linesize;
  2433. dst->uvlinesize = src->uvlinesize;
  2434. dst->first_field = src->first_field;
  2435. dst->prev_poc_msb = src->prev_poc_msb;
  2436. dst->prev_poc_lsb = src->prev_poc_lsb;
  2437. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  2438. dst->prev_frame_num = src->prev_frame_num;
  2439. dst->short_ref_count = src->short_ref_count;
  2440. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  2441. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  2442. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  2443. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  2444. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  2445. return 0;
  2446. }
  2447. /**
  2448. * Compute profile from profile_idc and constraint_set?_flags.
  2449. *
  2450. * @param sps SPS
  2451. *
  2452. * @return profile as defined by FF_PROFILE_H264_*
  2453. */
  2454. int ff_h264_get_profile(SPS *sps)
  2455. {
  2456. int profile = sps->profile_idc;
  2457. switch (sps->profile_idc) {
  2458. case FF_PROFILE_H264_BASELINE:
  2459. // constraint_set1_flag set to 1
  2460. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  2461. break;
  2462. case FF_PROFILE_H264_HIGH_10:
  2463. case FF_PROFILE_H264_HIGH_422:
  2464. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  2465. // constraint_set3_flag set to 1
  2466. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  2467. break;
  2468. }
  2469. return profile;
  2470. }
  2471. static int h264_set_parameter_from_sps(H264Context *h)
  2472. {
  2473. if (h->flags & CODEC_FLAG_LOW_DELAY ||
  2474. (h->sps.bitstream_restriction_flag &&
  2475. !h->sps.num_reorder_frames)) {
  2476. if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
  2477. av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
  2478. "Reenabling low delay requires a codec flush.\n");
  2479. else
  2480. h->low_delay = 1;
  2481. }
  2482. if (h->avctx->has_b_frames < 2)
  2483. h->avctx->has_b_frames = !h->low_delay;
  2484. if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2485. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  2486. if (h->avctx->codec &&
  2487. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
  2488. (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
  2489. av_log(h->avctx, AV_LOG_ERROR,
  2490. "VDPAU decoding does not support video colorspace.\n");
  2491. return AVERROR_INVALIDDATA;
  2492. }
  2493. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
  2494. h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
  2495. (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
  2496. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  2497. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  2498. h->pixel_shift = h->sps.bit_depth_luma > 8;
  2499. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  2500. h->sps.chroma_format_idc);
  2501. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  2502. ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
  2503. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
  2504. h->sps.chroma_format_idc);
  2505. h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
  2506. ff_dsputil_init(&h->dsp, h->avctx);
  2507. ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
  2508. } else {
  2509. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
  2510. h->sps.bit_depth_luma);
  2511. return AVERROR_INVALIDDATA;
  2512. }
  2513. }
  2514. return 0;
  2515. }
  2516. static enum PixelFormat get_pixel_format(H264Context *h)
  2517. {
  2518. switch (h->sps.bit_depth_luma) {
  2519. case 9:
  2520. if (CHROMA444) {
  2521. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2522. return AV_PIX_FMT_GBRP9;
  2523. } else
  2524. return AV_PIX_FMT_YUV444P9;
  2525. } else if (CHROMA422)
  2526. return AV_PIX_FMT_YUV422P9;
  2527. else
  2528. return AV_PIX_FMT_YUV420P9;
  2529. break;
  2530. case 10:
  2531. if (CHROMA444) {
  2532. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2533. return AV_PIX_FMT_GBRP10;
  2534. } else
  2535. return AV_PIX_FMT_YUV444P10;
  2536. } else if (CHROMA422)
  2537. return AV_PIX_FMT_YUV422P10;
  2538. else
  2539. return AV_PIX_FMT_YUV420P10;
  2540. break;
  2541. case 12:
  2542. if (CHROMA444) {
  2543. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2544. return AV_PIX_FMT_GBRP12;
  2545. } else
  2546. return AV_PIX_FMT_YUV444P12;
  2547. } else if (CHROMA422)
  2548. return AV_PIX_FMT_YUV422P12;
  2549. else
  2550. return AV_PIX_FMT_YUV420P12;
  2551. break;
  2552. case 14:
  2553. if (CHROMA444) {
  2554. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2555. return AV_PIX_FMT_GBRP14;
  2556. } else
  2557. return AV_PIX_FMT_YUV444P14;
  2558. } else if (CHROMA422)
  2559. return AV_PIX_FMT_YUV422P14;
  2560. else
  2561. return AV_PIX_FMT_YUV420P14;
  2562. break;
  2563. case 8:
  2564. if (CHROMA444) {
  2565. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2566. av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
  2567. return AV_PIX_FMT_GBR24P;
  2568. } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
  2569. av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
  2570. }
  2571. return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
  2572. : AV_PIX_FMT_YUV444P;
  2573. } else if (CHROMA422) {
  2574. return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
  2575. : AV_PIX_FMT_YUV422P;
  2576. } else {
  2577. int i;
  2578. const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
  2579. h->avctx->codec->pix_fmts :
  2580. h->avctx->color_range == AVCOL_RANGE_JPEG ?
  2581. hwaccel_pixfmt_list_h264_jpeg_420 :
  2582. hwaccel_pixfmt_list_h264_420;
  2583. for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
  2584. if (fmt[i] == h->avctx->pix_fmt)
  2585. return fmt[i];
  2586. return h->avctx->get_format(h->avctx, fmt);
  2587. }
  2588. break;
  2589. default:
  2590. av_log(h->avctx, AV_LOG_ERROR,
  2591. "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
  2592. return AVERROR_INVALIDDATA;
  2593. }
  2594. }
  2595. static int h264_slice_header_init(H264Context *h, int reinit)
  2596. {
  2597. int nb_slices = (HAVE_THREADS &&
  2598. h->avctx->active_thread_type & FF_THREAD_SLICE) ?
  2599. h->avctx->thread_count : 1;
  2600. int i;
  2601. if( FFALIGN(h->avctx->width , 16 ) == h->width
  2602. && FFALIGN(h->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == h->height
  2603. && !h->sps.crop_right && !h->sps.crop_bottom
  2604. && (h->avctx->width != h->width || h->avctx->height && h->height)
  2605. ) {
  2606. av_log(h->avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
  2607. h->avctx->coded_width = h->width;
  2608. h->avctx->coded_height = h->height;
  2609. } else{
  2610. avcodec_set_dimensions(h->avctx, h->width, h->height);
  2611. h->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
  2612. 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);
  2613. }
  2614. h->avctx->sample_aspect_ratio = h->sps.sar;
  2615. av_assert0(h->avctx->sample_aspect_ratio.den);
  2616. av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
  2617. &h->chroma_x_shift, &h->chroma_y_shift);
  2618. if (h->sps.timing_info_present_flag) {
  2619. int64_t den = h->sps.time_scale;
  2620. if (h->x264_build < 44U)
  2621. den *= 2;
  2622. av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
  2623. h->sps.num_units_in_tick, den, 1 << 30);
  2624. }
  2625. h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
  2626. if (reinit)
  2627. free_tables(h, 0);
  2628. h->first_field = 0;
  2629. h->prev_interlaced_frame = 1;
  2630. init_scan_tables(h);
  2631. if (ff_h264_alloc_tables(h) < 0) {
  2632. av_log(h->avctx, AV_LOG_ERROR,
  2633. "Could not allocate memory for h264\n");
  2634. return AVERROR(ENOMEM);
  2635. }
  2636. if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
  2637. int max_slices;
  2638. if (h->mb_height)
  2639. max_slices = FFMIN(MAX_THREADS, h->mb_height);
  2640. else
  2641. max_slices = MAX_THREADS;
  2642. av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
  2643. " reducing to %d\n", nb_slices, max_slices);
  2644. nb_slices = max_slices;
  2645. }
  2646. h->slice_context_count = nb_slices;
  2647. if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
  2648. if (context_init(h) < 0) {
  2649. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2650. return -1;
  2651. }
  2652. } else {
  2653. for (i = 1; i < h->slice_context_count; i++) {
  2654. H264Context *c;
  2655. c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
  2656. c->avctx = h->avctx;
  2657. c->dsp = h->dsp;
  2658. c->vdsp = h->vdsp;
  2659. c->h264dsp = h->h264dsp;
  2660. c->h264qpel = h->h264qpel;
  2661. c->h264chroma = h->h264chroma;
  2662. c->sps = h->sps;
  2663. c->pps = h->pps;
  2664. c->pixel_shift = h->pixel_shift;
  2665. c->cur_chroma_format_idc = h->cur_chroma_format_idc;
  2666. c->width = h->width;
  2667. c->height = h->height;
  2668. c->linesize = h->linesize;
  2669. c->uvlinesize = h->uvlinesize;
  2670. c->chroma_x_shift = h->chroma_x_shift;
  2671. c->chroma_y_shift = h->chroma_y_shift;
  2672. c->qscale = h->qscale;
  2673. c->droppable = h->droppable;
  2674. c->data_partitioning = h->data_partitioning;
  2675. c->low_delay = h->low_delay;
  2676. c->mb_width = h->mb_width;
  2677. c->mb_height = h->mb_height;
  2678. c->mb_stride = h->mb_stride;
  2679. c->mb_num = h->mb_num;
  2680. c->flags = h->flags;
  2681. c->workaround_bugs = h->workaround_bugs;
  2682. c->pict_type = h->pict_type;
  2683. init_scan_tables(c);
  2684. clone_tables(c, h, i);
  2685. c->context_initialized = 1;
  2686. }
  2687. for (i = 0; i < h->slice_context_count; i++)
  2688. if (context_init(h->thread_context[i]) < 0) {
  2689. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2690. return -1;
  2691. }
  2692. }
  2693. h->context_initialized = 1;
  2694. return 0;
  2695. }
  2696. /**
  2697. * Decode a slice header.
  2698. * This will also call ff_MPV_common_init() and frame_start() as needed.
  2699. *
  2700. * @param h h264context
  2701. * @param h0 h264 master context (differs from 'h' when doing sliced based
  2702. * parallel decoding)
  2703. *
  2704. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  2705. */
  2706. static int decode_slice_header(H264Context *h, H264Context *h0)
  2707. {
  2708. unsigned int first_mb_in_slice;
  2709. unsigned int pps_id;
  2710. int num_ref_idx_active_override_flag, ret;
  2711. unsigned int slice_type, tmp, i, j;
  2712. int default_ref_list_done = 0;
  2713. int last_pic_structure, last_pic_droppable;
  2714. int must_reinit;
  2715. int needs_reinit = 0;
  2716. h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
  2717. h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
  2718. first_mb_in_slice = get_ue_golomb_long(&h->gb);
  2719. if (first_mb_in_slice == 0) { // FIXME better field boundary detection
  2720. if (h0->current_slice && FIELD_PICTURE) {
  2721. field_end(h, 1);
  2722. }
  2723. h0->current_slice = 0;
  2724. if (!h0->first_field) {
  2725. if (h->cur_pic_ptr && !h->droppable &&
  2726. h->cur_pic_ptr->owner2 == h) {
  2727. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  2728. h->picture_structure == PICT_BOTTOM_FIELD);
  2729. }
  2730. h->cur_pic_ptr = NULL;
  2731. }
  2732. }
  2733. slice_type = get_ue_golomb_31(&h->gb);
  2734. if (slice_type > 9) {
  2735. av_log(h->avctx, AV_LOG_ERROR,
  2736. "slice type too large (%d) at %d %d\n",
  2737. slice_type, h->mb_x, h->mb_y);
  2738. return -1;
  2739. }
  2740. if (slice_type > 4) {
  2741. slice_type -= 5;
  2742. h->slice_type_fixed = 1;
  2743. } else
  2744. h->slice_type_fixed = 0;
  2745. slice_type = golomb_to_pict_type[slice_type];
  2746. if (slice_type == AV_PICTURE_TYPE_I ||
  2747. (h0->current_slice != 0 &&
  2748. slice_type == h0->last_slice_type &&
  2749. !memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
  2750. default_ref_list_done = 1;
  2751. }
  2752. h->slice_type = slice_type;
  2753. h->slice_type_nos = slice_type & 3;
  2754. // to make a few old functions happy, it's wrong though
  2755. h->pict_type = h->slice_type;
  2756. pps_id = get_ue_golomb(&h->gb);
  2757. if (pps_id >= MAX_PPS_COUNT) {
  2758. av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
  2759. return -1;
  2760. }
  2761. if (!h0->pps_buffers[pps_id]) {
  2762. av_log(h->avctx, AV_LOG_ERROR,
  2763. "non-existing PPS %u referenced\n",
  2764. pps_id);
  2765. return -1;
  2766. }
  2767. h->pps = *h0->pps_buffers[pps_id];
  2768. if (!h0->sps_buffers[h->pps.sps_id]) {
  2769. av_log(h->avctx, AV_LOG_ERROR,
  2770. "non-existing SPS %u referenced\n",
  2771. h->pps.sps_id);
  2772. return -1;
  2773. }
  2774. if (h->pps.sps_id != h->current_sps_id ||
  2775. h0->sps_buffers[h->pps.sps_id]->new) {
  2776. h0->sps_buffers[h->pps.sps_id]->new = 0;
  2777. h->current_sps_id = h->pps.sps_id;
  2778. h->sps = *h0->sps_buffers[h->pps.sps_id];
  2779. if (h->mb_width != h->sps.mb_width ||
  2780. h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
  2781. h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2782. h->cur_chroma_format_idc != h->sps.chroma_format_idc
  2783. )
  2784. needs_reinit = 1;
  2785. if (h->bit_depth_luma != h->sps.bit_depth_luma ||
  2786. h->chroma_format_idc != h->sps.chroma_format_idc) {
  2787. h->bit_depth_luma = h->sps.bit_depth_luma;
  2788. h->chroma_format_idc = h->sps.chroma_format_idc;
  2789. needs_reinit = 1;
  2790. }
  2791. if ((ret = h264_set_parameter_from_sps(h)) < 0)
  2792. return ret;
  2793. }
  2794. h->avctx->profile = ff_h264_get_profile(&h->sps);
  2795. h->avctx->level = h->sps.level_idc;
  2796. h->avctx->refs = h->sps.ref_frame_count;
  2797. must_reinit = (h->context_initialized &&
  2798. ( 16*h->sps.mb_width != h->avctx->coded_width
  2799. || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
  2800. || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
  2801. || h->cur_chroma_format_idc != h->sps.chroma_format_idc
  2802. || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)));
  2803. if (h0->avctx->pix_fmt != get_pixel_format(h0))
  2804. must_reinit = 1;
  2805. h->mb_width = h->sps.mb_width;
  2806. h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  2807. h->mb_num = h->mb_width * h->mb_height;
  2808. h->mb_stride = h->mb_width + 1;
  2809. h->b_stride = h->mb_width * 4;
  2810. h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  2811. h->width = 16 * h->mb_width;
  2812. h->height = 16 * h->mb_height;
  2813. if (h->sps.video_signal_type_present_flag) {
  2814. h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
  2815. : AVCOL_RANGE_MPEG;
  2816. if (h->sps.colour_description_present_flag) {
  2817. if (h->avctx->colorspace != h->sps.colorspace)
  2818. needs_reinit = 1;
  2819. h->avctx->color_primaries = h->sps.color_primaries;
  2820. h->avctx->color_trc = h->sps.color_trc;
  2821. h->avctx->colorspace = h->sps.colorspace;
  2822. }
  2823. }
  2824. if (h->context_initialized &&
  2825. (
  2826. needs_reinit ||
  2827. must_reinit)) {
  2828. if (h != h0) {
  2829. av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
  2830. "slice %d\n", h0->current_slice + 1);
  2831. return AVERROR_INVALIDDATA;
  2832. }
  2833. flush_change(h);
  2834. if ((ret = get_pixel_format(h)) < 0)
  2835. return ret;
  2836. h->avctx->pix_fmt = ret;
  2837. av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
  2838. "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
  2839. if ((ret = h264_slice_header_init(h, 1)) < 0) {
  2840. av_log(h->avctx, AV_LOG_ERROR,
  2841. "h264_slice_header_init() failed\n");
  2842. return ret;
  2843. }
  2844. }
  2845. if (!h->context_initialized) {
  2846. if (h != h0) {
  2847. av_log(h->avctx, AV_LOG_ERROR,
  2848. "Cannot (re-)initialize context during parallel decoding.\n");
  2849. return -1;
  2850. }
  2851. if ((ret = get_pixel_format(h)) < 0)
  2852. return ret;
  2853. h->avctx->pix_fmt = ret;
  2854. if ((ret = h264_slice_header_init(h, 0)) < 0) {
  2855. av_log(h->avctx, AV_LOG_ERROR,
  2856. "h264_slice_header_init() failed\n");
  2857. return ret;
  2858. }
  2859. }
  2860. if (h == h0 && h->dequant_coeff_pps != pps_id) {
  2861. h->dequant_coeff_pps = pps_id;
  2862. init_dequant_tables(h);
  2863. }
  2864. h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
  2865. h->mb_mbaff = 0;
  2866. h->mb_aff_frame = 0;
  2867. last_pic_structure = h0->picture_structure;
  2868. last_pic_droppable = h0->droppable;
  2869. h->droppable = h->nal_ref_idc == 0;
  2870. if (h->sps.frame_mbs_only_flag) {
  2871. h->picture_structure = PICT_FRAME;
  2872. } else {
  2873. if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
  2874. av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
  2875. return -1;
  2876. }
  2877. if (get_bits1(&h->gb)) { // field_pic_flag
  2878. h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
  2879. } else {
  2880. h->picture_structure = PICT_FRAME;
  2881. h->mb_aff_frame = h->sps.mb_aff;
  2882. }
  2883. }
  2884. h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
  2885. if (h0->current_slice != 0) {
  2886. if (last_pic_structure != h->picture_structure ||
  2887. last_pic_droppable != h->droppable) {
  2888. av_log(h->avctx, AV_LOG_ERROR,
  2889. "Changing field mode (%d -> %d) between slices is not allowed\n",
  2890. last_pic_structure, h->picture_structure);
  2891. h->picture_structure = last_pic_structure;
  2892. h->droppable = last_pic_droppable;
  2893. return AVERROR_INVALIDDATA;
  2894. } else if (!h0->cur_pic_ptr) {
  2895. av_log(h->avctx, AV_LOG_ERROR,
  2896. "unset cur_pic_ptr on %d. slice\n",
  2897. h0->current_slice + 1);
  2898. return AVERROR_INVALIDDATA;
  2899. }
  2900. } else {
  2901. /* Shorten frame num gaps so we don't have to allocate reference
  2902. * frames just to throw them away */
  2903. if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
  2904. int unwrap_prev_frame_num = h->prev_frame_num;
  2905. int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2906. if (unwrap_prev_frame_num > h->frame_num)
  2907. unwrap_prev_frame_num -= max_frame_num;
  2908. if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
  2909. unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
  2910. if (unwrap_prev_frame_num < 0)
  2911. unwrap_prev_frame_num += max_frame_num;
  2912. h->prev_frame_num = unwrap_prev_frame_num;
  2913. }
  2914. }
  2915. /* See if we have a decoded first field looking for a pair...
  2916. * Here, we're using that to see if we should mark previously
  2917. * decode frames as "finished".
  2918. * We have to do that before the "dummy" in-between frame allocation,
  2919. * since that can modify h->cur_pic_ptr. */
  2920. if (h0->first_field) {
  2921. assert(h0->cur_pic_ptr);
  2922. assert(h0->cur_pic_ptr->f.data[0]);
  2923. assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
  2924. /* Mark old field/frame as completed */
  2925. if (!last_pic_droppable && h0->cur_pic_ptr->owner2 == h0) {
  2926. ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
  2927. last_pic_structure == PICT_BOTTOM_FIELD);
  2928. }
  2929. /* figure out if we have a complementary field pair */
  2930. if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
  2931. /* Previous field is unmatched. Don't display it, but let it
  2932. * remain for reference if marked as such. */
  2933. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  2934. ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
  2935. last_pic_structure == PICT_TOP_FIELD);
  2936. }
  2937. } else {
  2938. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  2939. /* This and previous field were reference, but had
  2940. * different frame_nums. Consider this field first in
  2941. * pair. Throw away previous field except for reference
  2942. * purposes. */
  2943. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  2944. ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
  2945. last_pic_structure == PICT_TOP_FIELD);
  2946. }
  2947. } else {
  2948. /* Second field in complementary pair */
  2949. if (!((last_pic_structure == PICT_TOP_FIELD &&
  2950. h->picture_structure == PICT_BOTTOM_FIELD) ||
  2951. (last_pic_structure == PICT_BOTTOM_FIELD &&
  2952. h->picture_structure == PICT_TOP_FIELD))) {
  2953. av_log(h->avctx, AV_LOG_ERROR,
  2954. "Invalid field mode combination %d/%d\n",
  2955. last_pic_structure, h->picture_structure);
  2956. h->picture_structure = last_pic_structure;
  2957. h->droppable = last_pic_droppable;
  2958. return AVERROR_INVALIDDATA;
  2959. } else if (last_pic_droppable != h->droppable) {
  2960. av_log(h->avctx, AV_LOG_ERROR,
  2961. "Cannot combine reference and non-reference fields in the same frame\n");
  2962. av_log_ask_for_sample(h->avctx, NULL);
  2963. h->picture_structure = last_pic_structure;
  2964. h->droppable = last_pic_droppable;
  2965. return AVERROR_PATCHWELCOME;
  2966. }
  2967. /* Take ownership of this buffer. Note that if another thread owned
  2968. * the first field of this buffer, we're not operating on that pointer,
  2969. * so the original thread is still responsible for reporting progress
  2970. * on that first field (or if that was us, we just did that above).
  2971. * By taking ownership, we assign responsibility to ourselves to
  2972. * report progress on the second field. */
  2973. h0->cur_pic_ptr->owner2 = h0;
  2974. }
  2975. }
  2976. }
  2977. while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !h0->first_field &&
  2978. h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
  2979. Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2980. av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  2981. h->frame_num, h->prev_frame_num);
  2982. if (!h->sps.gaps_in_frame_num_allowed_flag)
  2983. for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
  2984. h->last_pocs[i] = INT_MIN;
  2985. if (ff_h264_frame_start(h) < 0)
  2986. return -1;
  2987. h->prev_frame_num++;
  2988. h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
  2989. h->cur_pic_ptr->frame_num = h->prev_frame_num;
  2990. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 0);
  2991. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 1);
  2992. if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
  2993. h->avctx->err_recognition & AV_EF_EXPLODE)
  2994. return ret;
  2995. if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
  2996. (h->avctx->err_recognition & AV_EF_EXPLODE))
  2997. return AVERROR_INVALIDDATA;
  2998. /* Error concealment: if a ref is missing, copy the previous ref in its place.
  2999. * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
  3000. * about there being no actual duplicates.
  3001. * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
  3002. * concealing a lost frame, this probably isn't noticeable by comparison, but it should
  3003. * be fixed. */
  3004. if (h->short_ref_count) {
  3005. if (prev) {
  3006. av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
  3007. (const uint8_t **)prev->f.data, prev->f.linesize,
  3008. h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16);
  3009. h->short_ref[0]->poc = prev->poc + 2;
  3010. }
  3011. h->short_ref[0]->frame_num = h->prev_frame_num;
  3012. }
  3013. }
  3014. /* See if we have a decoded first field looking for a pair...
  3015. * We're using that to see whether to continue decoding in that
  3016. * frame, or to allocate a new one. */
  3017. if (h0->first_field) {
  3018. assert(h0->cur_pic_ptr);
  3019. assert(h0->cur_pic_ptr->f.data[0]);
  3020. assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
  3021. /* figure out if we have a complementary field pair */
  3022. if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
  3023. /* Previous field is unmatched. Don't display it, but let it
  3024. * remain for reference if marked as such. */
  3025. h0->cur_pic_ptr = NULL;
  3026. h0->first_field = FIELD_PICTURE;
  3027. } else {
  3028. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  3029. ff_thread_report_progress((AVFrame*)h0->cur_pic_ptr, INT_MAX,
  3030. h0->picture_structure==PICT_BOTTOM_FIELD);
  3031. /* This and the previous field had different frame_nums.
  3032. * Consider this field first in pair. Throw away previous
  3033. * one except for reference purposes. */
  3034. h0->first_field = 1;
  3035. h0->cur_pic_ptr = NULL;
  3036. } else {
  3037. /* Second field in complementary pair */
  3038. h0->first_field = 0;
  3039. }
  3040. }
  3041. } else {
  3042. /* Frame or first field in a potentially complementary pair */
  3043. h0->first_field = FIELD_PICTURE;
  3044. }
  3045. if (!FIELD_PICTURE || h0->first_field) {
  3046. if (ff_h264_frame_start(h) < 0) {
  3047. h0->first_field = 0;
  3048. return -1;
  3049. }
  3050. } else {
  3051. release_unused_pictures(h, 0);
  3052. }
  3053. }
  3054. if (h != h0 && (ret = clone_slice(h, h0)) < 0)
  3055. return ret;
  3056. /* can't be in alloc_tables because linesize isn't known there.
  3057. * FIXME: redo bipred weight to not require extra buffer? */
  3058. for (i = 0; i < h->slice_context_count; i++)
  3059. if (h->thread_context[i]) {
  3060. ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
  3061. if (ret < 0)
  3062. return ret;
  3063. }
  3064. h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
  3065. av_assert1(h->mb_num == h->mb_width * h->mb_height);
  3066. if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= h->mb_num ||
  3067. first_mb_in_slice >= h->mb_num) {
  3068. av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  3069. return -1;
  3070. }
  3071. h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
  3072. h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE;
  3073. if (h->picture_structure == PICT_BOTTOM_FIELD)
  3074. h->resync_mb_y = h->mb_y = h->mb_y + 1;
  3075. av_assert1(h->mb_y < h->mb_height);
  3076. if (h->picture_structure == PICT_FRAME) {
  3077. h->curr_pic_num = h->frame_num;
  3078. h->max_pic_num = 1 << h->sps.log2_max_frame_num;
  3079. } else {
  3080. h->curr_pic_num = 2 * h->frame_num + 1;
  3081. h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
  3082. }
  3083. if (h->nal_unit_type == NAL_IDR_SLICE)
  3084. get_ue_golomb(&h->gb); /* idr_pic_id */
  3085. if (h->sps.poc_type == 0) {
  3086. h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
  3087. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  3088. h->delta_poc_bottom = get_se_golomb(&h->gb);
  3089. }
  3090. if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
  3091. h->delta_poc[0] = get_se_golomb(&h->gb);
  3092. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  3093. h->delta_poc[1] = get_se_golomb(&h->gb);
  3094. }
  3095. init_poc(h);
  3096. if (h->pps.redundant_pic_cnt_present)
  3097. h->redundant_pic_count = get_ue_golomb(&h->gb);
  3098. // set defaults, might be overridden a few lines later
  3099. h->ref_count[0] = h->pps.ref_count[0];
  3100. h->ref_count[1] = h->pps.ref_count[1];
  3101. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  3102. unsigned max[2];
  3103. max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
  3104. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  3105. h->direct_spatial_mv_pred = get_bits1(&h->gb);
  3106. num_ref_idx_active_override_flag = get_bits1(&h->gb);
  3107. if (num_ref_idx_active_override_flag) {
  3108. h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
  3109. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3110. h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
  3111. } else
  3112. // full range is spec-ok in this case, even for frames
  3113. h->ref_count[1] = 1;
  3114. }
  3115. if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
  3116. 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]);
  3117. h->ref_count[0] = h->ref_count[1] = 1;
  3118. return AVERROR_INVALIDDATA;
  3119. }
  3120. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  3121. h->list_count = 2;
  3122. else
  3123. h->list_count = 1;
  3124. } else
  3125. h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
  3126. if (!default_ref_list_done)
  3127. ff_h264_fill_default_ref_list(h);
  3128. if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
  3129. ff_h264_decode_ref_pic_list_reordering(h) < 0) {
  3130. h->ref_count[1] = h->ref_count[0] = 0;
  3131. return -1;
  3132. }
  3133. if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
  3134. (h->pps.weighted_bipred_idc == 1 &&
  3135. h->slice_type_nos == AV_PICTURE_TYPE_B))
  3136. pred_weight_table(h);
  3137. else if (h->pps.weighted_bipred_idc == 2 &&
  3138. h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3139. implicit_weight_table(h, -1);
  3140. } else {
  3141. h->use_weight = 0;
  3142. for (i = 0; i < 2; i++) {
  3143. h->luma_weight_flag[i] = 0;
  3144. h->chroma_weight_flag[i] = 0;
  3145. }
  3146. }
  3147. // If frame-mt is enabled, only update mmco tables for the first slice
  3148. // in a field. Subsequent slices can temporarily clobber h->mmco_index
  3149. // or h->mmco, which will cause ref list mix-ups and decoding errors
  3150. // further down the line. This may break decoding if the first slice is
  3151. // corrupt, thus we only do this if frame-mt is enabled.
  3152. if (h->nal_ref_idc &&
  3153. ff_h264_decode_ref_pic_marking(h0, &h->gb,
  3154. !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
  3155. h0->current_slice == 0) < 0 &&
  3156. (h->avctx->err_recognition & AV_EF_EXPLODE))
  3157. return AVERROR_INVALIDDATA;
  3158. if (FRAME_MBAFF) {
  3159. ff_h264_fill_mbaff_ref_list(h);
  3160. if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3161. implicit_weight_table(h, 0);
  3162. implicit_weight_table(h, 1);
  3163. }
  3164. }
  3165. if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
  3166. ff_h264_direct_dist_scale_factor(h);
  3167. ff_h264_direct_ref_list_init(h);
  3168. if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
  3169. tmp = get_ue_golomb_31(&h->gb);
  3170. if (tmp > 2) {
  3171. av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  3172. return -1;
  3173. }
  3174. h->cabac_init_idc = tmp;
  3175. }
  3176. h->last_qscale_diff = 0;
  3177. tmp = h->pps.init_qp + get_se_golomb(&h->gb);
  3178. if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
  3179. av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  3180. return -1;
  3181. }
  3182. h->qscale = tmp;
  3183. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  3184. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  3185. // FIXME qscale / qp ... stuff
  3186. if (h->slice_type == AV_PICTURE_TYPE_SP)
  3187. get_bits1(&h->gb); /* sp_for_switch_flag */
  3188. if (h->slice_type == AV_PICTURE_TYPE_SP ||
  3189. h->slice_type == AV_PICTURE_TYPE_SI)
  3190. get_se_golomb(&h->gb); /* slice_qs_delta */
  3191. h->deblocking_filter = 1;
  3192. h->slice_alpha_c0_offset = 52;
  3193. h->slice_beta_offset = 52;
  3194. if (h->pps.deblocking_filter_parameters_present) {
  3195. tmp = get_ue_golomb_31(&h->gb);
  3196. if (tmp > 2) {
  3197. av_log(h->avctx, AV_LOG_ERROR,
  3198. "deblocking_filter_idc %u out of range\n", tmp);
  3199. return -1;
  3200. }
  3201. h->deblocking_filter = tmp;
  3202. if (h->deblocking_filter < 2)
  3203. h->deblocking_filter ^= 1; // 1<->0
  3204. if (h->deblocking_filter) {
  3205. h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
  3206. h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
  3207. if (h->slice_alpha_c0_offset > 104U ||
  3208. h->slice_beta_offset > 104U) {
  3209. av_log(h->avctx, AV_LOG_ERROR,
  3210. "deblocking filter parameters %d %d out of range\n",
  3211. h->slice_alpha_c0_offset, h->slice_beta_offset);
  3212. return -1;
  3213. }
  3214. }
  3215. }
  3216. if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  3217. (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  3218. h->slice_type_nos != AV_PICTURE_TYPE_I) ||
  3219. (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  3220. h->slice_type_nos == AV_PICTURE_TYPE_B) ||
  3221. (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  3222. h->nal_ref_idc == 0))
  3223. h->deblocking_filter = 0;
  3224. if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
  3225. if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
  3226. /* Cheat slightly for speed:
  3227. * Do not bother to deblock across slices. */
  3228. h->deblocking_filter = 2;
  3229. } else {
  3230. h0->max_contexts = 1;
  3231. if (!h0->single_decode_warning) {
  3232. av_log(h->avctx, AV_LOG_INFO,
  3233. "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  3234. h0->single_decode_warning = 1;
  3235. }
  3236. if (h != h0) {
  3237. av_log(h->avctx, AV_LOG_ERROR,
  3238. "Deblocking switched inside frame.\n");
  3239. return 1;
  3240. }
  3241. }
  3242. }
  3243. h->qp_thresh = 15 + 52 -
  3244. FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
  3245. FFMAX3(0,
  3246. h->pps.chroma_qp_index_offset[0],
  3247. h->pps.chroma_qp_index_offset[1]) +
  3248. 6 * (h->sps.bit_depth_luma - 8);
  3249. h0->last_slice_type = slice_type;
  3250. memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
  3251. h->slice_num = ++h0->current_slice;
  3252. if (h->slice_num)
  3253. h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
  3254. if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
  3255. && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
  3256. && h->slice_num >= MAX_SLICES) {
  3257. //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
  3258. 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);
  3259. }
  3260. for (j = 0; j < 2; j++) {
  3261. int id_list[16];
  3262. int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
  3263. for (i = 0; i < 16; i++) {
  3264. id_list[i] = 60;
  3265. if (h->ref_list[j][i].f.data[0]) {
  3266. int k;
  3267. uint8_t *base = h->ref_list[j][i].f.base[0];
  3268. for (k = 0; k < h->short_ref_count; k++)
  3269. if (h->short_ref[k]->f.base[0] == base) {
  3270. id_list[i] = k;
  3271. break;
  3272. }
  3273. for (k = 0; k < h->long_ref_count; k++)
  3274. if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
  3275. id_list[i] = h->short_ref_count + k;
  3276. break;
  3277. }
  3278. }
  3279. }
  3280. ref2frm[0] =
  3281. ref2frm[1] = -1;
  3282. for (i = 0; i < 16; i++)
  3283. ref2frm[i + 2] = 4 * id_list[i] +
  3284. (h->ref_list[j][i].f.reference & 3);
  3285. ref2frm[18 + 0] =
  3286. ref2frm[18 + 1] = -1;
  3287. for (i = 16; i < 48; i++)
  3288. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  3289. (h->ref_list[j][i].f.reference & 3);
  3290. }
  3291. if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
  3292. av_log(h->avctx, AV_LOG_DEBUG,
  3293. "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",
  3294. h->slice_num,
  3295. (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  3296. first_mb_in_slice,
  3297. av_get_picture_type_char(h->slice_type),
  3298. h->slice_type_fixed ? " fix" : "",
  3299. h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  3300. pps_id, h->frame_num,
  3301. h->cur_pic_ptr->field_poc[0],
  3302. h->cur_pic_ptr->field_poc[1],
  3303. h->ref_count[0], h->ref_count[1],
  3304. h->qscale,
  3305. h->deblocking_filter,
  3306. h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
  3307. h->use_weight,
  3308. h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
  3309. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  3310. }
  3311. return 0;
  3312. }
  3313. int ff_h264_get_slice_type(const H264Context *h)
  3314. {
  3315. switch (h->slice_type) {
  3316. case AV_PICTURE_TYPE_P:
  3317. return 0;
  3318. case AV_PICTURE_TYPE_B:
  3319. return 1;
  3320. case AV_PICTURE_TYPE_I:
  3321. return 2;
  3322. case AV_PICTURE_TYPE_SP:
  3323. return 3;
  3324. case AV_PICTURE_TYPE_SI:
  3325. return 4;
  3326. default:
  3327. return -1;
  3328. }
  3329. }
  3330. static av_always_inline void fill_filter_caches_inter(H264Context *h,
  3331. int mb_type, int top_xy,
  3332. int left_xy[LEFT_MBS],
  3333. int top_type,
  3334. int left_type[LEFT_MBS],
  3335. int mb_xy, int list)
  3336. {
  3337. int b_stride = h->b_stride;
  3338. int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
  3339. int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
  3340. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  3341. if (USES_LIST(top_type, list)) {
  3342. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  3343. const int b8_xy = 4 * top_xy + 2;
  3344. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  3345. AV_COPY128(mv_dst - 1 * 8, h->cur_pic.f.motion_val[list][b_xy + 0]);
  3346. ref_cache[0 - 1 * 8] =
  3347. ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 0]];
  3348. ref_cache[2 - 1 * 8] =
  3349. ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 1]];
  3350. } else {
  3351. AV_ZERO128(mv_dst - 1 * 8);
  3352. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3353. }
  3354. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  3355. if (USES_LIST(left_type[LTOP], list)) {
  3356. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  3357. const int b8_xy = 4 * left_xy[LTOP] + 1;
  3358. int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  3359. AV_COPY32(mv_dst - 1 + 0, h->cur_pic.f.motion_val[list][b_xy + b_stride * 0]);
  3360. AV_COPY32(mv_dst - 1 + 8, h->cur_pic.f.motion_val[list][b_xy + b_stride * 1]);
  3361. AV_COPY32(mv_dst - 1 + 16, h->cur_pic.f.motion_val[list][b_xy + b_stride * 2]);
  3362. AV_COPY32(mv_dst - 1 + 24, h->cur_pic.f.motion_val[list][b_xy + b_stride * 3]);
  3363. ref_cache[-1 + 0] =
  3364. ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 0]];
  3365. ref_cache[-1 + 16] =
  3366. ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 1]];
  3367. } else {
  3368. AV_ZERO32(mv_dst - 1 + 0);
  3369. AV_ZERO32(mv_dst - 1 + 8);
  3370. AV_ZERO32(mv_dst - 1 + 16);
  3371. AV_ZERO32(mv_dst - 1 + 24);
  3372. ref_cache[-1 + 0] =
  3373. ref_cache[-1 + 8] =
  3374. ref_cache[-1 + 16] =
  3375. ref_cache[-1 + 24] = LIST_NOT_USED;
  3376. }
  3377. }
  3378. }
  3379. if (!USES_LIST(mb_type, list)) {
  3380. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  3381. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3382. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3383. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3384. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3385. return;
  3386. }
  3387. {
  3388. int8_t *ref = &h->cur_pic.f.ref_index[list][4 * mb_xy];
  3389. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  3390. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
  3391. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
  3392. AV_WN32A(&ref_cache[0 * 8], ref01);
  3393. AV_WN32A(&ref_cache[1 * 8], ref01);
  3394. AV_WN32A(&ref_cache[2 * 8], ref23);
  3395. AV_WN32A(&ref_cache[3 * 8], ref23);
  3396. }
  3397. {
  3398. int16_t(*mv_src)[2] = &h->cur_pic.f.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
  3399. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  3400. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  3401. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  3402. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  3403. }
  3404. }
  3405. /**
  3406. *
  3407. * @return non zero if the loop filter can be skipped
  3408. */
  3409. static int fill_filter_caches(H264Context *h, int mb_type)
  3410. {
  3411. const int mb_xy = h->mb_xy;
  3412. int top_xy, left_xy[LEFT_MBS];
  3413. int top_type, left_type[LEFT_MBS];
  3414. uint8_t *nnz;
  3415. uint8_t *nnz_cache;
  3416. top_xy = mb_xy - (h->mb_stride << MB_FIELD);
  3417. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  3418. * stuff, I can't imagine that these complex rules are worth it. */
  3419. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  3420. if (FRAME_MBAFF) {
  3421. const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.f.mb_type[mb_xy - 1]);
  3422. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  3423. if (h->mb_y & 1) {
  3424. if (left_mb_field_flag != curr_mb_field_flag)
  3425. left_xy[LTOP] -= h->mb_stride;
  3426. } else {
  3427. if (curr_mb_field_flag)
  3428. top_xy += h->mb_stride &
  3429. (((h->cur_pic.f.mb_type[top_xy] >> 7) & 1) - 1);
  3430. if (left_mb_field_flag != curr_mb_field_flag)
  3431. left_xy[LBOT] += h->mb_stride;
  3432. }
  3433. }
  3434. h->top_mb_xy = top_xy;
  3435. h->left_mb_xy[LTOP] = left_xy[LTOP];
  3436. h->left_mb_xy[LBOT] = left_xy[LBOT];
  3437. {
  3438. /* For sufficiently low qp, filtering wouldn't do anything.
  3439. * This is a conservative estimate: could also check beta_offset
  3440. * and more accurate chroma_qp. */
  3441. int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  3442. int qp = h->cur_pic.f.qscale_table[mb_xy];
  3443. if (qp <= qp_thresh &&
  3444. (left_xy[LTOP] < 0 ||
  3445. ((qp + h->cur_pic.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  3446. (top_xy < 0 ||
  3447. ((qp + h->cur_pic.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  3448. if (!FRAME_MBAFF)
  3449. return 1;
  3450. if ((left_xy[LTOP] < 0 ||
  3451. ((qp + h->cur_pic.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  3452. (top_xy < h->mb_stride ||
  3453. ((qp + h->cur_pic.f.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
  3454. return 1;
  3455. }
  3456. }
  3457. top_type = h->cur_pic.f.mb_type[top_xy];
  3458. left_type[LTOP] = h->cur_pic.f.mb_type[left_xy[LTOP]];
  3459. left_type[LBOT] = h->cur_pic.f.mb_type[left_xy[LBOT]];
  3460. if (h->deblocking_filter == 2) {
  3461. if (h->slice_table[top_xy] != h->slice_num)
  3462. top_type = 0;
  3463. if (h->slice_table[left_xy[LBOT]] != h->slice_num)
  3464. left_type[LTOP] = left_type[LBOT] = 0;
  3465. } else {
  3466. if (h->slice_table[top_xy] == 0xFFFF)
  3467. top_type = 0;
  3468. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  3469. left_type[LTOP] = left_type[LBOT] = 0;
  3470. }
  3471. h->top_type = top_type;
  3472. h->left_type[LTOP] = left_type[LTOP];
  3473. h->left_type[LBOT] = left_type[LBOT];
  3474. if (IS_INTRA(mb_type))
  3475. return 0;
  3476. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3477. top_type, left_type, mb_xy, 0);
  3478. if (h->list_count == 2)
  3479. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3480. top_type, left_type, mb_xy, 1);
  3481. nnz = h->non_zero_count[mb_xy];
  3482. nnz_cache = h->non_zero_count_cache;
  3483. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  3484. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  3485. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  3486. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  3487. h->cbp = h->cbp_table[mb_xy];
  3488. if (top_type) {
  3489. nnz = h->non_zero_count[top_xy];
  3490. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  3491. }
  3492. if (left_type[LTOP]) {
  3493. nnz = h->non_zero_count[left_xy[LTOP]];
  3494. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  3495. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  3496. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  3497. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  3498. }
  3499. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  3500. * from what the loop filter needs */
  3501. if (!CABAC && h->pps.transform_8x8_mode) {
  3502. if (IS_8x8DCT(top_type)) {
  3503. nnz_cache[4 + 8 * 0] =
  3504. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  3505. nnz_cache[6 + 8 * 0] =
  3506. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  3507. }
  3508. if (IS_8x8DCT(left_type[LTOP])) {
  3509. nnz_cache[3 + 8 * 1] =
  3510. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  3511. }
  3512. if (IS_8x8DCT(left_type[LBOT])) {
  3513. nnz_cache[3 + 8 * 3] =
  3514. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  3515. }
  3516. if (IS_8x8DCT(mb_type)) {
  3517. nnz_cache[scan8[0]] =
  3518. nnz_cache[scan8[1]] =
  3519. nnz_cache[scan8[2]] =
  3520. nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
  3521. nnz_cache[scan8[0 + 4]] =
  3522. nnz_cache[scan8[1 + 4]] =
  3523. nnz_cache[scan8[2 + 4]] =
  3524. nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
  3525. nnz_cache[scan8[0 + 8]] =
  3526. nnz_cache[scan8[1 + 8]] =
  3527. nnz_cache[scan8[2 + 8]] =
  3528. nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
  3529. nnz_cache[scan8[0 + 12]] =
  3530. nnz_cache[scan8[1 + 12]] =
  3531. nnz_cache[scan8[2 + 12]] =
  3532. nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
  3533. }
  3534. }
  3535. return 0;
  3536. }
  3537. static void loop_filter(H264Context *h, int start_x, int end_x)
  3538. {
  3539. uint8_t *dest_y, *dest_cb, *dest_cr;
  3540. int linesize, uvlinesize, mb_x, mb_y;
  3541. const int end_mb_y = h->mb_y + FRAME_MBAFF;
  3542. const int old_slice_type = h->slice_type;
  3543. const int pixel_shift = h->pixel_shift;
  3544. const int block_h = 16 >> h->chroma_y_shift;
  3545. if (h->deblocking_filter) {
  3546. for (mb_x = start_x; mb_x < end_x; mb_x++)
  3547. for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
  3548. int mb_xy, mb_type;
  3549. mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
  3550. h->slice_num = h->slice_table[mb_xy];
  3551. mb_type = h->cur_pic.f.mb_type[mb_xy];
  3552. h->list_count = h->list_counts[mb_xy];
  3553. if (FRAME_MBAFF)
  3554. h->mb_mbaff =
  3555. h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  3556. h->mb_x = mb_x;
  3557. h->mb_y = mb_y;
  3558. dest_y = h->cur_pic.f.data[0] +
  3559. ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
  3560. dest_cb = h->cur_pic.f.data[1] +
  3561. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3562. mb_y * h->uvlinesize * block_h;
  3563. dest_cr = h->cur_pic.f.data[2] +
  3564. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3565. mb_y * h->uvlinesize * block_h;
  3566. // FIXME simplify above
  3567. if (MB_FIELD) {
  3568. linesize = h->mb_linesize = h->linesize * 2;
  3569. uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
  3570. if (mb_y & 1) { // FIXME move out of this function?
  3571. dest_y -= h->linesize * 15;
  3572. dest_cb -= h->uvlinesize * (block_h - 1);
  3573. dest_cr -= h->uvlinesize * (block_h - 1);
  3574. }
  3575. } else {
  3576. linesize = h->mb_linesize = h->linesize;
  3577. uvlinesize = h->mb_uvlinesize = h->uvlinesize;
  3578. }
  3579. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
  3580. uvlinesize, 0);
  3581. if (fill_filter_caches(h, mb_type))
  3582. continue;
  3583. h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.f.qscale_table[mb_xy]);
  3584. h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.f.qscale_table[mb_xy]);
  3585. if (FRAME_MBAFF) {
  3586. ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  3587. linesize, uvlinesize);
  3588. } else {
  3589. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
  3590. dest_cr, linesize, uvlinesize);
  3591. }
  3592. }
  3593. }
  3594. h->slice_type = old_slice_type;
  3595. h->mb_x = end_x;
  3596. h->mb_y = end_mb_y - FRAME_MBAFF;
  3597. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  3598. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  3599. }
  3600. static void predict_field_decoding_flag(H264Context *h)
  3601. {
  3602. const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
  3603. int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
  3604. h->cur_pic.f.mb_type[mb_xy - 1] :
  3605. (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
  3606. h->cur_pic.f.mb_type[mb_xy - h->mb_stride] : 0;
  3607. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3608. }
  3609. /**
  3610. * Draw edges and report progress for the last MB row.
  3611. */
  3612. static void decode_finish_row(H264Context *h)
  3613. {
  3614. int top = 16 * (h->mb_y >> FIELD_PICTURE);
  3615. int pic_height = 16 * h->mb_height >> FIELD_PICTURE;
  3616. int height = 16 << FRAME_MBAFF;
  3617. int deblock_border = (16 + 4) << FRAME_MBAFF;
  3618. if (h->deblocking_filter) {
  3619. if ((top + height) >= pic_height)
  3620. height += deblock_border;
  3621. top -= deblock_border;
  3622. }
  3623. if (top >= pic_height || (top + height) < 0)
  3624. return;
  3625. height = FFMIN(height, pic_height - top);
  3626. if (top < 0) {
  3627. height = top + height;
  3628. top = 0;
  3629. }
  3630. ff_h264_draw_horiz_band(h, top, height);
  3631. if (h->droppable)
  3632. return;
  3633. ff_thread_report_progress(&h->cur_pic_ptr->f, top + height - 1,
  3634. h->picture_structure == PICT_BOTTOM_FIELD);
  3635. }
  3636. static void er_add_slice(H264Context *h, int startx, int starty,
  3637. int endx, int endy, int status)
  3638. {
  3639. ERContext *er = &h->er;
  3640. er->ref_count = h->ref_count[0];
  3641. ff_er_add_slice(er, startx, starty, endx, endy, status);
  3642. }
  3643. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  3644. {
  3645. H264Context *h = *(void **)arg;
  3646. int lf_x_start = h->mb_x;
  3647. h->mb_skip_run = -1;
  3648. av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
  3649. h->is_complex = FRAME_MBAFF || h->picture_structure != PICT_FRAME ||
  3650. avctx->codec_id != AV_CODEC_ID_H264 ||
  3651. (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
  3652. if (h->pps.cabac) {
  3653. /* realign */
  3654. align_get_bits(&h->gb);
  3655. /* init cabac */
  3656. ff_init_cabac_decoder(&h->cabac,
  3657. h->gb.buffer + get_bits_count(&h->gb) / 8,
  3658. (get_bits_left(&h->gb) + 7) / 8);
  3659. ff_h264_init_cabac_states(h);
  3660. for (;;) {
  3661. // START_TIMER
  3662. int ret = ff_h264_decode_mb_cabac(h);
  3663. int eos;
  3664. // STOP_TIMER("decode_mb_cabac")
  3665. if (ret >= 0)
  3666. ff_h264_hl_decode_mb(h);
  3667. // FIXME optimal? or let mb_decode decode 16x32 ?
  3668. if (ret >= 0 && FRAME_MBAFF) {
  3669. h->mb_y++;
  3670. ret = ff_h264_decode_mb_cabac(h);
  3671. if (ret >= 0)
  3672. ff_h264_hl_decode_mb(h);
  3673. h->mb_y--;
  3674. }
  3675. eos = get_cabac_terminate(&h->cabac);
  3676. if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
  3677. h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3678. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  3679. h->mb_y, ER_MB_END);
  3680. if (h->mb_x >= lf_x_start)
  3681. loop_filter(h, lf_x_start, h->mb_x + 1);
  3682. return 0;
  3683. }
  3684. if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
  3685. av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
  3686. if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
  3687. av_log(h->avctx, AV_LOG_ERROR,
  3688. "error while decoding MB %d %d, bytestream (%td)\n",
  3689. h->mb_x, h->mb_y,
  3690. h->cabac.bytestream_end - h->cabac.bytestream);
  3691. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3692. h->mb_y, ER_MB_ERROR);
  3693. return -1;
  3694. }
  3695. if (++h->mb_x >= h->mb_width) {
  3696. loop_filter(h, lf_x_start, h->mb_x);
  3697. h->mb_x = lf_x_start = 0;
  3698. decode_finish_row(h);
  3699. ++h->mb_y;
  3700. if (FIELD_OR_MBAFF_PICTURE) {
  3701. ++h->mb_y;
  3702. if (FRAME_MBAFF && h->mb_y < h->mb_height)
  3703. predict_field_decoding_flag(h);
  3704. }
  3705. }
  3706. if (eos || h->mb_y >= h->mb_height) {
  3707. tprintf(h->avctx, "slice end %d %d\n",
  3708. get_bits_count(&h->gb), h->gb.size_in_bits);
  3709. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  3710. h->mb_y, ER_MB_END);
  3711. if (h->mb_x > lf_x_start)
  3712. loop_filter(h, lf_x_start, h->mb_x);
  3713. return 0;
  3714. }
  3715. }
  3716. } else {
  3717. for (;;) {
  3718. int ret = ff_h264_decode_mb_cavlc(h);
  3719. if (ret >= 0)
  3720. ff_h264_hl_decode_mb(h);
  3721. // FIXME optimal? or let mb_decode decode 16x32 ?
  3722. if (ret >= 0 && FRAME_MBAFF) {
  3723. h->mb_y++;
  3724. ret = ff_h264_decode_mb_cavlc(h);
  3725. if (ret >= 0)
  3726. ff_h264_hl_decode_mb(h);
  3727. h->mb_y--;
  3728. }
  3729. if (ret < 0) {
  3730. av_log(h->avctx, AV_LOG_ERROR,
  3731. "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
  3732. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3733. h->mb_y, ER_MB_ERROR);
  3734. return -1;
  3735. }
  3736. if (++h->mb_x >= h->mb_width) {
  3737. loop_filter(h, lf_x_start, h->mb_x);
  3738. h->mb_x = lf_x_start = 0;
  3739. decode_finish_row(h);
  3740. ++h->mb_y;
  3741. if (FIELD_OR_MBAFF_PICTURE) {
  3742. ++h->mb_y;
  3743. if (FRAME_MBAFF && h->mb_y < h->mb_height)
  3744. predict_field_decoding_flag(h);
  3745. }
  3746. if (h->mb_y >= h->mb_height) {
  3747. tprintf(h->avctx, "slice end %d %d\n",
  3748. get_bits_count(&h->gb), h->gb.size_in_bits);
  3749. if ( get_bits_left(&h->gb) == 0
  3750. || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
  3751. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3752. h->mb_x - 1, h->mb_y,
  3753. ER_MB_END);
  3754. return 0;
  3755. } else {
  3756. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3757. h->mb_x, h->mb_y,
  3758. ER_MB_END);
  3759. return -1;
  3760. }
  3761. }
  3762. }
  3763. if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
  3764. tprintf(h->avctx, "slice end %d %d\n",
  3765. get_bits_count(&h->gb), h->gb.size_in_bits);
  3766. if (get_bits_left(&h->gb) == 0) {
  3767. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3768. h->mb_x - 1, h->mb_y,
  3769. ER_MB_END);
  3770. if (h->mb_x > lf_x_start)
  3771. loop_filter(h, lf_x_start, h->mb_x);
  3772. return 0;
  3773. } else {
  3774. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3775. h->mb_y, ER_MB_ERROR);
  3776. return -1;
  3777. }
  3778. }
  3779. }
  3780. }
  3781. }
  3782. /**
  3783. * Call decode_slice() for each context.
  3784. *
  3785. * @param h h264 master context
  3786. * @param context_count number of contexts to execute
  3787. */
  3788. static int execute_decode_slices(H264Context *h, int context_count)
  3789. {
  3790. AVCodecContext *const avctx = h->avctx;
  3791. H264Context *hx;
  3792. int i;
  3793. if (h->avctx->hwaccel ||
  3794. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3795. return 0;
  3796. if (context_count == 1) {
  3797. return decode_slice(avctx, &h);
  3798. } else {
  3799. av_assert0(context_count > 0);
  3800. for (i = 1; i < context_count; i++) {
  3801. hx = h->thread_context[i];
  3802. hx->er.error_count = 0;
  3803. hx->x264_build = h->x264_build;
  3804. }
  3805. avctx->execute(avctx, decode_slice, h->thread_context,
  3806. NULL, context_count, sizeof(void *));
  3807. /* pull back stuff from slices to master context */
  3808. hx = h->thread_context[context_count - 1];
  3809. h->mb_x = hx->mb_x;
  3810. h->mb_y = hx->mb_y;
  3811. h->droppable = hx->droppable;
  3812. h->picture_structure = hx->picture_structure;
  3813. for (i = 1; i < context_count; i++)
  3814. h->er.error_count += h->thread_context[i]->er.error_count;
  3815. }
  3816. return 0;
  3817. }
  3818. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  3819. int parse_extradata)
  3820. {
  3821. AVCodecContext *const avctx = h->avctx;
  3822. H264Context *hx; ///< thread context
  3823. int buf_index;
  3824. int context_count;
  3825. int next_avc;
  3826. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  3827. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  3828. int nal_index;
  3829. int idr_cleared=0;
  3830. int first_slice = 0;
  3831. h->nal_unit_type= 0;
  3832. if(!h->slice_context_count)
  3833. h->slice_context_count= 1;
  3834. h->max_contexts = h->slice_context_count;
  3835. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
  3836. h->current_slice = 0;
  3837. if (!h->first_field)
  3838. h->cur_pic_ptr = NULL;
  3839. ff_h264_reset_sei(h);
  3840. }
  3841. if (h->nal_length_size == 4) {
  3842. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  3843. h->is_avc = 0;
  3844. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  3845. h->is_avc = 1;
  3846. }
  3847. for (; pass <= 1; pass++) {
  3848. buf_index = 0;
  3849. context_count = 0;
  3850. next_avc = h->is_avc ? 0 : buf_size;
  3851. nal_index = 0;
  3852. for (;;) {
  3853. int consumed;
  3854. int dst_length;
  3855. int bit_length;
  3856. const uint8_t *ptr;
  3857. int i, nalsize = 0;
  3858. int err;
  3859. if (buf_index >= next_avc) {
  3860. if (buf_index >= buf_size - h->nal_length_size)
  3861. break;
  3862. nalsize = 0;
  3863. for (i = 0; i < h->nal_length_size; i++)
  3864. nalsize = (nalsize << 8) | buf[buf_index++];
  3865. if (nalsize <= 0 || nalsize > buf_size - buf_index) {
  3866. av_log(h->avctx, AV_LOG_ERROR,
  3867. "AVC: nal size %d\n", nalsize);
  3868. break;
  3869. }
  3870. next_avc = buf_index + nalsize;
  3871. } else {
  3872. // start code prefix search
  3873. for (; buf_index + 3 < next_avc; buf_index++)
  3874. // This should always succeed in the first iteration.
  3875. if (buf[buf_index] == 0 &&
  3876. buf[buf_index + 1] == 0 &&
  3877. buf[buf_index + 2] == 1)
  3878. break;
  3879. if (buf_index + 3 >= buf_size) {
  3880. buf_index = buf_size;
  3881. break;
  3882. }
  3883. buf_index += 3;
  3884. if (buf_index >= next_avc)
  3885. continue;
  3886. }
  3887. hx = h->thread_context[context_count];
  3888. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  3889. &consumed, next_avc - buf_index);
  3890. if (ptr == NULL || dst_length < 0) {
  3891. buf_index = -1;
  3892. goto end;
  3893. }
  3894. i = buf_index + consumed;
  3895. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  3896. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  3897. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  3898. h->workaround_bugs |= FF_BUG_TRUNCATED;
  3899. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  3900. while(dst_length > 0 && ptr[dst_length - 1] == 0)
  3901. dst_length--;
  3902. bit_length = !dst_length ? 0
  3903. : (8 * dst_length -
  3904. decode_rbsp_trailing(h, ptr + dst_length - 1));
  3905. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  3906. 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);
  3907. if (h->is_avc && (nalsize != consumed) && nalsize)
  3908. av_log(h->avctx, AV_LOG_DEBUG,
  3909. "AVC: Consumed only %d bytes instead of %d\n",
  3910. consumed, nalsize);
  3911. buf_index += consumed;
  3912. nal_index++;
  3913. if (pass == 0) {
  3914. /* packets can sometimes contain multiple PPS/SPS,
  3915. * e.g. two PAFF field pictures in one packet, or a demuxer
  3916. * which splits NALs strangely if so, when frame threading we
  3917. * can't start the next thread until we've read all of them */
  3918. switch (hx->nal_unit_type) {
  3919. case NAL_SPS:
  3920. case NAL_PPS:
  3921. nals_needed = nal_index;
  3922. break;
  3923. case NAL_DPA:
  3924. case NAL_IDR_SLICE:
  3925. case NAL_SLICE:
  3926. init_get_bits(&hx->gb, ptr, bit_length);
  3927. if (!get_ue_golomb(&hx->gb) || !first_slice)
  3928. nals_needed = nal_index;
  3929. if (!first_slice)
  3930. first_slice = hx->nal_unit_type;
  3931. }
  3932. continue;
  3933. }
  3934. if (!first_slice)
  3935. switch (hx->nal_unit_type) {
  3936. case NAL_DPA:
  3937. case NAL_IDR_SLICE:
  3938. case NAL_SLICE:
  3939. first_slice = hx->nal_unit_type;
  3940. }
  3941. // FIXME do not discard SEI id
  3942. if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
  3943. continue;
  3944. again:
  3945. /* Ignore per frame NAL unit type during extradata
  3946. * parsing. Decoding slices is not possible in codec init
  3947. * with frame-mt */
  3948. if (parse_extradata) {
  3949. switch (hx->nal_unit_type) {
  3950. case NAL_IDR_SLICE:
  3951. case NAL_SLICE:
  3952. case NAL_DPA:
  3953. case NAL_DPB:
  3954. case NAL_DPC:
  3955. case NAL_AUXILIARY_SLICE:
  3956. av_log(h->avctx, AV_LOG_WARNING, "Ignoring NAL %d in global header/extradata\n", hx->nal_unit_type);
  3957. hx->nal_unit_type = NAL_FF_IGNORE;
  3958. }
  3959. }
  3960. err = 0;
  3961. switch (hx->nal_unit_type) {
  3962. case NAL_IDR_SLICE:
  3963. if (first_slice != NAL_IDR_SLICE) {
  3964. av_log(h->avctx, AV_LOG_ERROR,
  3965. "Invalid mix of idr and non-idr slices\n");
  3966. buf_index = -1;
  3967. goto end;
  3968. }
  3969. if(!idr_cleared)
  3970. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  3971. idr_cleared = 1;
  3972. case NAL_SLICE:
  3973. init_get_bits(&hx->gb, ptr, bit_length);
  3974. hx->intra_gb_ptr =
  3975. hx->inter_gb_ptr = &hx->gb;
  3976. hx->data_partitioning = 0;
  3977. if ((err = decode_slice_header(hx, h)))
  3978. break;
  3979. if (h->sei_recovery_frame_cnt >= 0 && (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I))
  3980. h->valid_recovery_point = 1;
  3981. if ( h->sei_recovery_frame_cnt >= 0
  3982. && ( h->recovery_frame<0
  3983. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
  3984. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
  3985. (1 << h->sps.log2_max_frame_num);
  3986. if (!h->valid_recovery_point)
  3987. h->recovery_frame = h->frame_num;
  3988. }
  3989. h->cur_pic_ptr->f.key_frame |=
  3990. (hx->nal_unit_type == NAL_IDR_SLICE);
  3991. if (h->recovery_frame == h->frame_num) {
  3992. h->cur_pic_ptr->sync |= 1;
  3993. h->recovery_frame = -1;
  3994. }
  3995. h->sync |= !!h->cur_pic_ptr->f.key_frame;
  3996. h->sync |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
  3997. h->cur_pic_ptr->sync |= h->sync;
  3998. if (h->current_slice == 1) {
  3999. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
  4000. decode_postinit(h, nal_index >= nals_needed);
  4001. if (h->avctx->hwaccel &&
  4002. h->avctx->hwaccel->start_frame(h->avctx, NULL, 0) < 0)
  4003. return -1;
  4004. if (CONFIG_H264_VDPAU_DECODER &&
  4005. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  4006. ff_vdpau_h264_picture_start(h);
  4007. }
  4008. if (hx->redundant_pic_count == 0 &&
  4009. (avctx->skip_frame < AVDISCARD_NONREF ||
  4010. hx->nal_ref_idc) &&
  4011. (avctx->skip_frame < AVDISCARD_BIDIR ||
  4012. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  4013. (avctx->skip_frame < AVDISCARD_NONKEY ||
  4014. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  4015. avctx->skip_frame < AVDISCARD_ALL) {
  4016. if (avctx->hwaccel) {
  4017. if (avctx->hwaccel->decode_slice(avctx,
  4018. &buf[buf_index - consumed],
  4019. consumed) < 0)
  4020. return -1;
  4021. } else if (CONFIG_H264_VDPAU_DECODER &&
  4022. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  4023. static const uint8_t start_code[] = {
  4024. 0x00, 0x00, 0x01 };
  4025. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], start_code,
  4026. sizeof(start_code));
  4027. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], &buf[buf_index - consumed],
  4028. consumed);
  4029. } else
  4030. context_count++;
  4031. }
  4032. break;
  4033. case NAL_DPA:
  4034. init_get_bits(&hx->gb, ptr, bit_length);
  4035. hx->intra_gb_ptr =
  4036. hx->inter_gb_ptr = NULL;
  4037. if ((err = decode_slice_header(hx, h)) < 0)
  4038. break;
  4039. hx->data_partitioning = 1;
  4040. break;
  4041. case NAL_DPB:
  4042. init_get_bits(&hx->intra_gb, ptr, bit_length);
  4043. hx->intra_gb_ptr = &hx->intra_gb;
  4044. break;
  4045. case NAL_DPC:
  4046. init_get_bits(&hx->inter_gb, ptr, bit_length);
  4047. hx->inter_gb_ptr = &hx->inter_gb;
  4048. av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
  4049. break;
  4050. if (hx->redundant_pic_count == 0 &&
  4051. hx->intra_gb_ptr &&
  4052. hx->data_partitioning &&
  4053. h->cur_pic_ptr && h->context_initialized &&
  4054. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  4055. (avctx->skip_frame < AVDISCARD_BIDIR ||
  4056. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  4057. (avctx->skip_frame < AVDISCARD_NONKEY ||
  4058. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  4059. avctx->skip_frame < AVDISCARD_ALL)
  4060. context_count++;
  4061. break;
  4062. case NAL_SEI:
  4063. init_get_bits(&h->gb, ptr, bit_length);
  4064. ff_h264_decode_sei(h);
  4065. break;
  4066. case NAL_SPS:
  4067. init_get_bits(&h->gb, ptr, bit_length);
  4068. if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)) {
  4069. av_log(h->avctx, AV_LOG_DEBUG,
  4070. "SPS decoding failure, trying again with the complete NAL\n");
  4071. if (h->is_avc)
  4072. av_assert0(next_avc - buf_index + consumed == nalsize);
  4073. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  4074. break;
  4075. init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
  4076. 8*(next_avc - buf_index + consumed - 1));
  4077. ff_h264_decode_seq_parameter_set(h);
  4078. }
  4079. break;
  4080. case NAL_PPS:
  4081. init_get_bits(&h->gb, ptr, bit_length);
  4082. ff_h264_decode_picture_parameter_set(h, bit_length);
  4083. break;
  4084. case NAL_AUD:
  4085. case NAL_END_SEQUENCE:
  4086. case NAL_END_STREAM:
  4087. case NAL_FILLER_DATA:
  4088. case NAL_SPS_EXT:
  4089. case NAL_AUXILIARY_SLICE:
  4090. break;
  4091. case NAL_FF_IGNORE:
  4092. break;
  4093. default:
  4094. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  4095. hx->nal_unit_type, bit_length);
  4096. }
  4097. if (context_count == h->max_contexts) {
  4098. execute_decode_slices(h, context_count);
  4099. context_count = 0;
  4100. }
  4101. if (err < 0)
  4102. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  4103. else if (err == 1) {
  4104. /* Slice could not be decoded in parallel mode, copy down
  4105. * NAL unit stuff to context 0 and restart. Note that
  4106. * rbsp_buffer is not transferred, but since we no longer
  4107. * run in parallel mode this should not be an issue. */
  4108. h->nal_unit_type = hx->nal_unit_type;
  4109. h->nal_ref_idc = hx->nal_ref_idc;
  4110. hx = h;
  4111. goto again;
  4112. }
  4113. }
  4114. }
  4115. if (context_count)
  4116. execute_decode_slices(h, context_count);
  4117. end:
  4118. /* clean up */
  4119. if (h->cur_pic_ptr && h->cur_pic_ptr->owner2 == h &&
  4120. !h->droppable) {
  4121. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  4122. h->picture_structure == PICT_BOTTOM_FIELD);
  4123. }
  4124. return buf_index;
  4125. }
  4126. /**
  4127. * Return the number of bytes consumed for building the current frame.
  4128. */
  4129. static int get_consumed_bytes(int pos, int buf_size)
  4130. {
  4131. if (pos == 0)
  4132. pos = 1; // avoid infinite loops (i doubt that is needed but ...)
  4133. if (pos + 10 > buf_size)
  4134. pos = buf_size; // oops ;)
  4135. return pos;
  4136. }
  4137. static int decode_frame(AVCodecContext *avctx, void *data,
  4138. int *got_frame, AVPacket *avpkt)
  4139. {
  4140. const uint8_t *buf = avpkt->data;
  4141. int buf_size = avpkt->size;
  4142. H264Context *h = avctx->priv_data;
  4143. AVFrame *pict = data;
  4144. int buf_index = 0;
  4145. Picture *out;
  4146. int i, out_idx;
  4147. h->flags = avctx->flags;
  4148. /* end of stream, output what is still in the buffers */
  4149. if (buf_size == 0) {
  4150. out:
  4151. h->cur_pic_ptr = NULL;
  4152. h->first_field = 0;
  4153. // FIXME factorize this with the output code below
  4154. out = h->delayed_pic[0];
  4155. out_idx = 0;
  4156. for (i = 1;
  4157. h->delayed_pic[i] &&
  4158. !h->delayed_pic[i]->f.key_frame &&
  4159. !h->delayed_pic[i]->mmco_reset;
  4160. i++)
  4161. if (h->delayed_pic[i]->poc < out->poc) {
  4162. out = h->delayed_pic[i];
  4163. out_idx = i;
  4164. }
  4165. for (i = out_idx; h->delayed_pic[i]; i++)
  4166. h->delayed_pic[i] = h->delayed_pic[i + 1];
  4167. if (out) {
  4168. out->f.reference &= ~DELAYED_PIC_REF;
  4169. *got_frame = 1;
  4170. *pict = out->f;
  4171. }
  4172. return buf_index;
  4173. }
  4174. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  4175. int cnt= buf[5]&0x1f;
  4176. const uint8_t *p= buf+6;
  4177. while(cnt--){
  4178. int nalsize= AV_RB16(p) + 2;
  4179. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  4180. goto not_extra;
  4181. p += nalsize;
  4182. }
  4183. cnt = *(p++);
  4184. if(!cnt)
  4185. goto not_extra;
  4186. while(cnt--){
  4187. int nalsize= AV_RB16(p) + 2;
  4188. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  4189. goto not_extra;
  4190. p += nalsize;
  4191. }
  4192. return ff_h264_decode_extradata(h, buf, buf_size);
  4193. }
  4194. not_extra:
  4195. buf_index = decode_nal_units(h, buf, buf_size, 0);
  4196. if (buf_index < 0)
  4197. return -1;
  4198. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  4199. av_assert0(buf_index <= buf_size);
  4200. goto out;
  4201. }
  4202. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  4203. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  4204. buf_size >= 4 && !memcmp("Q264", buf, 4))
  4205. return buf_size;
  4206. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  4207. return -1;
  4208. }
  4209. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
  4210. (h->mb_y >= h->mb_height && h->mb_height)) {
  4211. if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
  4212. decode_postinit(h, 1);
  4213. field_end(h, 0);
  4214. /* Wait for second field. */
  4215. *got_frame = 0;
  4216. if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
  4217. *got_frame = 1;
  4218. *pict = h->next_output_pic->f;
  4219. }
  4220. }
  4221. assert(pict->data[0] || !*got_frame);
  4222. ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table, h->visualization_buffer, &h->low_delay,
  4223. h->mb_width, h->mb_height, h->mb_stride, 1);
  4224. return get_consumed_bytes(buf_index, buf_size);
  4225. }
  4226. av_cold void ff_h264_free_context(H264Context *h)
  4227. {
  4228. int i;
  4229. free_tables(h, 1); // FIXME cleanup init stuff perhaps
  4230. for (i = 0; i < MAX_SPS_COUNT; i++)
  4231. av_freep(h->sps_buffers + i);
  4232. for (i = 0; i < MAX_PPS_COUNT; i++)
  4233. av_freep(h->pps_buffers + i);
  4234. }
  4235. static av_cold int h264_decode_end(AVCodecContext *avctx)
  4236. {
  4237. H264Context *h = avctx->priv_data;
  4238. int i;
  4239. ff_h264_remove_all_refs(h);
  4240. ff_h264_free_context(h);
  4241. if (h->DPB && !h->avctx->internal->is_copy) {
  4242. for (i = 0; i < h->picture_count; i++) {
  4243. free_picture(h, &h->DPB[i]);
  4244. }
  4245. }
  4246. av_freep(&h->DPB);
  4247. return 0;
  4248. }
  4249. static const AVProfile profiles[] = {
  4250. { FF_PROFILE_H264_BASELINE, "Baseline" },
  4251. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  4252. { FF_PROFILE_H264_MAIN, "Main" },
  4253. { FF_PROFILE_H264_EXTENDED, "Extended" },
  4254. { FF_PROFILE_H264_HIGH, "High" },
  4255. { FF_PROFILE_H264_HIGH_10, "High 10" },
  4256. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  4257. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  4258. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  4259. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  4260. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  4261. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  4262. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  4263. { FF_PROFILE_UNKNOWN },
  4264. };
  4265. static const AVOption h264_options[] = {
  4266. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  4267. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  4268. {NULL}
  4269. };
  4270. static const AVClass h264_class = {
  4271. .class_name = "H264 Decoder",
  4272. .item_name = av_default_item_name,
  4273. .option = h264_options,
  4274. .version = LIBAVUTIL_VERSION_INT,
  4275. };
  4276. static const AVClass h264_vdpau_class = {
  4277. .class_name = "H264 VDPAU Decoder",
  4278. .item_name = av_default_item_name,
  4279. .option = h264_options,
  4280. .version = LIBAVUTIL_VERSION_INT,
  4281. };
  4282. AVCodec ff_h264_decoder = {
  4283. .name = "h264",
  4284. .type = AVMEDIA_TYPE_VIDEO,
  4285. .id = AV_CODEC_ID_H264,
  4286. .priv_data_size = sizeof(H264Context),
  4287. .init = ff_h264_decode_init,
  4288. .close = h264_decode_end,
  4289. .decode = decode_frame,
  4290. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  4291. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  4292. CODEC_CAP_FRAME_THREADS,
  4293. .flush = flush_dpb,
  4294. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  4295. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  4296. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  4297. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4298. .priv_class = &h264_class,
  4299. };
  4300. #if CONFIG_H264_VDPAU_DECODER
  4301. AVCodec ff_h264_vdpau_decoder = {
  4302. .name = "h264_vdpau",
  4303. .type = AVMEDIA_TYPE_VIDEO,
  4304. .id = AV_CODEC_ID_H264,
  4305. .priv_data_size = sizeof(H264Context),
  4306. .init = ff_h264_decode_init,
  4307. .close = h264_decode_end,
  4308. .decode = decode_frame,
  4309. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  4310. .flush = flush_dpb,
  4311. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  4312. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  4313. AV_PIX_FMT_NONE},
  4314. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4315. .priv_class = &h264_vdpau_class,
  4316. };
  4317. #endif