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.

4125 lines
159KB

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