You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4898 lines
185KB

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