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.

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