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.

4628 lines
183KB

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