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.

4897 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((void*)&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. h->er.last_pic =
  1502. h->er.next_pic = NULL;
  1503. assert(h->linesize && h->uvlinesize);
  1504. for (i = 0; i < 16; i++) {
  1505. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1506. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1507. }
  1508. for (i = 0; i < 16; i++) {
  1509. h->block_offset[16 + i] =
  1510. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1511. h->block_offset[48 + 16 + i] =
  1512. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1513. }
  1514. /* Some macroblocks can be accessed before they're available in case
  1515. * of lost slices, MBAFF or threading. */
  1516. memset(h->slice_table, -1,
  1517. (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
  1518. // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
  1519. // h->cur_pic.f.reference /* || h->contains_intra */ || 1;
  1520. /* We mark the current picture as non-reference after allocating it, so
  1521. * that if we break out due to an error it can be released automatically
  1522. * in the next ff_MPV_frame_start().
  1523. * SVQ3 as well as most other codecs have only last/next/current and thus
  1524. * get released even with set reference, besides SVQ3 and others do not
  1525. * mark frames as reference later "naturally". */
  1526. if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)
  1527. h->cur_pic_ptr->f.reference = 0;
  1528. h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
  1529. h->next_output_pic = NULL;
  1530. assert(h->cur_pic_ptr->long_ref == 0);
  1531. return 0;
  1532. }
  1533. /**
  1534. * Run setup operations that must be run after slice header decoding.
  1535. * This includes finding the next displayed frame.
  1536. *
  1537. * @param h h264 master context
  1538. * @param setup_finished enough NALs have been read that we can call
  1539. * ff_thread_finish_setup()
  1540. */
  1541. static void decode_postinit(H264Context *h, int setup_finished)
  1542. {
  1543. Picture *out = h->cur_pic_ptr;
  1544. Picture *cur = h->cur_pic_ptr;
  1545. int i, pics, out_of_order, out_idx;
  1546. h->cur_pic_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
  1547. h->cur_pic_ptr->f.pict_type = h->pict_type;
  1548. if (h->next_output_pic)
  1549. return;
  1550. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  1551. /* FIXME: if we have two PAFF fields in one packet, we can't start
  1552. * the next thread here. If we have one field per packet, we can.
  1553. * The check in decode_nal_units() is not good enough to find this
  1554. * yet, so we assume the worst for now. */
  1555. // if (setup_finished)
  1556. // ff_thread_finish_setup(h->avctx);
  1557. return;
  1558. }
  1559. cur->f.interlaced_frame = 0;
  1560. cur->f.repeat_pict = 0;
  1561. /* Signal interlacing information externally. */
  1562. /* Prioritize picture timing SEI information over used
  1563. * decoding process if it exists. */
  1564. if (h->sps.pic_struct_present_flag) {
  1565. switch (h->sei_pic_struct) {
  1566. case SEI_PIC_STRUCT_FRAME:
  1567. break;
  1568. case SEI_PIC_STRUCT_TOP_FIELD:
  1569. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1570. cur->f.interlaced_frame = 1;
  1571. break;
  1572. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1573. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1574. if (FIELD_OR_MBAFF_PICTURE)
  1575. cur->f.interlaced_frame = 1;
  1576. else
  1577. // try to flag soft telecine progressive
  1578. cur->f.interlaced_frame = h->prev_interlaced_frame;
  1579. break;
  1580. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1581. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1582. /* Signal the possibility of telecined film externally
  1583. * (pic_struct 5,6). From these hints, let the applications
  1584. * decide if they apply deinterlacing. */
  1585. cur->f.repeat_pict = 1;
  1586. break;
  1587. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1588. cur->f.repeat_pict = 2;
  1589. break;
  1590. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1591. cur->f.repeat_pict = 4;
  1592. break;
  1593. }
  1594. if ((h->sei_ct_type & 3) &&
  1595. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1596. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  1597. } else {
  1598. /* Derive interlacing flag from used decoding process. */
  1599. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  1600. }
  1601. h->prev_interlaced_frame = cur->f.interlaced_frame;
  1602. if (cur->field_poc[0] != cur->field_poc[1]) {
  1603. /* Derive top_field_first from field pocs. */
  1604. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1605. } else {
  1606. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  1607. /* Use picture timing SEI information. Even if it is a
  1608. * information of a past frame, better than nothing. */
  1609. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  1610. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1611. cur->f.top_field_first = 1;
  1612. else
  1613. cur->f.top_field_first = 0;
  1614. } else {
  1615. /* Most likely progressive */
  1616. cur->f.top_field_first = 0;
  1617. }
  1618. }
  1619. cur->mmco_reset = h->mmco_reset;
  1620. h->mmco_reset = 0;
  1621. // FIXME do something with unavailable reference frames
  1622. /* Sort B-frames into display order */
  1623. if (h->sps.bitstream_restriction_flag &&
  1624. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1625. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  1626. h->low_delay = 0;
  1627. }
  1628. if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  1629. !h->sps.bitstream_restriction_flag) {
  1630. h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  1631. h->low_delay = 0;
  1632. }
  1633. for (i = 0; 1; i++) {
  1634. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1635. if(i)
  1636. h->last_pocs[i-1] = cur->poc;
  1637. break;
  1638. } else if(i) {
  1639. h->last_pocs[i-1]= h->last_pocs[i];
  1640. }
  1641. }
  1642. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1643. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  1644. || (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))
  1645. out_of_order = FFMAX(out_of_order, 1);
  1646. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  1647. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  1648. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  1649. h->last_pocs[i] = INT_MIN;
  1650. h->last_pocs[0] = cur->poc;
  1651. cur->mmco_reset = 1;
  1652. } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  1653. av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
  1654. h->avctx->has_b_frames = out_of_order;
  1655. h->low_delay = 0;
  1656. }
  1657. pics = 0;
  1658. while (h->delayed_pic[pics])
  1659. pics++;
  1660. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1661. h->delayed_pic[pics++] = cur;
  1662. if (cur->f.reference == 0)
  1663. cur->f.reference = DELAYED_PIC_REF;
  1664. out = h->delayed_pic[0];
  1665. out_idx = 0;
  1666. for (i = 1; h->delayed_pic[i] &&
  1667. !h->delayed_pic[i]->f.key_frame &&
  1668. !h->delayed_pic[i]->mmco_reset;
  1669. i++)
  1670. if (h->delayed_pic[i]->poc < out->poc) {
  1671. out = h->delayed_pic[i];
  1672. out_idx = i;
  1673. }
  1674. if (h->avctx->has_b_frames == 0 &&
  1675. (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  1676. h->next_outputed_poc = INT_MIN;
  1677. out_of_order = out->poc < h->next_outputed_poc;
  1678. if (out_of_order || pics > h->avctx->has_b_frames) {
  1679. out->f.reference &= ~DELAYED_PIC_REF;
  1680. // for frame threading, the owner must be the second field's thread or
  1681. // else the first thread can release the picture and reuse it unsafely
  1682. out->owner2 = h;
  1683. for (i = out_idx; h->delayed_pic[i]; i++)
  1684. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1685. }
  1686. if (!out_of_order && pics > h->avctx->has_b_frames) {
  1687. h->next_output_pic = out;
  1688. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  1689. h->next_outputed_poc = INT_MIN;
  1690. } else
  1691. h->next_outputed_poc = out->poc;
  1692. } else {
  1693. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1694. }
  1695. if (h->next_output_pic && h->next_output_pic->sync) {
  1696. h->sync |= 2;
  1697. }
  1698. if (setup_finished)
  1699. ff_thread_finish_setup(h->avctx);
  1700. }
  1701. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  1702. uint8_t *src_cb, uint8_t *src_cr,
  1703. int linesize, int uvlinesize,
  1704. int simple)
  1705. {
  1706. uint8_t *top_border;
  1707. int top_idx = 1;
  1708. const int pixel_shift = h->pixel_shift;
  1709. int chroma444 = CHROMA444;
  1710. int chroma422 = CHROMA422;
  1711. src_y -= linesize;
  1712. src_cb -= uvlinesize;
  1713. src_cr -= uvlinesize;
  1714. if (!simple && FRAME_MBAFF) {
  1715. if (h->mb_y & 1) {
  1716. if (!MB_MBAFF) {
  1717. top_border = h->top_borders[0][h->mb_x];
  1718. AV_COPY128(top_border, src_y + 15 * linesize);
  1719. if (pixel_shift)
  1720. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  1721. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1722. if (chroma444) {
  1723. if (pixel_shift) {
  1724. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1725. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  1726. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  1727. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  1728. } else {
  1729. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  1730. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  1731. }
  1732. } else if (chroma422) {
  1733. if (pixel_shift) {
  1734. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1735. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  1736. } else {
  1737. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  1738. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  1739. }
  1740. } else {
  1741. if (pixel_shift) {
  1742. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  1743. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  1744. } else {
  1745. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  1746. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  1747. }
  1748. }
  1749. }
  1750. }
  1751. } else if (MB_MBAFF) {
  1752. top_idx = 0;
  1753. } else
  1754. return;
  1755. }
  1756. top_border = h->top_borders[top_idx][h->mb_x];
  1757. /* There are two lines saved, the line above the top macroblock
  1758. * of a pair, and the line above the bottom macroblock. */
  1759. AV_COPY128(top_border, src_y + 16 * linesize);
  1760. if (pixel_shift)
  1761. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  1762. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1763. if (chroma444) {
  1764. if (pixel_shift) {
  1765. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  1766. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  1767. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  1768. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  1769. } else {
  1770. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  1771. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  1772. }
  1773. } else if (chroma422) {
  1774. if (pixel_shift) {
  1775. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  1776. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  1777. } else {
  1778. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  1779. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  1780. }
  1781. } else {
  1782. if (pixel_shift) {
  1783. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  1784. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  1785. } else {
  1786. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  1787. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  1788. }
  1789. }
  1790. }
  1791. }
  1792. static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
  1793. uint8_t *src_cb, uint8_t *src_cr,
  1794. int linesize, int uvlinesize,
  1795. int xchg, int chroma444,
  1796. int simple, int pixel_shift)
  1797. {
  1798. int deblock_topleft;
  1799. int deblock_top;
  1800. int top_idx = 1;
  1801. uint8_t *top_border_m1;
  1802. uint8_t *top_border;
  1803. if (!simple && FRAME_MBAFF) {
  1804. if (h->mb_y & 1) {
  1805. if (!MB_MBAFF)
  1806. return;
  1807. } else {
  1808. top_idx = MB_MBAFF ? 0 : 1;
  1809. }
  1810. }
  1811. if (h->deblocking_filter == 2) {
  1812. deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
  1813. deblock_top = h->top_type;
  1814. } else {
  1815. deblock_topleft = (h->mb_x > 0);
  1816. deblock_top = (h->mb_y > !!MB_FIELD);
  1817. }
  1818. src_y -= linesize + 1 + pixel_shift;
  1819. src_cb -= uvlinesize + 1 + pixel_shift;
  1820. src_cr -= uvlinesize + 1 + pixel_shift;
  1821. top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
  1822. top_border = h->top_borders[top_idx][h->mb_x];
  1823. #define XCHG(a, b, xchg) \
  1824. if (pixel_shift) { \
  1825. if (xchg) { \
  1826. AV_SWAP64(b + 0, a + 0); \
  1827. AV_SWAP64(b + 8, a + 8); \
  1828. } else { \
  1829. AV_COPY128(b, a); \
  1830. } \
  1831. } else if (xchg) \
  1832. AV_SWAP64(b, a); \
  1833. else \
  1834. AV_COPY64(b, a);
  1835. if (deblock_top) {
  1836. if (deblock_topleft) {
  1837. XCHG(top_border_m1 + (8 << pixel_shift),
  1838. src_y - (7 << pixel_shift), 1);
  1839. }
  1840. XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
  1841. XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
  1842. if (h->mb_x + 1 < h->mb_width) {
  1843. XCHG(h->top_borders[top_idx][h->mb_x + 1],
  1844. src_y + (17 << pixel_shift), 1);
  1845. }
  1846. }
  1847. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1848. if (chroma444) {
  1849. if (deblock_topleft) {
  1850. XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1851. XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1852. }
  1853. XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
  1854. XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
  1855. XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
  1856. XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
  1857. if (h->mb_x + 1 < h->mb_width) {
  1858. XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
  1859. XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
  1860. }
  1861. } else {
  1862. if (deblock_top) {
  1863. if (deblock_topleft) {
  1864. XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1865. XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1866. }
  1867. XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
  1868. XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
  1869. }
  1870. }
  1871. }
  1872. }
  1873. static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
  1874. int index)
  1875. {
  1876. if (high_bit_depth) {
  1877. return AV_RN32A(((int32_t *)mb) + index);
  1878. } else
  1879. return AV_RN16A(mb + index);
  1880. }
  1881. static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
  1882. int index, int value)
  1883. {
  1884. if (high_bit_depth) {
  1885. AV_WN32A(((int32_t *)mb) + index, value);
  1886. } else
  1887. AV_WN16A(mb + index, value);
  1888. }
  1889. static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
  1890. int mb_type, int is_h264,
  1891. int simple,
  1892. int transform_bypass,
  1893. int pixel_shift,
  1894. int *block_offset,
  1895. int linesize,
  1896. uint8_t *dest_y, int p)
  1897. {
  1898. void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
  1899. void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
  1900. int i;
  1901. int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
  1902. block_offset += 16 * p;
  1903. if (IS_INTRA4x4(mb_type)) {
  1904. if (IS_8x8DCT(mb_type)) {
  1905. if (transform_bypass) {
  1906. idct_dc_add =
  1907. idct_add = h->h264dsp.h264_add_pixels8_clear;
  1908. } else {
  1909. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  1910. idct_add = h->h264dsp.h264_idct8_add;
  1911. }
  1912. for (i = 0; i < 16; i += 4) {
  1913. uint8_t *const ptr = dest_y + block_offset[i];
  1914. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1915. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1916. h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1917. } else {
  1918. const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1919. h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
  1920. (h->topright_samples_available << i) & 0x4000, linesize);
  1921. if (nnz) {
  1922. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1923. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1924. else
  1925. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1926. }
  1927. }
  1928. }
  1929. } else {
  1930. if (transform_bypass) {
  1931. idct_dc_add =
  1932. idct_add = h->h264dsp.h264_add_pixels4_clear;
  1933. } else {
  1934. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  1935. idct_add = h->h264dsp.h264_idct_add;
  1936. }
  1937. for (i = 0; i < 16; i++) {
  1938. uint8_t *const ptr = dest_y + block_offset[i];
  1939. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1940. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1941. h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1942. } else {
  1943. uint8_t *topright;
  1944. int nnz, tr;
  1945. uint64_t tr_high;
  1946. if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
  1947. const int topright_avail = (h->topright_samples_available << i) & 0x8000;
  1948. av_assert2(h->mb_y || linesize <= block_offset[i]);
  1949. if (!topright_avail) {
  1950. if (pixel_shift) {
  1951. tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
  1952. topright = (uint8_t *)&tr_high;
  1953. } else {
  1954. tr = ptr[3 - linesize] * 0x01010101u;
  1955. topright = (uint8_t *)&tr;
  1956. }
  1957. } else
  1958. topright = ptr + (4 << pixel_shift) - linesize;
  1959. } else
  1960. topright = NULL;
  1961. h->hpc.pred4x4[dir](ptr, topright, linesize);
  1962. nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1963. if (nnz) {
  1964. if (is_h264) {
  1965. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1966. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1967. else
  1968. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1969. } else if (CONFIG_SVQ3_DECODER)
  1970. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
  1971. }
  1972. }
  1973. }
  1974. }
  1975. } else {
  1976. h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
  1977. if (is_h264) {
  1978. if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
  1979. if (!transform_bypass)
  1980. h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
  1981. h->mb_luma_dc[p],
  1982. h->dequant4_coeff[p][qscale][0]);
  1983. else {
  1984. static const uint8_t dc_mapping[16] = {
  1985. 0 * 16, 1 * 16, 4 * 16, 5 * 16,
  1986. 2 * 16, 3 * 16, 6 * 16, 7 * 16,
  1987. 8 * 16, 9 * 16, 12 * 16, 13 * 16,
  1988. 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
  1989. for (i = 0; i < 16; i++)
  1990. dctcoef_set(h->mb + (p * 256 << pixel_shift),
  1991. pixel_shift, dc_mapping[i],
  1992. dctcoef_get(h->mb_luma_dc[p],
  1993. pixel_shift, i));
  1994. }
  1995. }
  1996. } else if (CONFIG_SVQ3_DECODER)
  1997. ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
  1998. h->mb_luma_dc[p], qscale);
  1999. }
  2000. }
  2001. static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
  2002. int is_h264, int simple,
  2003. int transform_bypass,
  2004. int pixel_shift,
  2005. int *block_offset,
  2006. int linesize,
  2007. uint8_t *dest_y, int p)
  2008. {
  2009. void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
  2010. int i;
  2011. block_offset += 16 * p;
  2012. if (!IS_INTRA4x4(mb_type)) {
  2013. if (is_h264) {
  2014. if (IS_INTRA16x16(mb_type)) {
  2015. if (transform_bypass) {
  2016. if (h->sps.profile_idc == 244 &&
  2017. (h->intra16x16_pred_mode == VERT_PRED8x8 ||
  2018. h->intra16x16_pred_mode == HOR_PRED8x8)) {
  2019. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
  2020. h->mb + (p * 256 << pixel_shift),
  2021. linesize);
  2022. } else {
  2023. for (i = 0; i < 16; i++)
  2024. if (h->non_zero_count_cache[scan8[i + p * 16]] ||
  2025. dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  2026. h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
  2027. h->mb + (i * 16 + p * 256 << pixel_shift),
  2028. linesize);
  2029. }
  2030. } else {
  2031. h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
  2032. h->mb + (p * 256 << pixel_shift),
  2033. linesize,
  2034. h->non_zero_count_cache + p * 5 * 8);
  2035. }
  2036. } else if (h->cbp & 15) {
  2037. if (transform_bypass) {
  2038. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  2039. idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
  2040. : h->h264dsp.h264_add_pixels4_clear;
  2041. for (i = 0; i < 16; i += di)
  2042. if (h->non_zero_count_cache[scan8[i + p * 16]])
  2043. idct_add(dest_y + block_offset[i],
  2044. h->mb + (i * 16 + p * 256 << pixel_shift),
  2045. linesize);
  2046. } else {
  2047. if (IS_8x8DCT(mb_type))
  2048. h->h264dsp.h264_idct8_add4(dest_y, block_offset,
  2049. h->mb + (p * 256 << pixel_shift),
  2050. linesize,
  2051. h->non_zero_count_cache + p * 5 * 8);
  2052. else
  2053. h->h264dsp.h264_idct_add16(dest_y, block_offset,
  2054. h->mb + (p * 256 << pixel_shift),
  2055. linesize,
  2056. h->non_zero_count_cache + p * 5 * 8);
  2057. }
  2058. }
  2059. } else if (CONFIG_SVQ3_DECODER) {
  2060. for (i = 0; i < 16; i++)
  2061. if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
  2062. // FIXME benchmark weird rule, & below
  2063. uint8_t *const ptr = dest_y + block_offset[i];
  2064. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
  2065. h->qscale, IS_INTRA(mb_type) ? 1 : 0);
  2066. }
  2067. }
  2068. }
  2069. }
  2070. #define BITS 8
  2071. #define SIMPLE 1
  2072. #include "h264_mb_template.c"
  2073. #undef BITS
  2074. #define BITS 16
  2075. #include "h264_mb_template.c"
  2076. #undef SIMPLE
  2077. #define SIMPLE 0
  2078. #include "h264_mb_template.c"
  2079. void ff_h264_hl_decode_mb(H264Context *h)
  2080. {
  2081. const int mb_xy = h->mb_xy;
  2082. const int mb_type = h->cur_pic.f.mb_type[mb_xy];
  2083. int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || h->qscale == 0;
  2084. if (CHROMA444) {
  2085. if (is_complex || h->pixel_shift)
  2086. hl_decode_mb_444_complex(h);
  2087. else
  2088. hl_decode_mb_444_simple_8(h);
  2089. } else if (is_complex) {
  2090. hl_decode_mb_complex(h);
  2091. } else if (h->pixel_shift) {
  2092. hl_decode_mb_simple_16(h);
  2093. } else
  2094. hl_decode_mb_simple_8(h);
  2095. }
  2096. static int pred_weight_table(H264Context *h)
  2097. {
  2098. int list, i;
  2099. int luma_def, chroma_def;
  2100. h->use_weight = 0;
  2101. h->use_weight_chroma = 0;
  2102. h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
  2103. if (h->sps.chroma_format_idc)
  2104. h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
  2105. luma_def = 1 << h->luma_log2_weight_denom;
  2106. chroma_def = 1 << h->chroma_log2_weight_denom;
  2107. for (list = 0; list < 2; list++) {
  2108. h->luma_weight_flag[list] = 0;
  2109. h->chroma_weight_flag[list] = 0;
  2110. for (i = 0; i < h->ref_count[list]; i++) {
  2111. int luma_weight_flag, chroma_weight_flag;
  2112. luma_weight_flag = get_bits1(&h->gb);
  2113. if (luma_weight_flag) {
  2114. h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
  2115. h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
  2116. if (h->luma_weight[i][list][0] != luma_def ||
  2117. h->luma_weight[i][list][1] != 0) {
  2118. h->use_weight = 1;
  2119. h->luma_weight_flag[list] = 1;
  2120. }
  2121. } else {
  2122. h->luma_weight[i][list][0] = luma_def;
  2123. h->luma_weight[i][list][1] = 0;
  2124. }
  2125. if (h->sps.chroma_format_idc) {
  2126. chroma_weight_flag = get_bits1(&h->gb);
  2127. if (chroma_weight_flag) {
  2128. int j;
  2129. for (j = 0; j < 2; j++) {
  2130. h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
  2131. h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
  2132. if (h->chroma_weight[i][list][j][0] != chroma_def ||
  2133. h->chroma_weight[i][list][j][1] != 0) {
  2134. h->use_weight_chroma = 1;
  2135. h->chroma_weight_flag[list] = 1;
  2136. }
  2137. }
  2138. } else {
  2139. int j;
  2140. for (j = 0; j < 2; j++) {
  2141. h->chroma_weight[i][list][j][0] = chroma_def;
  2142. h->chroma_weight[i][list][j][1] = 0;
  2143. }
  2144. }
  2145. }
  2146. }
  2147. if (h->slice_type_nos != AV_PICTURE_TYPE_B)
  2148. break;
  2149. }
  2150. h->use_weight = h->use_weight || h->use_weight_chroma;
  2151. return 0;
  2152. }
  2153. /**
  2154. * Initialize implicit_weight table.
  2155. * @param field 0/1 initialize the weight for interlaced MBAFF
  2156. * -1 initializes the rest
  2157. */
  2158. static void implicit_weight_table(H264Context *h, int field)
  2159. {
  2160. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  2161. for (i = 0; i < 2; i++) {
  2162. h->luma_weight_flag[i] = 0;
  2163. h->chroma_weight_flag[i] = 0;
  2164. }
  2165. if (field < 0) {
  2166. if (h->picture_structure == PICT_FRAME) {
  2167. cur_poc = h->cur_pic_ptr->poc;
  2168. } else {
  2169. cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
  2170. }
  2171. if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
  2172. h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
  2173. h->use_weight = 0;
  2174. h->use_weight_chroma = 0;
  2175. return;
  2176. }
  2177. ref_start = 0;
  2178. ref_count0 = h->ref_count[0];
  2179. ref_count1 = h->ref_count[1];
  2180. } else {
  2181. cur_poc = h->cur_pic_ptr->field_poc[field];
  2182. ref_start = 16;
  2183. ref_count0 = 16 + 2 * h->ref_count[0];
  2184. ref_count1 = 16 + 2 * h->ref_count[1];
  2185. }
  2186. h->use_weight = 2;
  2187. h->use_weight_chroma = 2;
  2188. h->luma_log2_weight_denom = 5;
  2189. h->chroma_log2_weight_denom = 5;
  2190. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  2191. int poc0 = h->ref_list[0][ref0].poc;
  2192. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  2193. int w = 32;
  2194. if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
  2195. int poc1 = h->ref_list[1][ref1].poc;
  2196. int td = av_clip(poc1 - poc0, -128, 127);
  2197. if (td) {
  2198. int tb = av_clip(cur_poc - poc0, -128, 127);
  2199. int tx = (16384 + (FFABS(td) >> 1)) / td;
  2200. int dist_scale_factor = (tb * tx + 32) >> 8;
  2201. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  2202. w = 64 - dist_scale_factor;
  2203. }
  2204. }
  2205. if (field < 0) {
  2206. h->implicit_weight[ref0][ref1][0] =
  2207. h->implicit_weight[ref0][ref1][1] = w;
  2208. } else {
  2209. h->implicit_weight[ref0][ref1][field] = w;
  2210. }
  2211. }
  2212. }
  2213. }
  2214. /**
  2215. * instantaneous decoder refresh.
  2216. */
  2217. static void idr(H264Context *h)
  2218. {
  2219. int i;
  2220. ff_h264_remove_all_refs(h);
  2221. h->prev_frame_num = 0;
  2222. h->prev_frame_num_offset = 0;
  2223. h->prev_poc_msb = 1<<16;
  2224. h->prev_poc_lsb = 0;
  2225. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  2226. h->last_pocs[i] = INT_MIN;
  2227. }
  2228. /* forget old pics after a seek */
  2229. static void flush_change(H264Context *h)
  2230. {
  2231. int i, j;
  2232. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  2233. h->prev_interlaced_frame = 1;
  2234. idr(h);
  2235. h->prev_frame_num = -1;
  2236. if (h->cur_pic_ptr) {
  2237. h->cur_pic_ptr->f.reference = 0;
  2238. for (j=i=0; h->delayed_pic[i]; i++)
  2239. if (h->delayed_pic[i] != h->cur_pic_ptr)
  2240. h->delayed_pic[j++] = h->delayed_pic[i];
  2241. h->delayed_pic[j] = NULL;
  2242. }
  2243. h->first_field = 0;
  2244. memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
  2245. memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
  2246. memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
  2247. memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
  2248. ff_h264_reset_sei(h);
  2249. h->recovery_frame= -1;
  2250. h->sync= 0;
  2251. h->list_count = 0;
  2252. h->current_slice = 0;
  2253. }
  2254. /* forget old pics after a seek */
  2255. static void flush_dpb(AVCodecContext *avctx)
  2256. {
  2257. H264Context *h = avctx->priv_data;
  2258. int i;
  2259. for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
  2260. if (h->delayed_pic[i])
  2261. h->delayed_pic[i]->f.reference = 0;
  2262. h->delayed_pic[i] = NULL;
  2263. }
  2264. flush_change(h);
  2265. for (i = 0; i < h->picture_count; i++) {
  2266. if (h->DPB[i].f.data[0])
  2267. free_frame_buffer(h, &h->DPB[i]);
  2268. }
  2269. h->cur_pic_ptr = NULL;
  2270. h->mb_x = h->mb_y = 0;
  2271. h->parse_context.state = -1;
  2272. h->parse_context.frame_start_found = 0;
  2273. h->parse_context.overread = 0;
  2274. h->parse_context.overread_index = 0;
  2275. h->parse_context.index = 0;
  2276. h->parse_context.last_index = 0;
  2277. }
  2278. static int init_poc(H264Context *h)
  2279. {
  2280. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2281. int field_poc[2];
  2282. Picture *cur = h->cur_pic_ptr;
  2283. h->frame_num_offset = h->prev_frame_num_offset;
  2284. if (h->frame_num < h->prev_frame_num)
  2285. h->frame_num_offset += max_frame_num;
  2286. if (h->sps.poc_type == 0) {
  2287. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  2288. 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 if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  2291. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  2292. else
  2293. h->poc_msb = h->prev_poc_msb;
  2294. field_poc[0] =
  2295. field_poc[1] = h->poc_msb + h->poc_lsb;
  2296. if (h->picture_structure == PICT_FRAME)
  2297. field_poc[1] += h->delta_poc_bottom;
  2298. } else if (h->sps.poc_type == 1) {
  2299. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  2300. int i;
  2301. if (h->sps.poc_cycle_length != 0)
  2302. abs_frame_num = h->frame_num_offset + h->frame_num;
  2303. else
  2304. abs_frame_num = 0;
  2305. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  2306. abs_frame_num--;
  2307. expected_delta_per_poc_cycle = 0;
  2308. for (i = 0; i < h->sps.poc_cycle_length; i++)
  2309. // FIXME integrate during sps parse
  2310. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  2311. if (abs_frame_num > 0) {
  2312. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  2313. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  2314. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  2315. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  2316. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  2317. } else
  2318. expectedpoc = 0;
  2319. if (h->nal_ref_idc == 0)
  2320. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  2321. field_poc[0] = expectedpoc + h->delta_poc[0];
  2322. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  2323. if (h->picture_structure == PICT_FRAME)
  2324. field_poc[1] += h->delta_poc[1];
  2325. } else {
  2326. int poc = 2 * (h->frame_num_offset + h->frame_num);
  2327. if (!h->nal_ref_idc)
  2328. poc--;
  2329. field_poc[0] = poc;
  2330. field_poc[1] = poc;
  2331. }
  2332. if (h->picture_structure != PICT_BOTTOM_FIELD)
  2333. h->cur_pic_ptr->field_poc[0] = field_poc[0];
  2334. if (h->picture_structure != PICT_TOP_FIELD)
  2335. h->cur_pic_ptr->field_poc[1] = field_poc[1];
  2336. cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
  2337. return 0;
  2338. }
  2339. /**
  2340. * initialize scan tables
  2341. */
  2342. static void init_scan_tables(H264Context *h)
  2343. {
  2344. int i;
  2345. for (i = 0; i < 16; i++) {
  2346. #define T(x) (x >> 2) | ((x << 2) & 0xF)
  2347. h->zigzag_scan[i] = T(zigzag_scan[i]);
  2348. h->field_scan[i] = T(field_scan[i]);
  2349. #undef T
  2350. }
  2351. for (i = 0; i < 64; i++) {
  2352. #define T(x) (x >> 3) | ((x & 7) << 3)
  2353. h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
  2354. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  2355. h->field_scan8x8[i] = T(field_scan8x8[i]);
  2356. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  2357. #undef T
  2358. }
  2359. if (h->sps.transform_bypass) { // FIXME same ugly
  2360. memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  2361. memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
  2362. memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  2363. memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
  2364. memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2365. memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2366. } else {
  2367. memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  2368. memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
  2369. memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  2370. memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
  2371. memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2372. memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2373. }
  2374. }
  2375. static int field_end(H264Context *h, int in_setup)
  2376. {
  2377. AVCodecContext *const avctx = h->avctx;
  2378. int err = 0;
  2379. h->mb_y = 0;
  2380. if (!in_setup && !h->droppable)
  2381. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  2382. h->picture_structure == PICT_BOTTOM_FIELD);
  2383. if (CONFIG_H264_VDPAU_DECODER &&
  2384. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2385. ff_vdpau_h264_set_reference_frames(h);
  2386. if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
  2387. if (!h->droppable) {
  2388. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2389. h->prev_poc_msb = h->poc_msb;
  2390. h->prev_poc_lsb = h->poc_lsb;
  2391. }
  2392. h->prev_frame_num_offset = h->frame_num_offset;
  2393. h->prev_frame_num = h->frame_num;
  2394. h->outputed_poc = h->next_outputed_poc;
  2395. }
  2396. if (avctx->hwaccel) {
  2397. if (avctx->hwaccel->end_frame(avctx) < 0)
  2398. av_log(avctx, AV_LOG_ERROR,
  2399. "hardware accelerator failed to decode picture\n");
  2400. }
  2401. if (CONFIG_H264_VDPAU_DECODER &&
  2402. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2403. ff_vdpau_h264_picture_complete(h);
  2404. /*
  2405. * FIXME: Error handling code does not seem to support interlaced
  2406. * when slices span multiple rows
  2407. * The ff_er_add_slice calls don't work right for bottom
  2408. * fields; they cause massive erroneous error concealing
  2409. * Error marking covers both fields (top and bottom).
  2410. * This causes a mismatched s->error_count
  2411. * and a bad error table. Further, the error count goes to
  2412. * INT_MAX when called for bottom field, because mb_y is
  2413. * past end by one (callers fault) and resync_mb_y != 0
  2414. * causes problems for the first MB line, too.
  2415. */
  2416. if (!FIELD_PICTURE && h->current_slice && !h->sps.new) {
  2417. h->er.cur_pic = h->cur_pic_ptr;
  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, int force_callback)
  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 && !force_callback)
  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, 0))
  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, 1)) < 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, 1)) < 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->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];
  3292. if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];
  3293. if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
  3294. av_log(h->avctx, AV_LOG_DEBUG,
  3295. "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",
  3296. h->slice_num,
  3297. (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  3298. first_mb_in_slice,
  3299. av_get_picture_type_char(h->slice_type),
  3300. h->slice_type_fixed ? " fix" : "",
  3301. h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  3302. pps_id, h->frame_num,
  3303. h->cur_pic_ptr->field_poc[0],
  3304. h->cur_pic_ptr->field_poc[1],
  3305. h->ref_count[0], h->ref_count[1],
  3306. h->qscale,
  3307. h->deblocking_filter,
  3308. h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
  3309. h->use_weight,
  3310. h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
  3311. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  3312. }
  3313. return 0;
  3314. }
  3315. int ff_h264_get_slice_type(const H264Context *h)
  3316. {
  3317. switch (h->slice_type) {
  3318. case AV_PICTURE_TYPE_P:
  3319. return 0;
  3320. case AV_PICTURE_TYPE_B:
  3321. return 1;
  3322. case AV_PICTURE_TYPE_I:
  3323. return 2;
  3324. case AV_PICTURE_TYPE_SP:
  3325. return 3;
  3326. case AV_PICTURE_TYPE_SI:
  3327. return 4;
  3328. default:
  3329. return -1;
  3330. }
  3331. }
  3332. static av_always_inline void fill_filter_caches_inter(H264Context *h,
  3333. int mb_type, int top_xy,
  3334. int left_xy[LEFT_MBS],
  3335. int top_type,
  3336. int left_type[LEFT_MBS],
  3337. int mb_xy, int list)
  3338. {
  3339. int b_stride = h->b_stride;
  3340. int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
  3341. int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
  3342. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  3343. if (USES_LIST(top_type, list)) {
  3344. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  3345. const int b8_xy = 4 * top_xy + 2;
  3346. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  3347. AV_COPY128(mv_dst - 1 * 8, h->cur_pic.f.motion_val[list][b_xy + 0]);
  3348. ref_cache[0 - 1 * 8] =
  3349. ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 0]];
  3350. ref_cache[2 - 1 * 8] =
  3351. ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 1]];
  3352. } else {
  3353. AV_ZERO128(mv_dst - 1 * 8);
  3354. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3355. }
  3356. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  3357. if (USES_LIST(left_type[LTOP], list)) {
  3358. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  3359. const int b8_xy = 4 * left_xy[LTOP] + 1;
  3360. int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  3361. AV_COPY32(mv_dst - 1 + 0, h->cur_pic.f.motion_val[list][b_xy + b_stride * 0]);
  3362. AV_COPY32(mv_dst - 1 + 8, h->cur_pic.f.motion_val[list][b_xy + b_stride * 1]);
  3363. AV_COPY32(mv_dst - 1 + 16, h->cur_pic.f.motion_val[list][b_xy + b_stride * 2]);
  3364. AV_COPY32(mv_dst - 1 + 24, h->cur_pic.f.motion_val[list][b_xy + b_stride * 3]);
  3365. ref_cache[-1 + 0] =
  3366. ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 0]];
  3367. ref_cache[-1 + 16] =
  3368. ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 1]];
  3369. } else {
  3370. AV_ZERO32(mv_dst - 1 + 0);
  3371. AV_ZERO32(mv_dst - 1 + 8);
  3372. AV_ZERO32(mv_dst - 1 + 16);
  3373. AV_ZERO32(mv_dst - 1 + 24);
  3374. ref_cache[-1 + 0] =
  3375. ref_cache[-1 + 8] =
  3376. ref_cache[-1 + 16] =
  3377. ref_cache[-1 + 24] = LIST_NOT_USED;
  3378. }
  3379. }
  3380. }
  3381. if (!USES_LIST(mb_type, list)) {
  3382. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  3383. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3384. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3385. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3386. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3387. return;
  3388. }
  3389. {
  3390. int8_t *ref = &h->cur_pic.f.ref_index[list][4 * mb_xy];
  3391. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  3392. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
  3393. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
  3394. AV_WN32A(&ref_cache[0 * 8], ref01);
  3395. AV_WN32A(&ref_cache[1 * 8], ref01);
  3396. AV_WN32A(&ref_cache[2 * 8], ref23);
  3397. AV_WN32A(&ref_cache[3 * 8], ref23);
  3398. }
  3399. {
  3400. int16_t(*mv_src)[2] = &h->cur_pic.f.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
  3401. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  3402. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  3403. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  3404. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  3405. }
  3406. }
  3407. /**
  3408. *
  3409. * @return non zero if the loop filter can be skipped
  3410. */
  3411. static int fill_filter_caches(H264Context *h, int mb_type)
  3412. {
  3413. const int mb_xy = h->mb_xy;
  3414. int top_xy, left_xy[LEFT_MBS];
  3415. int top_type, left_type[LEFT_MBS];
  3416. uint8_t *nnz;
  3417. uint8_t *nnz_cache;
  3418. top_xy = mb_xy - (h->mb_stride << MB_FIELD);
  3419. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  3420. * stuff, I can't imagine that these complex rules are worth it. */
  3421. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  3422. if (FRAME_MBAFF) {
  3423. const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.f.mb_type[mb_xy - 1]);
  3424. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  3425. if (h->mb_y & 1) {
  3426. if (left_mb_field_flag != curr_mb_field_flag)
  3427. left_xy[LTOP] -= h->mb_stride;
  3428. } else {
  3429. if (curr_mb_field_flag)
  3430. top_xy += h->mb_stride &
  3431. (((h->cur_pic.f.mb_type[top_xy] >> 7) & 1) - 1);
  3432. if (left_mb_field_flag != curr_mb_field_flag)
  3433. left_xy[LBOT] += h->mb_stride;
  3434. }
  3435. }
  3436. h->top_mb_xy = top_xy;
  3437. h->left_mb_xy[LTOP] = left_xy[LTOP];
  3438. h->left_mb_xy[LBOT] = left_xy[LBOT];
  3439. {
  3440. /* For sufficiently low qp, filtering wouldn't do anything.
  3441. * This is a conservative estimate: could also check beta_offset
  3442. * and more accurate chroma_qp. */
  3443. int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  3444. int qp = h->cur_pic.f.qscale_table[mb_xy];
  3445. if (qp <= qp_thresh &&
  3446. (left_xy[LTOP] < 0 ||
  3447. ((qp + h->cur_pic.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  3448. (top_xy < 0 ||
  3449. ((qp + h->cur_pic.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  3450. if (!FRAME_MBAFF)
  3451. return 1;
  3452. if ((left_xy[LTOP] < 0 ||
  3453. ((qp + h->cur_pic.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  3454. (top_xy < h->mb_stride ||
  3455. ((qp + h->cur_pic.f.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
  3456. return 1;
  3457. }
  3458. }
  3459. top_type = h->cur_pic.f.mb_type[top_xy];
  3460. left_type[LTOP] = h->cur_pic.f.mb_type[left_xy[LTOP]];
  3461. left_type[LBOT] = h->cur_pic.f.mb_type[left_xy[LBOT]];
  3462. if (h->deblocking_filter == 2) {
  3463. if (h->slice_table[top_xy] != h->slice_num)
  3464. top_type = 0;
  3465. if (h->slice_table[left_xy[LBOT]] != h->slice_num)
  3466. left_type[LTOP] = left_type[LBOT] = 0;
  3467. } else {
  3468. if (h->slice_table[top_xy] == 0xFFFF)
  3469. top_type = 0;
  3470. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  3471. left_type[LTOP] = left_type[LBOT] = 0;
  3472. }
  3473. h->top_type = top_type;
  3474. h->left_type[LTOP] = left_type[LTOP];
  3475. h->left_type[LBOT] = left_type[LBOT];
  3476. if (IS_INTRA(mb_type))
  3477. return 0;
  3478. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3479. top_type, left_type, mb_xy, 0);
  3480. if (h->list_count == 2)
  3481. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3482. top_type, left_type, mb_xy, 1);
  3483. nnz = h->non_zero_count[mb_xy];
  3484. nnz_cache = h->non_zero_count_cache;
  3485. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  3486. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  3487. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  3488. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  3489. h->cbp = h->cbp_table[mb_xy];
  3490. if (top_type) {
  3491. nnz = h->non_zero_count[top_xy];
  3492. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  3493. }
  3494. if (left_type[LTOP]) {
  3495. nnz = h->non_zero_count[left_xy[LTOP]];
  3496. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  3497. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  3498. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  3499. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  3500. }
  3501. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  3502. * from what the loop filter needs */
  3503. if (!CABAC && h->pps.transform_8x8_mode) {
  3504. if (IS_8x8DCT(top_type)) {
  3505. nnz_cache[4 + 8 * 0] =
  3506. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  3507. nnz_cache[6 + 8 * 0] =
  3508. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  3509. }
  3510. if (IS_8x8DCT(left_type[LTOP])) {
  3511. nnz_cache[3 + 8 * 1] =
  3512. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  3513. }
  3514. if (IS_8x8DCT(left_type[LBOT])) {
  3515. nnz_cache[3 + 8 * 3] =
  3516. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  3517. }
  3518. if (IS_8x8DCT(mb_type)) {
  3519. nnz_cache[scan8[0]] =
  3520. nnz_cache[scan8[1]] =
  3521. nnz_cache[scan8[2]] =
  3522. nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
  3523. nnz_cache[scan8[0 + 4]] =
  3524. nnz_cache[scan8[1 + 4]] =
  3525. nnz_cache[scan8[2 + 4]] =
  3526. nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
  3527. nnz_cache[scan8[0 + 8]] =
  3528. nnz_cache[scan8[1 + 8]] =
  3529. nnz_cache[scan8[2 + 8]] =
  3530. nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
  3531. nnz_cache[scan8[0 + 12]] =
  3532. nnz_cache[scan8[1 + 12]] =
  3533. nnz_cache[scan8[2 + 12]] =
  3534. nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
  3535. }
  3536. }
  3537. return 0;
  3538. }
  3539. static void loop_filter(H264Context *h, int start_x, int end_x)
  3540. {
  3541. uint8_t *dest_y, *dest_cb, *dest_cr;
  3542. int linesize, uvlinesize, mb_x, mb_y;
  3543. const int end_mb_y = h->mb_y + FRAME_MBAFF;
  3544. const int old_slice_type = h->slice_type;
  3545. const int pixel_shift = h->pixel_shift;
  3546. const int block_h = 16 >> h->chroma_y_shift;
  3547. if (h->deblocking_filter) {
  3548. for (mb_x = start_x; mb_x < end_x; mb_x++)
  3549. for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
  3550. int mb_xy, mb_type;
  3551. mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
  3552. h->slice_num = h->slice_table[mb_xy];
  3553. mb_type = h->cur_pic.f.mb_type[mb_xy];
  3554. h->list_count = h->list_counts[mb_xy];
  3555. if (FRAME_MBAFF)
  3556. h->mb_mbaff =
  3557. h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  3558. h->mb_x = mb_x;
  3559. h->mb_y = mb_y;
  3560. dest_y = h->cur_pic.f.data[0] +
  3561. ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
  3562. dest_cb = h->cur_pic.f.data[1] +
  3563. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3564. mb_y * h->uvlinesize * block_h;
  3565. dest_cr = h->cur_pic.f.data[2] +
  3566. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3567. mb_y * h->uvlinesize * block_h;
  3568. // FIXME simplify above
  3569. if (MB_FIELD) {
  3570. linesize = h->mb_linesize = h->linesize * 2;
  3571. uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
  3572. if (mb_y & 1) { // FIXME move out of this function?
  3573. dest_y -= h->linesize * 15;
  3574. dest_cb -= h->uvlinesize * (block_h - 1);
  3575. dest_cr -= h->uvlinesize * (block_h - 1);
  3576. }
  3577. } else {
  3578. linesize = h->mb_linesize = h->linesize;
  3579. uvlinesize = h->mb_uvlinesize = h->uvlinesize;
  3580. }
  3581. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
  3582. uvlinesize, 0);
  3583. if (fill_filter_caches(h, mb_type))
  3584. continue;
  3585. h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.f.qscale_table[mb_xy]);
  3586. h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.f.qscale_table[mb_xy]);
  3587. if (FRAME_MBAFF) {
  3588. ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  3589. linesize, uvlinesize);
  3590. } else {
  3591. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
  3592. dest_cr, linesize, uvlinesize);
  3593. }
  3594. }
  3595. }
  3596. h->slice_type = old_slice_type;
  3597. h->mb_x = end_x;
  3598. h->mb_y = end_mb_y - FRAME_MBAFF;
  3599. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  3600. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  3601. }
  3602. static void predict_field_decoding_flag(H264Context *h)
  3603. {
  3604. const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
  3605. int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
  3606. h->cur_pic.f.mb_type[mb_xy - 1] :
  3607. (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
  3608. h->cur_pic.f.mb_type[mb_xy - h->mb_stride] : 0;
  3609. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3610. }
  3611. /**
  3612. * Draw edges and report progress for the last MB row.
  3613. */
  3614. static void decode_finish_row(H264Context *h)
  3615. {
  3616. int top = 16 * (h->mb_y >> FIELD_PICTURE);
  3617. int pic_height = 16 * h->mb_height >> FIELD_PICTURE;
  3618. int height = 16 << FRAME_MBAFF;
  3619. int deblock_border = (16 + 4) << FRAME_MBAFF;
  3620. if (h->deblocking_filter) {
  3621. if ((top + height) >= pic_height)
  3622. height += deblock_border;
  3623. top -= deblock_border;
  3624. }
  3625. if (top >= pic_height || (top + height) < 0)
  3626. return;
  3627. height = FFMIN(height, pic_height - top);
  3628. if (top < 0) {
  3629. height = top + height;
  3630. top = 0;
  3631. }
  3632. ff_h264_draw_horiz_band(h, top, height);
  3633. if (h->droppable)
  3634. return;
  3635. ff_thread_report_progress(&h->cur_pic_ptr->f, top + height - 1,
  3636. h->picture_structure == PICT_BOTTOM_FIELD);
  3637. }
  3638. static void er_add_slice(H264Context *h, int startx, int starty,
  3639. int endx, int endy, int status)
  3640. {
  3641. ERContext *er = &h->er;
  3642. er->ref_count = h->ref_count[0];
  3643. ff_er_add_slice(er, startx, starty, endx, endy, status);
  3644. }
  3645. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  3646. {
  3647. H264Context *h = *(void **)arg;
  3648. int lf_x_start = h->mb_x;
  3649. h->mb_skip_run = -1;
  3650. av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
  3651. h->is_complex = FRAME_MBAFF || h->picture_structure != PICT_FRAME ||
  3652. avctx->codec_id != AV_CODEC_ID_H264 ||
  3653. (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
  3654. if (h->pps.cabac) {
  3655. /* realign */
  3656. align_get_bits(&h->gb);
  3657. /* init cabac */
  3658. ff_init_cabac_decoder(&h->cabac,
  3659. h->gb.buffer + get_bits_count(&h->gb) / 8,
  3660. (get_bits_left(&h->gb) + 7) / 8);
  3661. ff_h264_init_cabac_states(h);
  3662. for (;;) {
  3663. // START_TIMER
  3664. int ret = ff_h264_decode_mb_cabac(h);
  3665. int eos;
  3666. // STOP_TIMER("decode_mb_cabac")
  3667. if (ret >= 0)
  3668. ff_h264_hl_decode_mb(h);
  3669. // FIXME optimal? or let mb_decode decode 16x32 ?
  3670. if (ret >= 0 && FRAME_MBAFF) {
  3671. h->mb_y++;
  3672. ret = ff_h264_decode_mb_cabac(h);
  3673. if (ret >= 0)
  3674. ff_h264_hl_decode_mb(h);
  3675. h->mb_y--;
  3676. }
  3677. eos = get_cabac_terminate(&h->cabac);
  3678. if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
  3679. h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3680. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  3681. h->mb_y, ER_MB_END);
  3682. if (h->mb_x >= lf_x_start)
  3683. loop_filter(h, lf_x_start, h->mb_x + 1);
  3684. return 0;
  3685. }
  3686. if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
  3687. av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
  3688. if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
  3689. av_log(h->avctx, AV_LOG_ERROR,
  3690. "error while decoding MB %d %d, bytestream (%td)\n",
  3691. h->mb_x, h->mb_y,
  3692. h->cabac.bytestream_end - h->cabac.bytestream);
  3693. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3694. h->mb_y, ER_MB_ERROR);
  3695. return -1;
  3696. }
  3697. if (++h->mb_x >= h->mb_width) {
  3698. loop_filter(h, lf_x_start, h->mb_x);
  3699. h->mb_x = lf_x_start = 0;
  3700. decode_finish_row(h);
  3701. ++h->mb_y;
  3702. if (FIELD_OR_MBAFF_PICTURE) {
  3703. ++h->mb_y;
  3704. if (FRAME_MBAFF && h->mb_y < h->mb_height)
  3705. predict_field_decoding_flag(h);
  3706. }
  3707. }
  3708. if (eos || h->mb_y >= h->mb_height) {
  3709. tprintf(h->avctx, "slice end %d %d\n",
  3710. get_bits_count(&h->gb), h->gb.size_in_bits);
  3711. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  3712. h->mb_y, ER_MB_END);
  3713. if (h->mb_x > lf_x_start)
  3714. loop_filter(h, lf_x_start, h->mb_x);
  3715. return 0;
  3716. }
  3717. }
  3718. } else {
  3719. for (;;) {
  3720. int ret = ff_h264_decode_mb_cavlc(h);
  3721. if (ret >= 0)
  3722. ff_h264_hl_decode_mb(h);
  3723. // FIXME optimal? or let mb_decode decode 16x32 ?
  3724. if (ret >= 0 && FRAME_MBAFF) {
  3725. h->mb_y++;
  3726. ret = ff_h264_decode_mb_cavlc(h);
  3727. if (ret >= 0)
  3728. ff_h264_hl_decode_mb(h);
  3729. h->mb_y--;
  3730. }
  3731. if (ret < 0) {
  3732. av_log(h->avctx, AV_LOG_ERROR,
  3733. "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
  3734. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3735. h->mb_y, ER_MB_ERROR);
  3736. return -1;
  3737. }
  3738. if (++h->mb_x >= h->mb_width) {
  3739. loop_filter(h, lf_x_start, h->mb_x);
  3740. h->mb_x = lf_x_start = 0;
  3741. decode_finish_row(h);
  3742. ++h->mb_y;
  3743. if (FIELD_OR_MBAFF_PICTURE) {
  3744. ++h->mb_y;
  3745. if (FRAME_MBAFF && h->mb_y < h->mb_height)
  3746. predict_field_decoding_flag(h);
  3747. }
  3748. if (h->mb_y >= h->mb_height) {
  3749. tprintf(h->avctx, "slice end %d %d\n",
  3750. get_bits_count(&h->gb), h->gb.size_in_bits);
  3751. if ( get_bits_left(&h->gb) == 0
  3752. || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
  3753. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3754. h->mb_x - 1, h->mb_y,
  3755. ER_MB_END);
  3756. return 0;
  3757. } else {
  3758. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3759. h->mb_x, h->mb_y,
  3760. ER_MB_END);
  3761. return -1;
  3762. }
  3763. }
  3764. }
  3765. if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
  3766. tprintf(h->avctx, "slice end %d %d\n",
  3767. get_bits_count(&h->gb), h->gb.size_in_bits);
  3768. if (get_bits_left(&h->gb) == 0) {
  3769. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3770. h->mb_x - 1, h->mb_y,
  3771. ER_MB_END);
  3772. if (h->mb_x > lf_x_start)
  3773. loop_filter(h, lf_x_start, h->mb_x);
  3774. return 0;
  3775. } else {
  3776. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3777. h->mb_y, ER_MB_ERROR);
  3778. return -1;
  3779. }
  3780. }
  3781. }
  3782. }
  3783. }
  3784. /**
  3785. * Call decode_slice() for each context.
  3786. *
  3787. * @param h h264 master context
  3788. * @param context_count number of contexts to execute
  3789. */
  3790. static int execute_decode_slices(H264Context *h, int context_count)
  3791. {
  3792. AVCodecContext *const avctx = h->avctx;
  3793. H264Context *hx;
  3794. int i;
  3795. if (h->avctx->hwaccel ||
  3796. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3797. return 0;
  3798. if (context_count == 1) {
  3799. return decode_slice(avctx, &h);
  3800. } else {
  3801. av_assert0(context_count > 0);
  3802. for (i = 1; i < context_count; i++) {
  3803. hx = h->thread_context[i];
  3804. hx->er.error_count = 0;
  3805. hx->x264_build = h->x264_build;
  3806. }
  3807. avctx->execute(avctx, decode_slice, h->thread_context,
  3808. NULL, context_count, sizeof(void *));
  3809. /* pull back stuff from slices to master context */
  3810. hx = h->thread_context[context_count - 1];
  3811. h->mb_x = hx->mb_x;
  3812. h->mb_y = hx->mb_y;
  3813. h->droppable = hx->droppable;
  3814. h->picture_structure = hx->picture_structure;
  3815. for (i = 1; i < context_count; i++)
  3816. h->er.error_count += h->thread_context[i]->er.error_count;
  3817. }
  3818. return 0;
  3819. }
  3820. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  3821. int parse_extradata)
  3822. {
  3823. AVCodecContext *const avctx = h->avctx;
  3824. H264Context *hx; ///< thread context
  3825. int buf_index;
  3826. int context_count;
  3827. int next_avc;
  3828. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  3829. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  3830. int nal_index;
  3831. int idr_cleared=0;
  3832. int first_slice = 0;
  3833. h->nal_unit_type= 0;
  3834. if(!h->slice_context_count)
  3835. h->slice_context_count= 1;
  3836. h->max_contexts = h->slice_context_count;
  3837. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
  3838. h->current_slice = 0;
  3839. if (!h->first_field)
  3840. h->cur_pic_ptr = NULL;
  3841. ff_h264_reset_sei(h);
  3842. }
  3843. if (h->nal_length_size == 4) {
  3844. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  3845. h->is_avc = 0;
  3846. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  3847. h->is_avc = 1;
  3848. }
  3849. for (; pass <= 1; pass++) {
  3850. buf_index = 0;
  3851. context_count = 0;
  3852. next_avc = h->is_avc ? 0 : buf_size;
  3853. nal_index = 0;
  3854. for (;;) {
  3855. int consumed;
  3856. int dst_length;
  3857. int bit_length;
  3858. const uint8_t *ptr;
  3859. int i, nalsize = 0;
  3860. int err;
  3861. if (buf_index >= next_avc) {
  3862. if (buf_index >= buf_size - h->nal_length_size)
  3863. break;
  3864. nalsize = 0;
  3865. for (i = 0; i < h->nal_length_size; i++)
  3866. nalsize = (nalsize << 8) | buf[buf_index++];
  3867. if (nalsize <= 0 || nalsize > buf_size - buf_index) {
  3868. av_log(h->avctx, AV_LOG_ERROR,
  3869. "AVC: nal size %d\n", nalsize);
  3870. break;
  3871. }
  3872. next_avc = buf_index + nalsize;
  3873. } else {
  3874. // start code prefix search
  3875. for (; buf_index + 3 < next_avc; buf_index++)
  3876. // This should always succeed in the first iteration.
  3877. if (buf[buf_index] == 0 &&
  3878. buf[buf_index + 1] == 0 &&
  3879. buf[buf_index + 2] == 1)
  3880. break;
  3881. if (buf_index + 3 >= buf_size) {
  3882. buf_index = buf_size;
  3883. break;
  3884. }
  3885. buf_index += 3;
  3886. if (buf_index >= next_avc)
  3887. continue;
  3888. }
  3889. hx = h->thread_context[context_count];
  3890. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  3891. &consumed, next_avc - buf_index);
  3892. if (ptr == NULL || dst_length < 0) {
  3893. buf_index = -1;
  3894. goto end;
  3895. }
  3896. i = buf_index + consumed;
  3897. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  3898. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  3899. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  3900. h->workaround_bugs |= FF_BUG_TRUNCATED;
  3901. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  3902. while(dst_length > 0 && ptr[dst_length - 1] == 0)
  3903. dst_length--;
  3904. bit_length = !dst_length ? 0
  3905. : (8 * dst_length -
  3906. decode_rbsp_trailing(h, ptr + dst_length - 1));
  3907. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  3908. 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);
  3909. if (h->is_avc && (nalsize != consumed) && nalsize)
  3910. av_log(h->avctx, AV_LOG_DEBUG,
  3911. "AVC: Consumed only %d bytes instead of %d\n",
  3912. consumed, nalsize);
  3913. buf_index += consumed;
  3914. nal_index++;
  3915. if (pass == 0) {
  3916. /* packets can sometimes contain multiple PPS/SPS,
  3917. * e.g. two PAFF field pictures in one packet, or a demuxer
  3918. * which splits NALs strangely if so, when frame threading we
  3919. * can't start the next thread until we've read all of them */
  3920. switch (hx->nal_unit_type) {
  3921. case NAL_SPS:
  3922. case NAL_PPS:
  3923. nals_needed = nal_index;
  3924. break;
  3925. case NAL_DPA:
  3926. case NAL_IDR_SLICE:
  3927. case NAL_SLICE:
  3928. init_get_bits(&hx->gb, ptr, bit_length);
  3929. if (!get_ue_golomb(&hx->gb) || !first_slice)
  3930. nals_needed = nal_index;
  3931. if (!first_slice)
  3932. first_slice = hx->nal_unit_type;
  3933. }
  3934. continue;
  3935. }
  3936. if (!first_slice)
  3937. switch (hx->nal_unit_type) {
  3938. case NAL_DPA:
  3939. case NAL_IDR_SLICE:
  3940. case NAL_SLICE:
  3941. first_slice = hx->nal_unit_type;
  3942. }
  3943. // FIXME do not discard SEI id
  3944. if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
  3945. continue;
  3946. again:
  3947. /* Ignore per frame NAL unit type during extradata
  3948. * parsing. Decoding slices is not possible in codec init
  3949. * with frame-mt */
  3950. if (parse_extradata) {
  3951. switch (hx->nal_unit_type) {
  3952. case NAL_IDR_SLICE:
  3953. case NAL_SLICE:
  3954. case NAL_DPA:
  3955. case NAL_DPB:
  3956. case NAL_DPC:
  3957. case NAL_AUXILIARY_SLICE:
  3958. av_log(h->avctx, AV_LOG_WARNING, "Ignoring NAL %d in global header/extradata\n", hx->nal_unit_type);
  3959. hx->nal_unit_type = NAL_FF_IGNORE;
  3960. }
  3961. }
  3962. err = 0;
  3963. switch (hx->nal_unit_type) {
  3964. case NAL_IDR_SLICE:
  3965. if (first_slice != NAL_IDR_SLICE) {
  3966. av_log(h->avctx, AV_LOG_ERROR,
  3967. "Invalid mix of idr and non-idr slices\n");
  3968. buf_index = -1;
  3969. goto end;
  3970. }
  3971. if(!idr_cleared)
  3972. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  3973. idr_cleared = 1;
  3974. case NAL_SLICE:
  3975. init_get_bits(&hx->gb, ptr, bit_length);
  3976. hx->intra_gb_ptr =
  3977. hx->inter_gb_ptr = &hx->gb;
  3978. hx->data_partitioning = 0;
  3979. if ((err = decode_slice_header(hx, h)))
  3980. break;
  3981. if (h->sei_recovery_frame_cnt >= 0 && (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I))
  3982. h->valid_recovery_point = 1;
  3983. if ( h->sei_recovery_frame_cnt >= 0
  3984. && ( h->recovery_frame<0
  3985. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
  3986. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
  3987. (1 << h->sps.log2_max_frame_num);
  3988. if (!h->valid_recovery_point)
  3989. h->recovery_frame = h->frame_num;
  3990. }
  3991. h->cur_pic_ptr->f.key_frame |=
  3992. (hx->nal_unit_type == NAL_IDR_SLICE);
  3993. if (h->recovery_frame == h->frame_num) {
  3994. h->cur_pic_ptr->sync |= 1;
  3995. h->recovery_frame = -1;
  3996. }
  3997. h->sync |= !!h->cur_pic_ptr->f.key_frame;
  3998. h->sync |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
  3999. h->cur_pic_ptr->sync |= h->sync;
  4000. if (h->current_slice == 1) {
  4001. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
  4002. decode_postinit(h, nal_index >= nals_needed);
  4003. if (h->avctx->hwaccel &&
  4004. h->avctx->hwaccel->start_frame(h->avctx, NULL, 0) < 0)
  4005. return -1;
  4006. if (CONFIG_H264_VDPAU_DECODER &&
  4007. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  4008. ff_vdpau_h264_picture_start(h);
  4009. }
  4010. if (hx->redundant_pic_count == 0 &&
  4011. (avctx->skip_frame < AVDISCARD_NONREF ||
  4012. hx->nal_ref_idc) &&
  4013. (avctx->skip_frame < AVDISCARD_BIDIR ||
  4014. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  4015. (avctx->skip_frame < AVDISCARD_NONKEY ||
  4016. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  4017. avctx->skip_frame < AVDISCARD_ALL) {
  4018. if (avctx->hwaccel) {
  4019. if (avctx->hwaccel->decode_slice(avctx,
  4020. &buf[buf_index - consumed],
  4021. consumed) < 0)
  4022. return -1;
  4023. } else if (CONFIG_H264_VDPAU_DECODER &&
  4024. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  4025. static const uint8_t start_code[] = {
  4026. 0x00, 0x00, 0x01 };
  4027. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], start_code,
  4028. sizeof(start_code));
  4029. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], &buf[buf_index - consumed],
  4030. consumed);
  4031. } else
  4032. context_count++;
  4033. }
  4034. break;
  4035. case NAL_DPA:
  4036. init_get_bits(&hx->gb, ptr, bit_length);
  4037. hx->intra_gb_ptr =
  4038. hx->inter_gb_ptr = NULL;
  4039. if ((err = decode_slice_header(hx, h)) < 0)
  4040. break;
  4041. hx->data_partitioning = 1;
  4042. break;
  4043. case NAL_DPB:
  4044. init_get_bits(&hx->intra_gb, ptr, bit_length);
  4045. hx->intra_gb_ptr = &hx->intra_gb;
  4046. break;
  4047. case NAL_DPC:
  4048. init_get_bits(&hx->inter_gb, ptr, bit_length);
  4049. hx->inter_gb_ptr = &hx->inter_gb;
  4050. av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
  4051. break;
  4052. if (hx->redundant_pic_count == 0 &&
  4053. hx->intra_gb_ptr &&
  4054. hx->data_partitioning &&
  4055. h->cur_pic_ptr && h->context_initialized &&
  4056. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  4057. (avctx->skip_frame < AVDISCARD_BIDIR ||
  4058. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  4059. (avctx->skip_frame < AVDISCARD_NONKEY ||
  4060. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  4061. avctx->skip_frame < AVDISCARD_ALL)
  4062. context_count++;
  4063. break;
  4064. case NAL_SEI:
  4065. init_get_bits(&h->gb, ptr, bit_length);
  4066. ff_h264_decode_sei(h);
  4067. break;
  4068. case NAL_SPS:
  4069. init_get_bits(&h->gb, ptr, bit_length);
  4070. if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)) {
  4071. av_log(h->avctx, AV_LOG_DEBUG,
  4072. "SPS decoding failure, trying again with the complete NAL\n");
  4073. if (h->is_avc)
  4074. av_assert0(next_avc - buf_index + consumed == nalsize);
  4075. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  4076. break;
  4077. init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
  4078. 8*(next_avc - buf_index + consumed - 1));
  4079. ff_h264_decode_seq_parameter_set(h);
  4080. }
  4081. break;
  4082. case NAL_PPS:
  4083. init_get_bits(&h->gb, ptr, bit_length);
  4084. ff_h264_decode_picture_parameter_set(h, bit_length);
  4085. break;
  4086. case NAL_AUD:
  4087. case NAL_END_SEQUENCE:
  4088. case NAL_END_STREAM:
  4089. case NAL_FILLER_DATA:
  4090. case NAL_SPS_EXT:
  4091. case NAL_AUXILIARY_SLICE:
  4092. break;
  4093. case NAL_FF_IGNORE:
  4094. break;
  4095. default:
  4096. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  4097. hx->nal_unit_type, bit_length);
  4098. }
  4099. if (context_count == h->max_contexts) {
  4100. execute_decode_slices(h, context_count);
  4101. context_count = 0;
  4102. }
  4103. if (err < 0)
  4104. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  4105. else if (err == 1) {
  4106. /* Slice could not be decoded in parallel mode, copy down
  4107. * NAL unit stuff to context 0 and restart. Note that
  4108. * rbsp_buffer is not transferred, but since we no longer
  4109. * run in parallel mode this should not be an issue. */
  4110. h->nal_unit_type = hx->nal_unit_type;
  4111. h->nal_ref_idc = hx->nal_ref_idc;
  4112. hx = h;
  4113. goto again;
  4114. }
  4115. }
  4116. }
  4117. if (context_count)
  4118. execute_decode_slices(h, context_count);
  4119. end:
  4120. /* clean up */
  4121. if (h->cur_pic_ptr && h->cur_pic_ptr->owner2 == h &&
  4122. !h->droppable) {
  4123. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  4124. h->picture_structure == PICT_BOTTOM_FIELD);
  4125. }
  4126. return buf_index;
  4127. }
  4128. /**
  4129. * Return the number of bytes consumed for building the current frame.
  4130. */
  4131. static int get_consumed_bytes(int pos, int buf_size)
  4132. {
  4133. if (pos == 0)
  4134. pos = 1; // avoid infinite loops (i doubt that is needed but ...)
  4135. if (pos + 10 > buf_size)
  4136. pos = buf_size; // oops ;)
  4137. return pos;
  4138. }
  4139. static int decode_frame(AVCodecContext *avctx, void *data,
  4140. int *got_frame, AVPacket *avpkt)
  4141. {
  4142. const uint8_t *buf = avpkt->data;
  4143. int buf_size = avpkt->size;
  4144. H264Context *h = avctx->priv_data;
  4145. AVFrame *pict = data;
  4146. int buf_index = 0;
  4147. Picture *out;
  4148. int i, out_idx;
  4149. h->flags = avctx->flags;
  4150. /* end of stream, output what is still in the buffers */
  4151. if (buf_size == 0) {
  4152. out:
  4153. h->cur_pic_ptr = NULL;
  4154. h->first_field = 0;
  4155. // FIXME factorize this with the output code below
  4156. out = h->delayed_pic[0];
  4157. out_idx = 0;
  4158. for (i = 1;
  4159. h->delayed_pic[i] &&
  4160. !h->delayed_pic[i]->f.key_frame &&
  4161. !h->delayed_pic[i]->mmco_reset;
  4162. i++)
  4163. if (h->delayed_pic[i]->poc < out->poc) {
  4164. out = h->delayed_pic[i];
  4165. out_idx = i;
  4166. }
  4167. for (i = out_idx; h->delayed_pic[i]; i++)
  4168. h->delayed_pic[i] = h->delayed_pic[i + 1];
  4169. if (out) {
  4170. out->f.reference &= ~DELAYED_PIC_REF;
  4171. *got_frame = 1;
  4172. *pict = out->f;
  4173. }
  4174. return buf_index;
  4175. }
  4176. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  4177. int cnt= buf[5]&0x1f;
  4178. const uint8_t *p= buf+6;
  4179. while(cnt--){
  4180. int nalsize= AV_RB16(p) + 2;
  4181. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  4182. goto not_extra;
  4183. p += nalsize;
  4184. }
  4185. cnt = *(p++);
  4186. if(!cnt)
  4187. goto not_extra;
  4188. while(cnt--){
  4189. int nalsize= AV_RB16(p) + 2;
  4190. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  4191. goto not_extra;
  4192. p += nalsize;
  4193. }
  4194. return ff_h264_decode_extradata(h, buf, buf_size);
  4195. }
  4196. not_extra:
  4197. buf_index = decode_nal_units(h, buf, buf_size, 0);
  4198. if (buf_index < 0)
  4199. return -1;
  4200. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  4201. av_assert0(buf_index <= buf_size);
  4202. goto out;
  4203. }
  4204. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  4205. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  4206. buf_size >= 4 && !memcmp("Q264", buf, 4))
  4207. return buf_size;
  4208. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  4209. return -1;
  4210. }
  4211. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
  4212. (h->mb_y >= h->mb_height && h->mb_height)) {
  4213. if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
  4214. decode_postinit(h, 1);
  4215. field_end(h, 0);
  4216. /* Wait for second field. */
  4217. *got_frame = 0;
  4218. if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
  4219. *got_frame = 1;
  4220. *pict = h->next_output_pic->f;
  4221. }
  4222. }
  4223. assert(pict->data[0] || !*got_frame);
  4224. ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table, h->visualization_buffer, &h->low_delay,
  4225. h->mb_width, h->mb_height, h->mb_stride, 1);
  4226. return get_consumed_bytes(buf_index, buf_size);
  4227. }
  4228. av_cold void ff_h264_free_context(H264Context *h)
  4229. {
  4230. int i;
  4231. free_tables(h, 1); // FIXME cleanup init stuff perhaps
  4232. for (i = 0; i < MAX_SPS_COUNT; i++)
  4233. av_freep(h->sps_buffers + i);
  4234. for (i = 0; i < MAX_PPS_COUNT; i++)
  4235. av_freep(h->pps_buffers + i);
  4236. }
  4237. static av_cold int h264_decode_end(AVCodecContext *avctx)
  4238. {
  4239. H264Context *h = avctx->priv_data;
  4240. int i;
  4241. ff_h264_remove_all_refs(h);
  4242. ff_h264_free_context(h);
  4243. if (h->DPB && !h->avctx->internal->is_copy) {
  4244. for (i = 0; i < h->picture_count; i++) {
  4245. free_picture(h, &h->DPB[i]);
  4246. }
  4247. }
  4248. av_freep(&h->DPB);
  4249. return 0;
  4250. }
  4251. static const AVProfile profiles[] = {
  4252. { FF_PROFILE_H264_BASELINE, "Baseline" },
  4253. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  4254. { FF_PROFILE_H264_MAIN, "Main" },
  4255. { FF_PROFILE_H264_EXTENDED, "Extended" },
  4256. { FF_PROFILE_H264_HIGH, "High" },
  4257. { FF_PROFILE_H264_HIGH_10, "High 10" },
  4258. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  4259. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  4260. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  4261. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  4262. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  4263. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  4264. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  4265. { FF_PROFILE_UNKNOWN },
  4266. };
  4267. static const AVOption h264_options[] = {
  4268. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  4269. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  4270. {NULL}
  4271. };
  4272. static const AVClass h264_class = {
  4273. .class_name = "H264 Decoder",
  4274. .item_name = av_default_item_name,
  4275. .option = h264_options,
  4276. .version = LIBAVUTIL_VERSION_INT,
  4277. };
  4278. static const AVClass h264_vdpau_class = {
  4279. .class_name = "H264 VDPAU Decoder",
  4280. .item_name = av_default_item_name,
  4281. .option = h264_options,
  4282. .version = LIBAVUTIL_VERSION_INT,
  4283. };
  4284. AVCodec ff_h264_decoder = {
  4285. .name = "h264",
  4286. .type = AVMEDIA_TYPE_VIDEO,
  4287. .id = AV_CODEC_ID_H264,
  4288. .priv_data_size = sizeof(H264Context),
  4289. .init = ff_h264_decode_init,
  4290. .close = h264_decode_end,
  4291. .decode = decode_frame,
  4292. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  4293. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  4294. CODEC_CAP_FRAME_THREADS,
  4295. .flush = flush_dpb,
  4296. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  4297. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  4298. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  4299. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4300. .priv_class = &h264_class,
  4301. };
  4302. #if CONFIG_H264_VDPAU_DECODER
  4303. AVCodec ff_h264_vdpau_decoder = {
  4304. .name = "h264_vdpau",
  4305. .type = AVMEDIA_TYPE_VIDEO,
  4306. .id = AV_CODEC_ID_H264,
  4307. .priv_data_size = sizeof(H264Context),
  4308. .init = ff_h264_decode_init,
  4309. .close = h264_decode_end,
  4310. .decode = decode_frame,
  4311. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  4312. .flush = flush_dpb,
  4313. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  4314. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  4315. AV_PIX_FMT_NONE},
  4316. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4317. .priv_class = &h264_vdpau_class,
  4318. };
  4319. #endif