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.

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