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.

4152 lines
160KB

  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 AVPixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
  56. AV_PIX_FMT_DXVA2_VLD,
  57. AV_PIX_FMT_VAAPI_VLD,
  58. AV_PIX_FMT_VDA_VLD,
  59. AV_PIX_FMT_YUVJ420P,
  60. AV_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. memcpy(dst, src, i);
  215. si = di = i;
  216. while (si + 2 < length) {
  217. // remove escapes (very rare 1:2^22)
  218. if (src[si + 2] > 3) {
  219. dst[di++] = src[si++];
  220. dst[di++] = src[si++];
  221. } else if (src[si] == 0 && src[si + 1] == 0) {
  222. if (src[si + 2] == 3) { // escape
  223. dst[di++] = 0;
  224. dst[di++] = 0;
  225. si += 3;
  226. continue;
  227. } else // next start code
  228. goto nsc;
  229. }
  230. dst[di++] = src[si++];
  231. }
  232. while (si < length)
  233. dst[di++] = src[si++];
  234. nsc:
  235. memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  236. *dst_length = di;
  237. *consumed = si + 1; // +1 for the header
  238. /* FIXME store exact number of bits in the getbitcontext
  239. * (it is needed for decoding) */
  240. return dst;
  241. }
  242. /**
  243. * Identify the exact end of the bitstream
  244. * @return the length of the trailing, or 0 if damaged
  245. */
  246. static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
  247. {
  248. int v = *src;
  249. int r;
  250. tprintf(h->s.avctx, "rbsp trailing %X\n", v);
  251. for (r = 1; r < 9; r++) {
  252. if (v & 1)
  253. return r;
  254. v >>= 1;
  255. }
  256. return 0;
  257. }
  258. static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
  259. int height, int y_offset, int list)
  260. {
  261. int raw_my = h->mv_cache[list][scan8[n]][1];
  262. int filter_height = (raw_my & 3) ? 2 : 0;
  263. int full_my = (raw_my >> 2) + y_offset;
  264. int top = full_my - filter_height;
  265. int bottom = full_my + filter_height + height;
  266. return FFMAX(abs(top), bottom);
  267. }
  268. static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
  269. int height, int y_offset, int list0,
  270. int list1, int *nrefs)
  271. {
  272. MpegEncContext *const s = &h->s;
  273. int my;
  274. y_offset += 16 * (s->mb_y >> MB_FIELD);
  275. if (list0) {
  276. int ref_n = h->ref_cache[0][scan8[n]];
  277. Picture *ref = &h->ref_list[0][ref_n];
  278. // Error resilience puts the current picture in the ref list.
  279. // Don't try to wait on these as it will cause a deadlock.
  280. // Fields can wait on each other, though.
  281. if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
  282. (ref->f.reference & 3) != s->picture_structure) {
  283. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
  284. if (refs[0][ref_n] < 0)
  285. nrefs[0] += 1;
  286. refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
  287. }
  288. }
  289. if (list1) {
  290. int ref_n = h->ref_cache[1][scan8[n]];
  291. Picture *ref = &h->ref_list[1][ref_n];
  292. if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
  293. (ref->f.reference & 3) != s->picture_structure) {
  294. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
  295. if (refs[1][ref_n] < 0)
  296. nrefs[1] += 1;
  297. refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
  298. }
  299. }
  300. }
  301. /**
  302. * Wait until all reference frames are available for MC operations.
  303. *
  304. * @param h the H264 context
  305. */
  306. static void await_references(H264Context *h)
  307. {
  308. MpegEncContext *const s = &h->s;
  309. const int mb_xy = h->mb_xy;
  310. const int mb_type = s->current_picture.f.mb_type[mb_xy];
  311. int refs[2][48];
  312. int nrefs[2] = { 0 };
  313. int ref, list;
  314. memset(refs, -1, sizeof(refs));
  315. if (IS_16X16(mb_type)) {
  316. get_lowest_part_y(h, refs, 0, 16, 0,
  317. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  318. } else if (IS_16X8(mb_type)) {
  319. get_lowest_part_y(h, refs, 0, 8, 0,
  320. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  321. get_lowest_part_y(h, refs, 8, 8, 8,
  322. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  323. } else if (IS_8X16(mb_type)) {
  324. get_lowest_part_y(h, refs, 0, 16, 0,
  325. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  326. get_lowest_part_y(h, refs, 4, 16, 0,
  327. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  328. } else {
  329. int i;
  330. assert(IS_8X8(mb_type));
  331. for (i = 0; i < 4; i++) {
  332. const int sub_mb_type = h->sub_mb_type[i];
  333. const int n = 4 * i;
  334. int y_offset = (i & 2) << 2;
  335. if (IS_SUB_8X8(sub_mb_type)) {
  336. get_lowest_part_y(h, refs, n, 8, y_offset,
  337. IS_DIR(sub_mb_type, 0, 0),
  338. IS_DIR(sub_mb_type, 0, 1),
  339. nrefs);
  340. } else if (IS_SUB_8X4(sub_mb_type)) {
  341. get_lowest_part_y(h, refs, n, 4, y_offset,
  342. IS_DIR(sub_mb_type, 0, 0),
  343. IS_DIR(sub_mb_type, 0, 1),
  344. nrefs);
  345. get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
  346. IS_DIR(sub_mb_type, 0, 0),
  347. IS_DIR(sub_mb_type, 0, 1),
  348. nrefs);
  349. } else if (IS_SUB_4X8(sub_mb_type)) {
  350. get_lowest_part_y(h, refs, n, 8, y_offset,
  351. IS_DIR(sub_mb_type, 0, 0),
  352. IS_DIR(sub_mb_type, 0, 1),
  353. nrefs);
  354. get_lowest_part_y(h, refs, n + 1, 8, y_offset,
  355. IS_DIR(sub_mb_type, 0, 0),
  356. IS_DIR(sub_mb_type, 0, 1),
  357. nrefs);
  358. } else {
  359. int j;
  360. assert(IS_SUB_4X4(sub_mb_type));
  361. for (j = 0; j < 4; j++) {
  362. int sub_y_offset = y_offset + 2 * (j & 2);
  363. get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
  364. IS_DIR(sub_mb_type, 0, 0),
  365. IS_DIR(sub_mb_type, 0, 1),
  366. nrefs);
  367. }
  368. }
  369. }
  370. }
  371. for (list = h->list_count - 1; list >= 0; list--)
  372. for (ref = 0; ref < 48 && nrefs[list]; ref++) {
  373. int row = refs[list][ref];
  374. if (row >= 0) {
  375. Picture *ref_pic = &h->ref_list[list][ref];
  376. int ref_field = ref_pic->f.reference - 1;
  377. int ref_field_picture = ref_pic->field_picture;
  378. int pic_height = 16 * s->mb_height >> ref_field_picture;
  379. row <<= MB_MBAFF;
  380. nrefs[list]--;
  381. if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
  382. ff_thread_await_progress(&ref_pic->f,
  383. FFMIN((row >> 1) - !(row & 1),
  384. pic_height - 1),
  385. 1);
  386. ff_thread_await_progress(&ref_pic->f,
  387. FFMIN((row >> 1), pic_height - 1),
  388. 0);
  389. } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
  390. ff_thread_await_progress(&ref_pic->f,
  391. FFMIN(row * 2 + ref_field,
  392. pic_height - 1),
  393. 0);
  394. } else if (FIELD_PICTURE) {
  395. ff_thread_await_progress(&ref_pic->f,
  396. FFMIN(row, pic_height - 1),
  397. ref_field);
  398. } else {
  399. ff_thread_await_progress(&ref_pic->f,
  400. FFMIN(row, pic_height - 1),
  401. 0);
  402. }
  403. }
  404. }
  405. }
  406. static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
  407. int n, int square, int height,
  408. int delta, int list,
  409. uint8_t *dest_y, uint8_t *dest_cb,
  410. uint8_t *dest_cr,
  411. int src_x_offset, int src_y_offset,
  412. qpel_mc_func *qpix_op,
  413. h264_chroma_mc_func chroma_op,
  414. int pixel_shift, int chroma_idc)
  415. {
  416. MpegEncContext *const s = &h->s;
  417. const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
  418. int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
  419. const int luma_xy = (mx & 3) + ((my & 3) << 2);
  420. int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
  421. uint8_t *src_y = pic->f.data[0] + offset;
  422. uint8_t *src_cb, *src_cr;
  423. int extra_width = h->emu_edge_width;
  424. int extra_height = h->emu_edge_height;
  425. int emu = 0;
  426. const int full_mx = mx >> 2;
  427. const int full_my = my >> 2;
  428. const int pic_width = 16 * s->mb_width;
  429. const int pic_height = 16 * s->mb_height >> MB_FIELD;
  430. int ysh;
  431. if (mx & 7)
  432. extra_width -= 3;
  433. if (my & 7)
  434. extra_height -= 3;
  435. if (full_mx < 0 - extra_width ||
  436. full_my < 0 - extra_height ||
  437. full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
  438. full_my + 16 /*FIXME*/ > pic_height + extra_height) {
  439. s->dsp.emulated_edge_mc(s->edge_emu_buffer,
  440. src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
  441. h->mb_linesize,
  442. 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
  443. full_my - 2, pic_width, pic_height);
  444. src_y = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  445. emu = 1;
  446. }
  447. qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
  448. if (!square)
  449. qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
  450. if (CONFIG_GRAY && s->flags & CODEC_FLAG_GRAY)
  451. return;
  452. if (chroma_idc == 3 /* yuv444 */) {
  453. src_cb = pic->f.data[1] + offset;
  454. if (emu) {
  455. s->dsp.emulated_edge_mc(s->edge_emu_buffer,
  456. src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
  457. h->mb_linesize,
  458. 16 + 5, 16 + 5 /*FIXME*/,
  459. full_mx - 2, full_my - 2,
  460. pic_width, pic_height);
  461. src_cb = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  462. }
  463. qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
  464. if (!square)
  465. qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
  466. src_cr = pic->f.data[2] + offset;
  467. if (emu) {
  468. s->dsp.emulated_edge_mc(s->edge_emu_buffer,
  469. src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
  470. h->mb_linesize,
  471. 16 + 5, 16 + 5 /*FIXME*/,
  472. full_mx - 2, full_my - 2,
  473. pic_width, pic_height);
  474. src_cr = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  475. }
  476. qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
  477. if (!square)
  478. qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
  479. return;
  480. }
  481. ysh = 3 - (chroma_idc == 2 /* yuv422 */);
  482. if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
  483. // chroma offset when predicting from a field of opposite parity
  484. my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
  485. emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
  486. }
  487. src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
  488. (my >> ysh) * h->mb_uvlinesize;
  489. src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
  490. (my >> ysh) * h->mb_uvlinesize;
  491. if (emu) {
  492. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
  493. 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
  494. pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
  495. src_cb = s->edge_emu_buffer;
  496. }
  497. chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
  498. height >> (chroma_idc == 1 /* yuv420 */),
  499. mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
  500. if (emu) {
  501. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
  502. 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
  503. pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
  504. src_cr = s->edge_emu_buffer;
  505. }
  506. chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
  507. mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
  508. }
  509. static av_always_inline void mc_part_std(H264Context *h, int n, int square,
  510. int height, int delta,
  511. uint8_t *dest_y, uint8_t *dest_cb,
  512. uint8_t *dest_cr,
  513. int x_offset, int y_offset,
  514. qpel_mc_func *qpix_put,
  515. h264_chroma_mc_func chroma_put,
  516. qpel_mc_func *qpix_avg,
  517. h264_chroma_mc_func chroma_avg,
  518. int list0, int list1,
  519. int pixel_shift, int chroma_idc)
  520. {
  521. MpegEncContext *const s = &h->s;
  522. qpel_mc_func *qpix_op = qpix_put;
  523. h264_chroma_mc_func chroma_op = chroma_put;
  524. dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  525. if (chroma_idc == 3 /* yuv444 */) {
  526. dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  527. dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  528. } else if (chroma_idc == 2 /* yuv422 */) {
  529. dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  530. dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  531. } else { /* yuv420 */
  532. dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  533. dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  534. }
  535. x_offset += 8 * s->mb_x;
  536. y_offset += 8 * (s->mb_y >> MB_FIELD);
  537. if (list0) {
  538. Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
  539. mc_dir_part(h, ref, n, square, height, delta, 0,
  540. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  541. qpix_op, chroma_op, pixel_shift, chroma_idc);
  542. qpix_op = qpix_avg;
  543. chroma_op = chroma_avg;
  544. }
  545. if (list1) {
  546. Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
  547. mc_dir_part(h, ref, n, square, height, delta, 1,
  548. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  549. qpix_op, chroma_op, pixel_shift, chroma_idc);
  550. }
  551. }
  552. static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
  553. int height, int delta,
  554. uint8_t *dest_y, uint8_t *dest_cb,
  555. uint8_t *dest_cr,
  556. int x_offset, int y_offset,
  557. qpel_mc_func *qpix_put,
  558. h264_chroma_mc_func chroma_put,
  559. h264_weight_func luma_weight_op,
  560. h264_weight_func chroma_weight_op,
  561. h264_biweight_func luma_weight_avg,
  562. h264_biweight_func chroma_weight_avg,
  563. int list0, int list1,
  564. int pixel_shift, int chroma_idc)
  565. {
  566. MpegEncContext *const s = &h->s;
  567. int chroma_height;
  568. dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  569. if (chroma_idc == 3 /* yuv444 */) {
  570. chroma_height = height;
  571. chroma_weight_avg = luma_weight_avg;
  572. chroma_weight_op = luma_weight_op;
  573. dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  574. dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  575. } else if (chroma_idc == 2 /* yuv422 */) {
  576. chroma_height = height;
  577. dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  578. dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  579. } else { /* yuv420 */
  580. chroma_height = height >> 1;
  581. dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  582. dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  583. }
  584. x_offset += 8 * s->mb_x;
  585. y_offset += 8 * (s->mb_y >> MB_FIELD);
  586. if (list0 && list1) {
  587. /* don't optimize for luma-only case, since B-frames usually
  588. * use implicit weights => chroma too. */
  589. uint8_t *tmp_cb = h->bipred_scratchpad;
  590. uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
  591. uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
  592. int refn0 = h->ref_cache[0][scan8[n]];
  593. int refn1 = h->ref_cache[1][scan8[n]];
  594. mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
  595. dest_y, dest_cb, dest_cr,
  596. x_offset, y_offset, qpix_put, chroma_put,
  597. pixel_shift, chroma_idc);
  598. mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
  599. tmp_y, tmp_cb, tmp_cr,
  600. x_offset, y_offset, qpix_put, chroma_put,
  601. pixel_shift, chroma_idc);
  602. if (h->use_weight == 2) {
  603. int weight0 = h->implicit_weight[refn0][refn1][s->mb_y & 1];
  604. int weight1 = 64 - weight0;
  605. luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
  606. height, 5, weight0, weight1, 0);
  607. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
  608. chroma_height, 5, weight0, weight1, 0);
  609. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
  610. chroma_height, 5, weight0, weight1, 0);
  611. } else {
  612. luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
  613. h->luma_log2_weight_denom,
  614. h->luma_weight[refn0][0][0],
  615. h->luma_weight[refn1][1][0],
  616. h->luma_weight[refn0][0][1] +
  617. h->luma_weight[refn1][1][1]);
  618. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
  619. h->chroma_log2_weight_denom,
  620. h->chroma_weight[refn0][0][0][0],
  621. h->chroma_weight[refn1][1][0][0],
  622. h->chroma_weight[refn0][0][0][1] +
  623. h->chroma_weight[refn1][1][0][1]);
  624. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
  625. h->chroma_log2_weight_denom,
  626. h->chroma_weight[refn0][0][1][0],
  627. h->chroma_weight[refn1][1][1][0],
  628. h->chroma_weight[refn0][0][1][1] +
  629. h->chroma_weight[refn1][1][1][1]);
  630. }
  631. } else {
  632. int list = list1 ? 1 : 0;
  633. int refn = h->ref_cache[list][scan8[n]];
  634. Picture *ref = &h->ref_list[list][refn];
  635. mc_dir_part(h, ref, n, square, height, delta, list,
  636. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  637. qpix_put, chroma_put, pixel_shift, chroma_idc);
  638. luma_weight_op(dest_y, h->mb_linesize, height,
  639. h->luma_log2_weight_denom,
  640. h->luma_weight[refn][list][0],
  641. h->luma_weight[refn][list][1]);
  642. if (h->use_weight_chroma) {
  643. chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
  644. h->chroma_log2_weight_denom,
  645. h->chroma_weight[refn][list][0][0],
  646. h->chroma_weight[refn][list][0][1]);
  647. chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
  648. h->chroma_log2_weight_denom,
  649. h->chroma_weight[refn][list][1][0],
  650. h->chroma_weight[refn][list][1][1]);
  651. }
  652. }
  653. }
  654. static av_always_inline void prefetch_motion(H264Context *h, int list,
  655. int pixel_shift, int chroma_idc)
  656. {
  657. /* fetch pixels for estimated mv 4 macroblocks ahead
  658. * optimized for 64byte cache lines */
  659. MpegEncContext *const s = &h->s;
  660. const int refn = h->ref_cache[list][scan8[0]];
  661. if (refn >= 0) {
  662. const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * s->mb_x + 8;
  663. const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * s->mb_y;
  664. uint8_t **src = h->ref_list[list][refn].f.data;
  665. int off = (mx << pixel_shift) +
  666. (my + (s->mb_x & 3) * 4) * h->mb_linesize +
  667. (64 << pixel_shift);
  668. s->dsp.prefetch(src[0] + off, s->linesize, 4);
  669. if (chroma_idc == 3 /* yuv444 */) {
  670. s->dsp.prefetch(src[1] + off, s->linesize, 4);
  671. s->dsp.prefetch(src[2] + off, s->linesize, 4);
  672. } else {
  673. off = ((mx >> 1) << pixel_shift) +
  674. ((my >> 1) + (s->mb_x & 7)) * s->uvlinesize +
  675. (64 << pixel_shift);
  676. s->dsp.prefetch(src[1] + off, src[2] - src[1], 2);
  677. }
  678. }
  679. }
  680. static void free_tables(H264Context *h, int free_rbsp)
  681. {
  682. int i;
  683. H264Context *hx;
  684. av_freep(&h->intra4x4_pred_mode);
  685. av_freep(&h->chroma_pred_mode_table);
  686. av_freep(&h->cbp_table);
  687. av_freep(&h->mvd_table[0]);
  688. av_freep(&h->mvd_table[1]);
  689. av_freep(&h->direct_table);
  690. av_freep(&h->non_zero_count);
  691. av_freep(&h->slice_table_base);
  692. h->slice_table = NULL;
  693. av_freep(&h->list_counts);
  694. av_freep(&h->mb2b_xy);
  695. av_freep(&h->mb2br_xy);
  696. for (i = 0; i < MAX_THREADS; i++) {
  697. hx = h->thread_context[i];
  698. if (!hx)
  699. continue;
  700. av_freep(&hx->top_borders[1]);
  701. av_freep(&hx->top_borders[0]);
  702. av_freep(&hx->bipred_scratchpad);
  703. if (free_rbsp) {
  704. av_freep(&hx->rbsp_buffer[1]);
  705. av_freep(&hx->rbsp_buffer[0]);
  706. hx->rbsp_buffer_size[0] = 0;
  707. hx->rbsp_buffer_size[1] = 0;
  708. }
  709. if (i)
  710. av_freep(&h->thread_context[i]);
  711. }
  712. }
  713. static void init_dequant8_coeff_table(H264Context *h)
  714. {
  715. int i, j, q, x;
  716. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  717. for (i = 0; i < 6; i++) {
  718. h->dequant8_coeff[i] = h->dequant8_buffer[i];
  719. for (j = 0; j < i; j++)
  720. if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
  721. 64 * sizeof(uint8_t))) {
  722. h->dequant8_coeff[i] = h->dequant8_buffer[j];
  723. break;
  724. }
  725. if (j < i)
  726. continue;
  727. for (q = 0; q < max_qp + 1; q++) {
  728. int shift = div6[q];
  729. int idx = rem6[q];
  730. for (x = 0; x < 64; x++)
  731. h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
  732. ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
  733. h->pps.scaling_matrix8[i][x]) << shift;
  734. }
  735. }
  736. }
  737. static void init_dequant4_coeff_table(H264Context *h)
  738. {
  739. int i, j, q, x;
  740. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  741. for (i = 0; i < 6; i++) {
  742. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  743. for (j = 0; j < i; j++)
  744. if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
  745. 16 * sizeof(uint8_t))) {
  746. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  747. break;
  748. }
  749. if (j < i)
  750. continue;
  751. for (q = 0; q < max_qp + 1; q++) {
  752. int shift = div6[q] + 2;
  753. int idx = rem6[q];
  754. for (x = 0; x < 16; x++)
  755. h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
  756. ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
  757. h->pps.scaling_matrix4[i][x]) << shift;
  758. }
  759. }
  760. }
  761. static void init_dequant_tables(H264Context *h)
  762. {
  763. int i, x;
  764. init_dequant4_coeff_table(h);
  765. if (h->pps.transform_8x8_mode)
  766. init_dequant8_coeff_table(h);
  767. if (h->sps.transform_bypass) {
  768. for (i = 0; i < 6; i++)
  769. for (x = 0; x < 16; x++)
  770. h->dequant4_coeff[i][0][x] = 1 << 6;
  771. if (h->pps.transform_8x8_mode)
  772. for (i = 0; i < 6; i++)
  773. for (x = 0; x < 64; x++)
  774. h->dequant8_coeff[i][0][x] = 1 << 6;
  775. }
  776. }
  777. int ff_h264_alloc_tables(H264Context *h)
  778. {
  779. MpegEncContext *const s = &h->s;
  780. const int big_mb_num = s->mb_stride * (s->mb_height + 1);
  781. const int row_mb_num = s->mb_stride * 2 * s->avctx->thread_count;
  782. int x, y;
  783. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode,
  784. row_mb_num * 8 * sizeof(uint8_t), fail)
  785. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count,
  786. big_mb_num * 48 * sizeof(uint8_t), fail)
  787. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base,
  788. (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base), fail)
  789. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table,
  790. big_mb_num * sizeof(uint16_t), fail)
  791. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table,
  792. big_mb_num * sizeof(uint8_t), fail)
  793. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0],
  794. 16 * row_mb_num * sizeof(uint8_t), fail);
  795. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1],
  796. 16 * row_mb_num * sizeof(uint8_t), fail);
  797. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table,
  798. 4 * big_mb_num * sizeof(uint8_t), fail);
  799. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts,
  800. big_mb_num * sizeof(uint8_t), fail)
  801. memset(h->slice_table_base, -1,
  802. (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base));
  803. h->slice_table = h->slice_table_base + s->mb_stride * 2 + 1;
  804. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy,
  805. big_mb_num * sizeof(uint32_t), fail);
  806. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy,
  807. big_mb_num * sizeof(uint32_t), fail);
  808. for (y = 0; y < s->mb_height; y++)
  809. for (x = 0; x < s->mb_width; x++) {
  810. const int mb_xy = x + y * s->mb_stride;
  811. const int b_xy = 4 * x + 4 * y * h->b_stride;
  812. h->mb2b_xy[mb_xy] = b_xy;
  813. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * s->mb_stride)));
  814. }
  815. if (!h->dequant4_coeff[0])
  816. init_dequant_tables(h);
  817. return 0;
  818. fail:
  819. free_tables(h, 1);
  820. return -1;
  821. }
  822. /**
  823. * Mimic alloc_tables(), but for every context thread.
  824. */
  825. static void clone_tables(H264Context *dst, H264Context *src, int i)
  826. {
  827. MpegEncContext *const s = &src->s;
  828. dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * s->mb_stride;
  829. dst->non_zero_count = src->non_zero_count;
  830. dst->slice_table = src->slice_table;
  831. dst->cbp_table = src->cbp_table;
  832. dst->mb2b_xy = src->mb2b_xy;
  833. dst->mb2br_xy = src->mb2br_xy;
  834. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  835. dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * s->mb_stride;
  836. dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * s->mb_stride;
  837. dst->direct_table = src->direct_table;
  838. dst->list_counts = src->list_counts;
  839. dst->bipred_scratchpad = NULL;
  840. ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma,
  841. src->sps.chroma_format_idc);
  842. }
  843. /**
  844. * Init context
  845. * Allocate buffers which are not shared amongst multiple threads.
  846. */
  847. static int context_init(H264Context *h)
  848. {
  849. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0],
  850. h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  851. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1],
  852. h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  853. h->ref_cache[0][scan8[5] + 1] =
  854. h->ref_cache[0][scan8[7] + 1] =
  855. h->ref_cache[0][scan8[13] + 1] =
  856. h->ref_cache[1][scan8[5] + 1] =
  857. h->ref_cache[1][scan8[7] + 1] =
  858. h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  859. return 0;
  860. fail:
  861. return -1; // free_tables will clean up for us
  862. }
  863. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
  864. static av_cold void common_init(H264Context *h)
  865. {
  866. MpegEncContext *const s = &h->s;
  867. s->width = s->avctx->width;
  868. s->height = s->avctx->height;
  869. s->codec_id = s->avctx->codec->id;
  870. ff_h264dsp_init(&h->h264dsp, 8, 1);
  871. ff_h264_pred_init(&h->hpc, s->codec_id, 8, 1);
  872. h->dequant_coeff_pps = -1;
  873. s->unrestricted_mv = 1;
  874. /* needed so that IDCT permutation is known early */
  875. ff_dsputil_init(&s->dsp, s->avctx);
  876. memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
  877. memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
  878. }
  879. int ff_h264_decode_extradata(H264Context *h)
  880. {
  881. AVCodecContext *avctx = h->s.avctx;
  882. if (avctx->extradata[0] == 1) {
  883. int i, cnt, nalsize;
  884. unsigned char *p = avctx->extradata;
  885. h->is_avc = 1;
  886. if (avctx->extradata_size < 7) {
  887. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  888. return -1;
  889. }
  890. /* sps and pps in the avcC always have length coded with 2 bytes,
  891. * so put a fake nal_length_size = 2 while parsing them */
  892. h->nal_length_size = 2;
  893. // Decode sps from avcC
  894. cnt = *(p + 5) & 0x1f; // Number of sps
  895. p += 6;
  896. for (i = 0; i < cnt; i++) {
  897. nalsize = AV_RB16(p) + 2;
  898. if (p - avctx->extradata + nalsize > avctx->extradata_size)
  899. return -1;
  900. if (decode_nal_units(h, p, nalsize) < 0) {
  901. av_log(avctx, AV_LOG_ERROR,
  902. "Decoding sps %d from avcC failed\n", i);
  903. return -1;
  904. }
  905. p += nalsize;
  906. }
  907. // Decode pps from avcC
  908. cnt = *(p++); // Number of pps
  909. for (i = 0; i < cnt; i++) {
  910. nalsize = AV_RB16(p) + 2;
  911. if (p - avctx->extradata + nalsize > avctx->extradata_size)
  912. return -1;
  913. if (decode_nal_units(h, p, nalsize) < 0) {
  914. av_log(avctx, AV_LOG_ERROR,
  915. "Decoding pps %d from avcC failed\n", i);
  916. return -1;
  917. }
  918. p += nalsize;
  919. }
  920. // Now store right nal length size, that will be used to parse all other nals
  921. h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
  922. } else {
  923. h->is_avc = 0;
  924. if (decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
  925. return -1;
  926. }
  927. return 0;
  928. }
  929. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  930. {
  931. H264Context *h = avctx->priv_data;
  932. MpegEncContext *const s = &h->s;
  933. int i;
  934. ff_MPV_decode_defaults(s);
  935. s->avctx = avctx;
  936. common_init(h);
  937. s->out_format = FMT_H264;
  938. s->workaround_bugs = avctx->workaround_bugs;
  939. /* set defaults */
  940. // s->decode_mb = ff_h263_decode_mb;
  941. s->quarter_sample = 1;
  942. if (!avctx->has_b_frames)
  943. s->low_delay = 1;
  944. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  945. ff_h264_decode_init_vlc();
  946. h->pixel_shift = 0;
  947. h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
  948. h->thread_context[0] = h;
  949. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  950. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  951. h->last_pocs[i] = INT_MIN;
  952. h->prev_poc_msb = 1 << 16;
  953. h->x264_build = -1;
  954. ff_h264_reset_sei(h);
  955. if (avctx->codec_id == AV_CODEC_ID_H264) {
  956. if (avctx->ticks_per_frame == 1)
  957. s->avctx->time_base.den *= 2;
  958. avctx->ticks_per_frame = 2;
  959. }
  960. if (avctx->extradata_size > 0 && avctx->extradata &&
  961. ff_h264_decode_extradata(h))
  962. return -1;
  963. if (h->sps.bitstream_restriction_flag &&
  964. s->avctx->has_b_frames < h->sps.num_reorder_frames) {
  965. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  966. s->low_delay = 0;
  967. }
  968. return 0;
  969. }
  970. #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
  971. static void copy_picture_range(Picture **to, Picture **from, int count,
  972. MpegEncContext *new_base,
  973. MpegEncContext *old_base)
  974. {
  975. int i;
  976. for (i = 0; i < count; i++) {
  977. assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
  978. IN_RANGE(from[i], old_base->picture,
  979. sizeof(Picture) * old_base->picture_count) ||
  980. !from[i]));
  981. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  982. }
  983. }
  984. static void copy_parameter_set(void **to, void **from, int count, int size)
  985. {
  986. int i;
  987. for (i = 0; i < count; i++) {
  988. if (to[i] && !from[i])
  989. av_freep(&to[i]);
  990. else if (from[i] && !to[i])
  991. to[i] = av_malloc(size);
  992. if (from[i])
  993. memcpy(to[i], from[i], size);
  994. }
  995. }
  996. static int decode_init_thread_copy(AVCodecContext *avctx)
  997. {
  998. H264Context *h = avctx->priv_data;
  999. if (!avctx->internal->is_copy)
  1000. return 0;
  1001. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1002. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1003. return 0;
  1004. }
  1005. #define copy_fields(to, from, start_field, end_field) \
  1006. memcpy(&to->start_field, &from->start_field, \
  1007. (char *)&to->end_field - (char *)&to->start_field)
  1008. static int decode_update_thread_context(AVCodecContext *dst,
  1009. const AVCodecContext *src)
  1010. {
  1011. H264Context *h = dst->priv_data, *h1 = src->priv_data;
  1012. MpegEncContext *const s = &h->s, *const s1 = &h1->s;
  1013. int inited = s->context_initialized, err;
  1014. int i;
  1015. if (dst == src || !s1->context_initialized)
  1016. return 0;
  1017. err = ff_mpeg_update_thread_context(dst, src);
  1018. if (err)
  1019. return err;
  1020. // FIXME handle width/height changing
  1021. if (!inited) {
  1022. for (i = 0; i < MAX_SPS_COUNT; i++)
  1023. av_freep(h->sps_buffers + i);
  1024. for (i = 0; i < MAX_PPS_COUNT; i++)
  1025. av_freep(h->pps_buffers + i);
  1026. // copy all fields after MpegEnc
  1027. memcpy(&h->s + 1, &h1->s + 1,
  1028. sizeof(H264Context) - sizeof(MpegEncContext));
  1029. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1030. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1031. if (ff_h264_alloc_tables(h) < 0) {
  1032. av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
  1033. return AVERROR(ENOMEM);
  1034. }
  1035. context_init(h);
  1036. for (i = 0; i < 2; i++) {
  1037. h->rbsp_buffer[i] = NULL;
  1038. h->rbsp_buffer_size[i] = 0;
  1039. }
  1040. h->bipred_scratchpad = NULL;
  1041. h->thread_context[0] = h;
  1042. s->dsp.clear_blocks(h->mb);
  1043. s->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
  1044. }
  1045. /* frame_start may not be called for the next thread (if it's decoding
  1046. * a bottom field) so this has to be allocated here */
  1047. if (!h->bipred_scratchpad)
  1048. h->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
  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]->bipred_scratchpad)
  1122. h->thread_context[i]->bipred_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 != AV_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. field_poc[0] =
  1917. field_poc[1] = h->poc_msb + h->poc_lsb;
  1918. if (s->picture_structure == PICT_FRAME)
  1919. field_poc[1] += h->delta_poc_bottom;
  1920. } else if (h->sps.poc_type == 1) {
  1921. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  1922. int i;
  1923. if (h->sps.poc_cycle_length != 0)
  1924. abs_frame_num = h->frame_num_offset + h->frame_num;
  1925. else
  1926. abs_frame_num = 0;
  1927. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  1928. abs_frame_num--;
  1929. expected_delta_per_poc_cycle = 0;
  1930. for (i = 0; i < h->sps.poc_cycle_length; i++)
  1931. // FIXME integrate during sps parse
  1932. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  1933. if (abs_frame_num > 0) {
  1934. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  1935. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  1936. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1937. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  1938. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  1939. } else
  1940. expectedpoc = 0;
  1941. if (h->nal_ref_idc == 0)
  1942. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1943. field_poc[0] = expectedpoc + h->delta_poc[0];
  1944. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1945. if (s->picture_structure == PICT_FRAME)
  1946. field_poc[1] += h->delta_poc[1];
  1947. } else {
  1948. int poc = 2 * (h->frame_num_offset + h->frame_num);
  1949. if (!h->nal_ref_idc)
  1950. poc--;
  1951. field_poc[0] = poc;
  1952. field_poc[1] = poc;
  1953. }
  1954. if (s->picture_structure != PICT_BOTTOM_FIELD)
  1955. s->current_picture_ptr->field_poc[0] = field_poc[0];
  1956. if (s->picture_structure != PICT_TOP_FIELD)
  1957. s->current_picture_ptr->field_poc[1] = field_poc[1];
  1958. cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
  1959. return 0;
  1960. }
  1961. /**
  1962. * initialize scan tables
  1963. */
  1964. static void init_scan_tables(H264Context *h)
  1965. {
  1966. int i;
  1967. for (i = 0; i < 16; i++) {
  1968. #define T(x) (x >> 2) | ((x << 2) & 0xF)
  1969. h->zigzag_scan[i] = T(zigzag_scan[i]);
  1970. h->field_scan[i] = T(field_scan[i]);
  1971. #undef T
  1972. }
  1973. for (i = 0; i < 64; i++) {
  1974. #define T(x) (x >> 3) | ((x & 7) << 3)
  1975. h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
  1976. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  1977. h->field_scan8x8[i] = T(field_scan8x8[i]);
  1978. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  1979. #undef T
  1980. }
  1981. if (h->sps.transform_bypass) { // FIXME same ugly
  1982. h->zigzag_scan_q0 = zigzag_scan;
  1983. h->zigzag_scan8x8_q0 = ff_zigzag_direct;
  1984. h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
  1985. h->field_scan_q0 = field_scan;
  1986. h->field_scan8x8_q0 = field_scan8x8;
  1987. h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
  1988. } else {
  1989. h->zigzag_scan_q0 = h->zigzag_scan;
  1990. h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
  1991. h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
  1992. h->field_scan_q0 = h->field_scan;
  1993. h->field_scan8x8_q0 = h->field_scan8x8;
  1994. h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
  1995. }
  1996. }
  1997. static int field_end(H264Context *h, int in_setup)
  1998. {
  1999. MpegEncContext *const s = &h->s;
  2000. AVCodecContext *const avctx = s->avctx;
  2001. int err = 0;
  2002. s->mb_y = 0;
  2003. if (!in_setup && !s->dropable)
  2004. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
  2005. s->picture_structure == PICT_BOTTOM_FIELD);
  2006. if (CONFIG_H264_VDPAU_DECODER &&
  2007. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2008. ff_vdpau_h264_set_reference_frames(s);
  2009. if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
  2010. if (!s->dropable) {
  2011. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2012. h->prev_poc_msb = h->poc_msb;
  2013. h->prev_poc_lsb = h->poc_lsb;
  2014. }
  2015. h->prev_frame_num_offset = h->frame_num_offset;
  2016. h->prev_frame_num = h->frame_num;
  2017. h->outputed_poc = h->next_outputed_poc;
  2018. }
  2019. if (avctx->hwaccel) {
  2020. if (avctx->hwaccel->end_frame(avctx) < 0)
  2021. av_log(avctx, AV_LOG_ERROR,
  2022. "hardware accelerator failed to decode picture\n");
  2023. }
  2024. if (CONFIG_H264_VDPAU_DECODER &&
  2025. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2026. ff_vdpau_h264_picture_complete(s);
  2027. /*
  2028. * FIXME: Error handling code does not seem to support interlaced
  2029. * when slices span multiple rows
  2030. * The ff_er_add_slice calls don't work right for bottom
  2031. * fields; they cause massive erroneous error concealing
  2032. * Error marking covers both fields (top and bottom).
  2033. * This causes a mismatched s->error_count
  2034. * and a bad error table. Further, the error count goes to
  2035. * INT_MAX when called for bottom field, because mb_y is
  2036. * past end by one (callers fault) and resync_mb_y != 0
  2037. * causes problems for the first MB line, too.
  2038. */
  2039. if (!FIELD_PICTURE)
  2040. ff_er_frame_end(s);
  2041. ff_MPV_frame_end(s);
  2042. h->current_slice = 0;
  2043. return err;
  2044. }
  2045. /**
  2046. * Replicate H264 "master" context to thread contexts.
  2047. */
  2048. static void clone_slice(H264Context *dst, H264Context *src)
  2049. {
  2050. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  2051. dst->s.current_picture_ptr = src->s.current_picture_ptr;
  2052. dst->s.current_picture = src->s.current_picture;
  2053. dst->s.linesize = src->s.linesize;
  2054. dst->s.uvlinesize = src->s.uvlinesize;
  2055. dst->s.first_field = src->s.first_field;
  2056. dst->prev_poc_msb = src->prev_poc_msb;
  2057. dst->prev_poc_lsb = src->prev_poc_lsb;
  2058. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  2059. dst->prev_frame_num = src->prev_frame_num;
  2060. dst->short_ref_count = src->short_ref_count;
  2061. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  2062. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  2063. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  2064. memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
  2065. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  2066. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  2067. }
  2068. /**
  2069. * Compute profile from profile_idc and constraint_set?_flags.
  2070. *
  2071. * @param sps SPS
  2072. *
  2073. * @return profile as defined by FF_PROFILE_H264_*
  2074. */
  2075. int ff_h264_get_profile(SPS *sps)
  2076. {
  2077. int profile = sps->profile_idc;
  2078. switch (sps->profile_idc) {
  2079. case FF_PROFILE_H264_BASELINE:
  2080. // constraint_set1_flag set to 1
  2081. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  2082. break;
  2083. case FF_PROFILE_H264_HIGH_10:
  2084. case FF_PROFILE_H264_HIGH_422:
  2085. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  2086. // constraint_set3_flag set to 1
  2087. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  2088. break;
  2089. }
  2090. return profile;
  2091. }
  2092. /**
  2093. * Decode a slice header.
  2094. * This will also call ff_MPV_common_init() and frame_start() as needed.
  2095. *
  2096. * @param h h264context
  2097. * @param h0 h264 master context (differs from 'h' when doing sliced based
  2098. * parallel decoding)
  2099. *
  2100. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  2101. */
  2102. static int decode_slice_header(H264Context *h, H264Context *h0)
  2103. {
  2104. MpegEncContext *const s = &h->s;
  2105. MpegEncContext *const s0 = &h0->s;
  2106. unsigned int first_mb_in_slice;
  2107. unsigned int pps_id;
  2108. int num_ref_idx_active_override_flag, max_refs;
  2109. unsigned int slice_type, tmp, i, j;
  2110. int default_ref_list_done = 0;
  2111. int last_pic_structure, last_pic_dropable;
  2112. /* FIXME: 2tap qpel isn't implemented for high bit depth. */
  2113. if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
  2114. !h->nal_ref_idc && !h->pixel_shift) {
  2115. s->me.qpel_put = s->dsp.put_2tap_qpel_pixels_tab;
  2116. s->me.qpel_avg = s->dsp.avg_2tap_qpel_pixels_tab;
  2117. } else {
  2118. s->me.qpel_put = s->dsp.put_h264_qpel_pixels_tab;
  2119. s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
  2120. }
  2121. first_mb_in_slice = get_ue_golomb(&s->gb);
  2122. if (first_mb_in_slice == 0) { // FIXME better field boundary detection
  2123. if (h0->current_slice && FIELD_PICTURE) {
  2124. field_end(h, 1);
  2125. }
  2126. h0->current_slice = 0;
  2127. if (!s0->first_field) {
  2128. if (s->current_picture_ptr && !s->dropable &&
  2129. s->current_picture_ptr->owner2 == s) {
  2130. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
  2131. s->picture_structure == PICT_BOTTOM_FIELD);
  2132. }
  2133. s->current_picture_ptr = NULL;
  2134. }
  2135. }
  2136. slice_type = get_ue_golomb_31(&s->gb);
  2137. if (slice_type > 9) {
  2138. av_log(h->s.avctx, AV_LOG_ERROR,
  2139. "slice type too large (%d) at %d %d\n",
  2140. h->slice_type, s->mb_x, s->mb_y);
  2141. return -1;
  2142. }
  2143. if (slice_type > 4) {
  2144. slice_type -= 5;
  2145. h->slice_type_fixed = 1;
  2146. } else
  2147. h->slice_type_fixed = 0;
  2148. slice_type = golomb_to_pict_type[slice_type];
  2149. if (slice_type == AV_PICTURE_TYPE_I ||
  2150. (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
  2151. default_ref_list_done = 1;
  2152. }
  2153. h->slice_type = slice_type;
  2154. h->slice_type_nos = slice_type & 3;
  2155. // to make a few old functions happy, it's wrong though
  2156. s->pict_type = h->slice_type;
  2157. pps_id = get_ue_golomb(&s->gb);
  2158. if (pps_id >= MAX_PPS_COUNT) {
  2159. av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
  2160. return -1;
  2161. }
  2162. if (!h0->pps_buffers[pps_id]) {
  2163. av_log(h->s.avctx, AV_LOG_ERROR,
  2164. "non-existing PPS %u referenced\n",
  2165. pps_id);
  2166. return -1;
  2167. }
  2168. h->pps = *h0->pps_buffers[pps_id];
  2169. if (!h0->sps_buffers[h->pps.sps_id]) {
  2170. av_log(h->s.avctx, AV_LOG_ERROR,
  2171. "non-existing SPS %u referenced\n",
  2172. h->pps.sps_id);
  2173. return -1;
  2174. }
  2175. h->sps = *h0->sps_buffers[h->pps.sps_id];
  2176. s->avctx->profile = ff_h264_get_profile(&h->sps);
  2177. s->avctx->level = h->sps.level_idc;
  2178. s->avctx->refs = h->sps.ref_frame_count;
  2179. s->mb_width = h->sps.mb_width;
  2180. s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  2181. h->b_stride = s->mb_width * 4;
  2182. s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  2183. s->width = 16 * s->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
  2184. if (h->sps.frame_mbs_only_flag)
  2185. s->height = 16 * s->mb_height - (1 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
  2186. else
  2187. s->height = 16 * s->mb_height - (2 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
  2188. if (FFALIGN(s->avctx->width, 16) == s->width &&
  2189. FFALIGN(s->avctx->height, 16) == s->height) {
  2190. s->width = s->avctx->width;
  2191. s->height = s->avctx->height;
  2192. }
  2193. if (s->context_initialized &&
  2194. (s->width != s->avctx->width || s->height != s->avctx->height ||
  2195. av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
  2196. if (h != h0 || (HAVE_THREADS && h->s.avctx->active_thread_type & FF_THREAD_FRAME)) {
  2197. av_log_missing_feature(s->avctx,
  2198. "Width/height changing with threads", 0);
  2199. return AVERROR_PATCHWELCOME; // width / height changed during parallelized decoding
  2200. }
  2201. free_tables(h, 0);
  2202. flush_dpb(s->avctx);
  2203. ff_MPV_common_end(s);
  2204. }
  2205. if (!s->context_initialized) {
  2206. if (h != h0) {
  2207. av_log(h->s.avctx, AV_LOG_ERROR,
  2208. "Cannot (re-)initialize context during parallel decoding.\n");
  2209. return -1;
  2210. }
  2211. avcodec_set_dimensions(s->avctx, s->width, s->height);
  2212. s->avctx->sample_aspect_ratio = h->sps.sar;
  2213. av_assert0(s->avctx->sample_aspect_ratio.den);
  2214. if (h->sps.video_signal_type_present_flag) {
  2215. s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
  2216. : AVCOL_RANGE_MPEG;
  2217. if (h->sps.colour_description_present_flag) {
  2218. s->avctx->color_primaries = h->sps.color_primaries;
  2219. s->avctx->color_trc = h->sps.color_trc;
  2220. s->avctx->colorspace = h->sps.colorspace;
  2221. }
  2222. }
  2223. if (h->sps.timing_info_present_flag) {
  2224. int64_t den = h->sps.time_scale;
  2225. if (h->x264_build < 44U)
  2226. den *= 2;
  2227. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  2228. h->sps.num_units_in_tick, den, 1 << 30);
  2229. }
  2230. switch (h->sps.bit_depth_luma) {
  2231. case 9:
  2232. if (CHROMA444) {
  2233. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2234. s->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
  2235. } else
  2236. s->avctx->pix_fmt = AV_PIX_FMT_YUV444P9;
  2237. } else if (CHROMA422)
  2238. s->avctx->pix_fmt = AV_PIX_FMT_YUV422P9;
  2239. else
  2240. s->avctx->pix_fmt = AV_PIX_FMT_YUV420P9;
  2241. break;
  2242. case 10:
  2243. if (CHROMA444) {
  2244. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2245. s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
  2246. } else
  2247. s->avctx->pix_fmt = AV_PIX_FMT_YUV444P10;
  2248. } else if (CHROMA422)
  2249. s->avctx->pix_fmt = AV_PIX_FMT_YUV422P10;
  2250. else
  2251. s->avctx->pix_fmt = AV_PIX_FMT_YUV420P10;
  2252. break;
  2253. case 8:
  2254. if (CHROMA444) {
  2255. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2256. s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
  2257. } else
  2258. s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
  2259. : AV_PIX_FMT_YUV444P;
  2260. } else if (CHROMA422) {
  2261. s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
  2262. : AV_PIX_FMT_YUV422P;
  2263. } else {
  2264. s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
  2265. s->avctx->codec->pix_fmts ?
  2266. s->avctx->codec->pix_fmts :
  2267. s->avctx->color_range == AVCOL_RANGE_JPEG ?
  2268. hwaccel_pixfmt_list_h264_jpeg_420 :
  2269. ff_hwaccel_pixfmt_list_420);
  2270. }
  2271. break;
  2272. default:
  2273. av_log(s->avctx, AV_LOG_ERROR,
  2274. "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
  2275. return AVERROR_INVALIDDATA;
  2276. }
  2277. s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id,
  2278. s->avctx->pix_fmt);
  2279. if (ff_MPV_common_init(s) < 0) {
  2280. av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
  2281. return -1;
  2282. }
  2283. s->first_field = 0;
  2284. h->prev_interlaced_frame = 1;
  2285. init_scan_tables(h);
  2286. if (ff_h264_alloc_tables(h) < 0) {
  2287. av_log(h->s.avctx, AV_LOG_ERROR,
  2288. "Could not allocate memory for h264\n");
  2289. return AVERROR(ENOMEM);
  2290. }
  2291. if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
  2292. if (context_init(h) < 0) {
  2293. av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2294. return -1;
  2295. }
  2296. } else {
  2297. for (i = 1; i < s->slice_context_count; i++) {
  2298. H264Context *c;
  2299. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  2300. memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
  2301. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  2302. c->h264dsp = h->h264dsp;
  2303. c->sps = h->sps;
  2304. c->pps = h->pps;
  2305. c->pixel_shift = h->pixel_shift;
  2306. init_scan_tables(c);
  2307. clone_tables(c, h, i);
  2308. }
  2309. for (i = 0; i < s->slice_context_count; i++)
  2310. if (context_init(h->thread_context[i]) < 0) {
  2311. av_log(h->s.avctx, AV_LOG_ERROR,
  2312. "context_init() failed.\n");
  2313. return -1;
  2314. }
  2315. }
  2316. }
  2317. if (h == h0 && h->dequant_coeff_pps != pps_id) {
  2318. h->dequant_coeff_pps = pps_id;
  2319. init_dequant_tables(h);
  2320. }
  2321. h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
  2322. h->mb_mbaff = 0;
  2323. h->mb_aff_frame = 0;
  2324. last_pic_structure = s0->picture_structure;
  2325. last_pic_dropable = s0->dropable;
  2326. s->dropable = h->nal_ref_idc == 0;
  2327. if (h->sps.frame_mbs_only_flag) {
  2328. s->picture_structure = PICT_FRAME;
  2329. } else {
  2330. if (get_bits1(&s->gb)) { // field_pic_flag
  2331. s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
  2332. } else {
  2333. s->picture_structure = PICT_FRAME;
  2334. h->mb_aff_frame = h->sps.mb_aff;
  2335. }
  2336. }
  2337. h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
  2338. if (h0->current_slice != 0) {
  2339. if (last_pic_structure != s->picture_structure ||
  2340. last_pic_dropable != s->dropable) {
  2341. av_log(h->s.avctx, AV_LOG_ERROR,
  2342. "Changing field mode (%d -> %d) between slices is not allowed\n",
  2343. last_pic_structure, s->picture_structure);
  2344. s->picture_structure = last_pic_structure;
  2345. s->dropable = last_pic_dropable;
  2346. return AVERROR_INVALIDDATA;
  2347. } else if (!s0->current_picture_ptr) {
  2348. av_log(s->avctx, AV_LOG_ERROR,
  2349. "unset current_picture_ptr on %d. slice\n",
  2350. h0->current_slice + 1);
  2351. return AVERROR_INVALIDDATA;
  2352. }
  2353. } else {
  2354. /* Shorten frame num gaps so we don't have to allocate reference
  2355. * frames just to throw them away */
  2356. if (h->frame_num != h->prev_frame_num) {
  2357. int unwrap_prev_frame_num = h->prev_frame_num;
  2358. int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2359. if (unwrap_prev_frame_num > h->frame_num)
  2360. unwrap_prev_frame_num -= max_frame_num;
  2361. if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
  2362. unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
  2363. if (unwrap_prev_frame_num < 0)
  2364. unwrap_prev_frame_num += max_frame_num;
  2365. h->prev_frame_num = unwrap_prev_frame_num;
  2366. }
  2367. }
  2368. /* See if we have a decoded first field looking for a pair...
  2369. * Here, we're using that to see if we should mark previously
  2370. * decode frames as "finished".
  2371. * We have to do that before the "dummy" in-between frame allocation,
  2372. * since that can modify s->current_picture_ptr. */
  2373. if (s0->first_field) {
  2374. assert(s0->current_picture_ptr);
  2375. assert(s0->current_picture_ptr->f.data[0]);
  2376. assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
  2377. /* Mark old field/frame as completed */
  2378. if (!last_pic_dropable && s0->current_picture_ptr->owner2 == s0) {
  2379. ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
  2380. last_pic_structure == PICT_BOTTOM_FIELD);
  2381. }
  2382. /* figure out if we have a complementary field pair */
  2383. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  2384. /* Previous field is unmatched. Don't display it, but let it
  2385. * remain for reference if marked as such. */
  2386. if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
  2387. ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
  2388. last_pic_structure == PICT_TOP_FIELD);
  2389. }
  2390. } else {
  2391. if (s0->current_picture_ptr->frame_num != h->frame_num) {
  2392. /* This and previous field were reference, but had
  2393. * different frame_nums. Consider this field first in
  2394. * pair. Throw away previous field except for reference
  2395. * purposes. */
  2396. if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
  2397. ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
  2398. last_pic_structure == PICT_TOP_FIELD);
  2399. }
  2400. } else {
  2401. /* Second field in complementary pair */
  2402. if (!((last_pic_structure == PICT_TOP_FIELD &&
  2403. s->picture_structure == PICT_BOTTOM_FIELD) ||
  2404. (last_pic_structure == PICT_BOTTOM_FIELD &&
  2405. s->picture_structure == PICT_TOP_FIELD))) {
  2406. av_log(s->avctx, AV_LOG_ERROR,
  2407. "Invalid field mode combination %d/%d\n",
  2408. last_pic_structure, s->picture_structure);
  2409. s->picture_structure = last_pic_structure;
  2410. s->dropable = last_pic_dropable;
  2411. return AVERROR_INVALIDDATA;
  2412. } else if (last_pic_dropable != s->dropable) {
  2413. av_log(s->avctx, AV_LOG_ERROR,
  2414. "Cannot combine reference and non-reference fields in the same frame\n");
  2415. av_log_ask_for_sample(s->avctx, NULL);
  2416. s->picture_structure = last_pic_structure;
  2417. s->dropable = last_pic_dropable;
  2418. return AVERROR_INVALIDDATA;
  2419. }
  2420. /* Take ownership of this buffer. Note that if another thread owned
  2421. * the first field of this buffer, we're not operating on that pointer,
  2422. * so the original thread is still responsible for reporting progress
  2423. * on that first field (or if that was us, we just did that above).
  2424. * By taking ownership, we assign responsibility to ourselves to
  2425. * report progress on the second field. */
  2426. s0->current_picture_ptr->owner2 = s0;
  2427. }
  2428. }
  2429. }
  2430. while (h->frame_num != h->prev_frame_num &&
  2431. h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
  2432. Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2433. av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  2434. h->frame_num, h->prev_frame_num);
  2435. if (ff_h264_frame_start(h) < 0)
  2436. return -1;
  2437. h->prev_frame_num++;
  2438. h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
  2439. s->current_picture_ptr->frame_num = h->prev_frame_num;
  2440. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
  2441. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
  2442. ff_generate_sliding_window_mmcos(h);
  2443. if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
  2444. (s->avctx->err_recognition & AV_EF_EXPLODE))
  2445. return AVERROR_INVALIDDATA;
  2446. /* Error concealment: if a ref is missing, copy the previous ref in its place.
  2447. * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
  2448. * about there being no actual duplicates.
  2449. * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
  2450. * concealing a lost frame, this probably isn't noticeable by comparison, but it should
  2451. * be fixed. */
  2452. if (h->short_ref_count) {
  2453. if (prev) {
  2454. av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
  2455. (const uint8_t **)prev->f.data, prev->f.linesize,
  2456. s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
  2457. h->short_ref[0]->poc = prev->poc + 2;
  2458. }
  2459. h->short_ref[0]->frame_num = h->prev_frame_num;
  2460. }
  2461. }
  2462. /* See if we have a decoded first field looking for a pair...
  2463. * We're using that to see whether to continue decoding in that
  2464. * frame, or to allocate a new one. */
  2465. if (s0->first_field) {
  2466. assert(s0->current_picture_ptr);
  2467. assert(s0->current_picture_ptr->f.data[0]);
  2468. assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
  2469. /* figure out if we have a complementary field pair */
  2470. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  2471. /* Previous field is unmatched. Don't display it, but let it
  2472. * remain for reference if marked as such. */
  2473. s0->current_picture_ptr = NULL;
  2474. s0->first_field = FIELD_PICTURE;
  2475. } else {
  2476. if (s0->current_picture_ptr->frame_num != h->frame_num) {
  2477. /* This and the previous field had different frame_nums.
  2478. * Consider this field first in pair. Throw away previous
  2479. * one except for reference purposes. */
  2480. s0->first_field = 1;
  2481. s0->current_picture_ptr = NULL;
  2482. } else {
  2483. /* Second field in complementary pair */
  2484. s0->first_field = 0;
  2485. }
  2486. }
  2487. } else {
  2488. /* Frame or first field in a potentially complementary pair */
  2489. s0->first_field = FIELD_PICTURE;
  2490. }
  2491. if (!FIELD_PICTURE || s0->first_field) {
  2492. if (ff_h264_frame_start(h) < 0) {
  2493. s0->first_field = 0;
  2494. return -1;
  2495. }
  2496. } else {
  2497. ff_release_unused_pictures(s, 0);
  2498. }
  2499. }
  2500. if (h != h0)
  2501. clone_slice(h, h0);
  2502. s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
  2503. assert(s->mb_num == s->mb_width * s->mb_height);
  2504. if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  2505. first_mb_in_slice >= s->mb_num) {
  2506. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  2507. return -1;
  2508. }
  2509. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  2510. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  2511. if (s->picture_structure == PICT_BOTTOM_FIELD)
  2512. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  2513. assert(s->mb_y < s->mb_height);
  2514. if (s->picture_structure == PICT_FRAME) {
  2515. h->curr_pic_num = h->frame_num;
  2516. h->max_pic_num = 1 << h->sps.log2_max_frame_num;
  2517. } else {
  2518. h->curr_pic_num = 2 * h->frame_num + 1;
  2519. h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
  2520. }
  2521. if (h->nal_unit_type == NAL_IDR_SLICE)
  2522. get_ue_golomb(&s->gb); /* idr_pic_id */
  2523. if (h->sps.poc_type == 0) {
  2524. h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  2525. if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
  2526. h->delta_poc_bottom = get_se_golomb(&s->gb);
  2527. }
  2528. if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
  2529. h->delta_poc[0] = get_se_golomb(&s->gb);
  2530. if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
  2531. h->delta_poc[1] = get_se_golomb(&s->gb);
  2532. }
  2533. init_poc(h);
  2534. if (h->pps.redundant_pic_cnt_present)
  2535. h->redundant_pic_count = get_ue_golomb(&s->gb);
  2536. // set defaults, might be overridden a few lines later
  2537. h->ref_count[0] = h->pps.ref_count[0];
  2538. h->ref_count[1] = h->pps.ref_count[1];
  2539. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  2540. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  2541. h->direct_spatial_mv_pred = get_bits1(&s->gb);
  2542. num_ref_idx_active_override_flag = get_bits1(&s->gb);
  2543. if (num_ref_idx_active_override_flag) {
  2544. h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
  2545. if (h->ref_count[0] < 1)
  2546. return AVERROR_INVALIDDATA;
  2547. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2548. h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
  2549. if (h->ref_count[1] < 1)
  2550. return AVERROR_INVALIDDATA;
  2551. }
  2552. }
  2553. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  2554. h->list_count = 2;
  2555. else
  2556. h->list_count = 1;
  2557. } else
  2558. h->list_count = 0;
  2559. max_refs = s->picture_structure == PICT_FRAME ? 16 : 32;
  2560. if (h->ref_count[0] > max_refs || h->ref_count[1] > max_refs) {
  2561. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
  2562. h->ref_count[0] = h->ref_count[1] = 1;
  2563. return AVERROR_INVALIDDATA;
  2564. }
  2565. if (!default_ref_list_done)
  2566. ff_h264_fill_default_ref_list(h);
  2567. if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
  2568. ff_h264_decode_ref_pic_list_reordering(h) < 0) {
  2569. h->ref_count[1] = h->ref_count[0] = 0;
  2570. return -1;
  2571. }
  2572. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  2573. s->last_picture_ptr = &h->ref_list[0][0];
  2574. s->last_picture_ptr->owner2 = s;
  2575. ff_copy_picture(&s->last_picture, s->last_picture_ptr);
  2576. }
  2577. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2578. s->next_picture_ptr = &h->ref_list[1][0];
  2579. s->next_picture_ptr->owner2 = s;
  2580. ff_copy_picture(&s->next_picture, s->next_picture_ptr);
  2581. }
  2582. if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
  2583. (h->pps.weighted_bipred_idc == 1 &&
  2584. h->slice_type_nos == AV_PICTURE_TYPE_B))
  2585. pred_weight_table(h);
  2586. else if (h->pps.weighted_bipred_idc == 2 &&
  2587. h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2588. implicit_weight_table(h, -1);
  2589. } else {
  2590. h->use_weight = 0;
  2591. for (i = 0; i < 2; i++) {
  2592. h->luma_weight_flag[i] = 0;
  2593. h->chroma_weight_flag[i] = 0;
  2594. }
  2595. }
  2596. if (h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
  2597. (s->avctx->err_recognition & AV_EF_EXPLODE))
  2598. return AVERROR_INVALIDDATA;
  2599. if (FRAME_MBAFF) {
  2600. ff_h264_fill_mbaff_ref_list(h);
  2601. if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2602. implicit_weight_table(h, 0);
  2603. implicit_weight_table(h, 1);
  2604. }
  2605. }
  2606. if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
  2607. ff_h264_direct_dist_scale_factor(h);
  2608. ff_h264_direct_ref_list_init(h);
  2609. if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
  2610. tmp = get_ue_golomb_31(&s->gb);
  2611. if (tmp > 2) {
  2612. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  2613. return -1;
  2614. }
  2615. h->cabac_init_idc = tmp;
  2616. }
  2617. h->last_qscale_diff = 0;
  2618. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  2619. if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
  2620. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  2621. return -1;
  2622. }
  2623. s->qscale = tmp;
  2624. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2625. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2626. // FIXME qscale / qp ... stuff
  2627. if (h->slice_type == AV_PICTURE_TYPE_SP)
  2628. get_bits1(&s->gb); /* sp_for_switch_flag */
  2629. if (h->slice_type == AV_PICTURE_TYPE_SP ||
  2630. h->slice_type == AV_PICTURE_TYPE_SI)
  2631. get_se_golomb(&s->gb); /* slice_qs_delta */
  2632. h->deblocking_filter = 1;
  2633. h->slice_alpha_c0_offset = 52;
  2634. h->slice_beta_offset = 52;
  2635. if (h->pps.deblocking_filter_parameters_present) {
  2636. tmp = get_ue_golomb_31(&s->gb);
  2637. if (tmp > 2) {
  2638. av_log(s->avctx, AV_LOG_ERROR,
  2639. "deblocking_filter_idc %u out of range\n", tmp);
  2640. return -1;
  2641. }
  2642. h->deblocking_filter = tmp;
  2643. if (h->deblocking_filter < 2)
  2644. h->deblocking_filter ^= 1; // 1<->0
  2645. if (h->deblocking_filter) {
  2646. h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
  2647. h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
  2648. if (h->slice_alpha_c0_offset > 104U ||
  2649. h->slice_beta_offset > 104U) {
  2650. av_log(s->avctx, AV_LOG_ERROR,
  2651. "deblocking filter parameters %d %d out of range\n",
  2652. h->slice_alpha_c0_offset, h->slice_beta_offset);
  2653. return -1;
  2654. }
  2655. }
  2656. }
  2657. if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  2658. (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  2659. h->slice_type_nos != AV_PICTURE_TYPE_I) ||
  2660. (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  2661. h->slice_type_nos == AV_PICTURE_TYPE_B) ||
  2662. (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  2663. h->nal_ref_idc == 0))
  2664. h->deblocking_filter = 0;
  2665. if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
  2666. if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
  2667. /* Cheat slightly for speed:
  2668. * Do not bother to deblock across slices. */
  2669. h->deblocking_filter = 2;
  2670. } else {
  2671. h0->max_contexts = 1;
  2672. if (!h0->single_decode_warning) {
  2673. av_log(s->avctx, AV_LOG_INFO,
  2674. "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  2675. h0->single_decode_warning = 1;
  2676. }
  2677. if (h != h0) {
  2678. av_log(h->s.avctx, AV_LOG_ERROR,
  2679. "Deblocking switched inside frame.\n");
  2680. return 1;
  2681. }
  2682. }
  2683. }
  2684. h->qp_thresh = 15 + 52 -
  2685. FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
  2686. FFMAX3(0,
  2687. h->pps.chroma_qp_index_offset[0],
  2688. h->pps.chroma_qp_index_offset[1]) +
  2689. 6 * (h->sps.bit_depth_luma - 8);
  2690. h0->last_slice_type = slice_type;
  2691. h->slice_num = ++h0->current_slice;
  2692. if (h->slice_num >= MAX_SLICES) {
  2693. av_log(s->avctx, AV_LOG_ERROR,
  2694. "Too many slices, increase MAX_SLICES and recompile\n");
  2695. }
  2696. for (j = 0; j < 2; j++) {
  2697. int id_list[16];
  2698. int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
  2699. for (i = 0; i < 16; i++) {
  2700. id_list[i] = 60;
  2701. if (h->ref_list[j][i].f.data[0]) {
  2702. int k;
  2703. uint8_t *base = h->ref_list[j][i].f.base[0];
  2704. for (k = 0; k < h->short_ref_count; k++)
  2705. if (h->short_ref[k]->f.base[0] == base) {
  2706. id_list[i] = k;
  2707. break;
  2708. }
  2709. for (k = 0; k < h->long_ref_count; k++)
  2710. if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
  2711. id_list[i] = h->short_ref_count + k;
  2712. break;
  2713. }
  2714. }
  2715. }
  2716. ref2frm[0] =
  2717. ref2frm[1] = -1;
  2718. for (i = 0; i < 16; i++)
  2719. ref2frm[i + 2] = 4 * id_list[i] +
  2720. (h->ref_list[j][i].f.reference & 3);
  2721. ref2frm[18 + 0] =
  2722. ref2frm[18 + 1] = -1;
  2723. for (i = 16; i < 48; i++)
  2724. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  2725. (h->ref_list[j][i].f.reference & 3);
  2726. }
  2727. // FIXME: fix draw_edges + PAFF + frame threads
  2728. h->emu_edge_width = (s->flags & CODEC_FLAG_EMU_EDGE ||
  2729. (!h->sps.frame_mbs_only_flag &&
  2730. s->avctx->active_thread_type))
  2731. ? 0 : 16;
  2732. h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  2733. if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
  2734. av_log(h->s.avctx, AV_LOG_DEBUG,
  2735. "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",
  2736. h->slice_num,
  2737. (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  2738. first_mb_in_slice,
  2739. av_get_picture_type_char(h->slice_type),
  2740. h->slice_type_fixed ? " fix" : "",
  2741. h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  2742. pps_id, h->frame_num,
  2743. s->current_picture_ptr->field_poc[0],
  2744. s->current_picture_ptr->field_poc[1],
  2745. h->ref_count[0], h->ref_count[1],
  2746. s->qscale,
  2747. h->deblocking_filter,
  2748. h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
  2749. h->use_weight,
  2750. h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
  2751. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  2752. }
  2753. return 0;
  2754. }
  2755. int ff_h264_get_slice_type(const H264Context *h)
  2756. {
  2757. switch (h->slice_type) {
  2758. case AV_PICTURE_TYPE_P:
  2759. return 0;
  2760. case AV_PICTURE_TYPE_B:
  2761. return 1;
  2762. case AV_PICTURE_TYPE_I:
  2763. return 2;
  2764. case AV_PICTURE_TYPE_SP:
  2765. return 3;
  2766. case AV_PICTURE_TYPE_SI:
  2767. return 4;
  2768. default:
  2769. return -1;
  2770. }
  2771. }
  2772. static av_always_inline void fill_filter_caches_inter(H264Context *h,
  2773. MpegEncContext *const s,
  2774. int mb_type, int top_xy,
  2775. int left_xy[LEFT_MBS],
  2776. int top_type,
  2777. int left_type[LEFT_MBS],
  2778. int mb_xy, int list)
  2779. {
  2780. int b_stride = h->b_stride;
  2781. int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
  2782. int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
  2783. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  2784. if (USES_LIST(top_type, list)) {
  2785. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  2786. const int b8_xy = 4 * top_xy + 2;
  2787. int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
  2788. AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
  2789. ref_cache[0 - 1 * 8] =
  2790. ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
  2791. ref_cache[2 - 1 * 8] =
  2792. ref_cache[3 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
  2793. } else {
  2794. AV_ZERO128(mv_dst - 1 * 8);
  2795. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2796. }
  2797. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  2798. if (USES_LIST(left_type[LTOP], list)) {
  2799. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  2800. const int b8_xy = 4 * left_xy[LTOP] + 1;
  2801. int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
  2802. AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
  2803. AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
  2804. AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
  2805. AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride * 3]);
  2806. ref_cache[-1 + 0] =
  2807. ref_cache[-1 + 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 0]];
  2808. ref_cache[-1 + 16] =
  2809. ref_cache[-1 + 24] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 1]];
  2810. } else {
  2811. AV_ZERO32(mv_dst - 1 + 0);
  2812. AV_ZERO32(mv_dst - 1 + 8);
  2813. AV_ZERO32(mv_dst - 1 + 16);
  2814. AV_ZERO32(mv_dst - 1 + 24);
  2815. ref_cache[-1 + 0] =
  2816. ref_cache[-1 + 8] =
  2817. ref_cache[-1 + 16] =
  2818. ref_cache[-1 + 24] = LIST_NOT_USED;
  2819. }
  2820. }
  2821. }
  2822. if (!USES_LIST(mb_type, list)) {
  2823. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  2824. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2825. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2826. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2827. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2828. return;
  2829. }
  2830. {
  2831. int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
  2832. int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
  2833. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
  2834. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
  2835. AV_WN32A(&ref_cache[0 * 8], ref01);
  2836. AV_WN32A(&ref_cache[1 * 8], ref01);
  2837. AV_WN32A(&ref_cache[2 * 8], ref23);
  2838. AV_WN32A(&ref_cache[3 * 8], ref23);
  2839. }
  2840. {
  2841. int16_t(*mv_src)[2] = &s->current_picture.f.motion_val[list][4 * s->mb_x + 4 * s->mb_y * b_stride];
  2842. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  2843. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  2844. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  2845. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  2846. }
  2847. }
  2848. /**
  2849. *
  2850. * @return non zero if the loop filter can be skipped
  2851. */
  2852. static int fill_filter_caches(H264Context *h, int mb_type)
  2853. {
  2854. MpegEncContext *const s = &h->s;
  2855. const int mb_xy = h->mb_xy;
  2856. int top_xy, left_xy[LEFT_MBS];
  2857. int top_type, left_type[LEFT_MBS];
  2858. uint8_t *nnz;
  2859. uint8_t *nnz_cache;
  2860. top_xy = mb_xy - (s->mb_stride << MB_FIELD);
  2861. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  2862. * stuff, I can't imagine that these complex rules are worth it. */
  2863. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  2864. if (FRAME_MBAFF) {
  2865. const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
  2866. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  2867. if (s->mb_y & 1) {
  2868. if (left_mb_field_flag != curr_mb_field_flag)
  2869. left_xy[LTOP] -= s->mb_stride;
  2870. } else {
  2871. if (curr_mb_field_flag)
  2872. top_xy += s->mb_stride &
  2873. (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
  2874. if (left_mb_field_flag != curr_mb_field_flag)
  2875. left_xy[LBOT] += s->mb_stride;
  2876. }
  2877. }
  2878. h->top_mb_xy = top_xy;
  2879. h->left_mb_xy[LTOP] = left_xy[LTOP];
  2880. h->left_mb_xy[LBOT] = left_xy[LBOT];
  2881. {
  2882. /* For sufficiently low qp, filtering wouldn't do anything.
  2883. * This is a conservative estimate: could also check beta_offset
  2884. * and more accurate chroma_qp. */
  2885. int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  2886. int qp = s->current_picture.f.qscale_table[mb_xy];
  2887. if (qp <= qp_thresh &&
  2888. (left_xy[LTOP] < 0 ||
  2889. ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  2890. (top_xy < 0 ||
  2891. ((qp + s->current_picture.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  2892. if (!FRAME_MBAFF)
  2893. return 1;
  2894. if ((left_xy[LTOP] < 0 ||
  2895. ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  2896. (top_xy < s->mb_stride ||
  2897. ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
  2898. return 1;
  2899. }
  2900. }
  2901. top_type = s->current_picture.f.mb_type[top_xy];
  2902. left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
  2903. left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
  2904. if (h->deblocking_filter == 2) {
  2905. if (h->slice_table[top_xy] != h->slice_num)
  2906. top_type = 0;
  2907. if (h->slice_table[left_xy[LBOT]] != h->slice_num)
  2908. left_type[LTOP] = left_type[LBOT] = 0;
  2909. } else {
  2910. if (h->slice_table[top_xy] == 0xFFFF)
  2911. top_type = 0;
  2912. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  2913. left_type[LTOP] = left_type[LBOT] = 0;
  2914. }
  2915. h->top_type = top_type;
  2916. h->left_type[LTOP] = left_type[LTOP];
  2917. h->left_type[LBOT] = left_type[LBOT];
  2918. if (IS_INTRA(mb_type))
  2919. return 0;
  2920. fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
  2921. top_type, left_type, mb_xy, 0);
  2922. if (h->list_count == 2)
  2923. fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
  2924. top_type, left_type, mb_xy, 1);
  2925. nnz = h->non_zero_count[mb_xy];
  2926. nnz_cache = h->non_zero_count_cache;
  2927. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  2928. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  2929. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  2930. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  2931. h->cbp = h->cbp_table[mb_xy];
  2932. if (top_type) {
  2933. nnz = h->non_zero_count[top_xy];
  2934. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  2935. }
  2936. if (left_type[LTOP]) {
  2937. nnz = h->non_zero_count[left_xy[LTOP]];
  2938. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  2939. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  2940. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  2941. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  2942. }
  2943. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  2944. * from what the loop filter needs */
  2945. if (!CABAC && h->pps.transform_8x8_mode) {
  2946. if (IS_8x8DCT(top_type)) {
  2947. nnz_cache[4 + 8 * 0] =
  2948. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  2949. nnz_cache[6 + 8 * 0] =
  2950. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  2951. }
  2952. if (IS_8x8DCT(left_type[LTOP])) {
  2953. nnz_cache[3 + 8 * 1] =
  2954. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  2955. }
  2956. if (IS_8x8DCT(left_type[LBOT])) {
  2957. nnz_cache[3 + 8 * 3] =
  2958. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  2959. }
  2960. if (IS_8x8DCT(mb_type)) {
  2961. nnz_cache[scan8[0]] =
  2962. nnz_cache[scan8[1]] =
  2963. nnz_cache[scan8[2]] =
  2964. nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
  2965. nnz_cache[scan8[0 + 4]] =
  2966. nnz_cache[scan8[1 + 4]] =
  2967. nnz_cache[scan8[2 + 4]] =
  2968. nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
  2969. nnz_cache[scan8[0 + 8]] =
  2970. nnz_cache[scan8[1 + 8]] =
  2971. nnz_cache[scan8[2 + 8]] =
  2972. nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
  2973. nnz_cache[scan8[0 + 12]] =
  2974. nnz_cache[scan8[1 + 12]] =
  2975. nnz_cache[scan8[2 + 12]] =
  2976. nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
  2977. }
  2978. }
  2979. return 0;
  2980. }
  2981. static void loop_filter(H264Context *h, int start_x, int end_x)
  2982. {
  2983. MpegEncContext *const s = &h->s;
  2984. uint8_t *dest_y, *dest_cb, *dest_cr;
  2985. int linesize, uvlinesize, mb_x, mb_y;
  2986. const int end_mb_y = s->mb_y + FRAME_MBAFF;
  2987. const int old_slice_type = h->slice_type;
  2988. const int pixel_shift = h->pixel_shift;
  2989. const int block_h = 16 >> s->chroma_y_shift;
  2990. if (h->deblocking_filter) {
  2991. for (mb_x = start_x; mb_x < end_x; mb_x++)
  2992. for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
  2993. int mb_xy, mb_type;
  2994. mb_xy = h->mb_xy = mb_x + mb_y * s->mb_stride;
  2995. h->slice_num = h->slice_table[mb_xy];
  2996. mb_type = s->current_picture.f.mb_type[mb_xy];
  2997. h->list_count = h->list_counts[mb_xy];
  2998. if (FRAME_MBAFF)
  2999. h->mb_mbaff =
  3000. h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  3001. s->mb_x = mb_x;
  3002. s->mb_y = mb_y;
  3003. dest_y = s->current_picture.f.data[0] +
  3004. ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
  3005. dest_cb = s->current_picture.f.data[1] +
  3006. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3007. mb_y * s->uvlinesize * block_h;
  3008. dest_cr = s->current_picture.f.data[2] +
  3009. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3010. mb_y * s->uvlinesize * block_h;
  3011. // FIXME simplify above
  3012. if (MB_FIELD) {
  3013. linesize = h->mb_linesize = s->linesize * 2;
  3014. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  3015. if (mb_y & 1) { // FIXME move out of this function?
  3016. dest_y -= s->linesize * 15;
  3017. dest_cb -= s->uvlinesize * (block_h - 1);
  3018. dest_cr -= s->uvlinesize * (block_h - 1);
  3019. }
  3020. } else {
  3021. linesize = h->mb_linesize = s->linesize;
  3022. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  3023. }
  3024. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
  3025. uvlinesize, 0);
  3026. if (fill_filter_caches(h, mb_type))
  3027. continue;
  3028. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
  3029. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
  3030. if (FRAME_MBAFF) {
  3031. ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  3032. linesize, uvlinesize);
  3033. } else {
  3034. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
  3035. dest_cr, linesize, uvlinesize);
  3036. }
  3037. }
  3038. }
  3039. h->slice_type = old_slice_type;
  3040. s->mb_x = end_x;
  3041. s->mb_y = end_mb_y - FRAME_MBAFF;
  3042. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  3043. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  3044. }
  3045. static void predict_field_decoding_flag(H264Context *h)
  3046. {
  3047. MpegEncContext *const s = &h->s;
  3048. const int mb_xy = s->mb_x + s->mb_y * s->mb_stride;
  3049. int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
  3050. s->current_picture.f.mb_type[mb_xy - 1] :
  3051. (h->slice_table[mb_xy - s->mb_stride] == h->slice_num) ?
  3052. s->current_picture.f.mb_type[mb_xy - s->mb_stride] : 0;
  3053. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3054. }
  3055. /**
  3056. * Draw edges and report progress for the last MB row.
  3057. */
  3058. static void decode_finish_row(H264Context *h)
  3059. {
  3060. MpegEncContext *const s = &h->s;
  3061. int top = 16 * (s->mb_y >> FIELD_PICTURE);
  3062. int pic_height = 16 * s->mb_height >> FIELD_PICTURE;
  3063. int height = 16 << FRAME_MBAFF;
  3064. int deblock_border = (16 + 4) << FRAME_MBAFF;
  3065. if (h->deblocking_filter) {
  3066. if ((top + height) >= pic_height)
  3067. height += deblock_border;
  3068. top -= deblock_border;
  3069. }
  3070. if (top >= pic_height || (top + height) < h->emu_edge_height)
  3071. return;
  3072. height = FFMIN(height, pic_height - top);
  3073. if (top < h->emu_edge_height) {
  3074. height = top + height;
  3075. top = 0;
  3076. }
  3077. ff_draw_horiz_band(s, top, height);
  3078. if (s->dropable)
  3079. return;
  3080. ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
  3081. s->picture_structure == PICT_BOTTOM_FIELD);
  3082. }
  3083. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  3084. {
  3085. H264Context *h = *(void **)arg;
  3086. MpegEncContext *const s = &h->s;
  3087. const int part_mask = s->partitioned_frame ? (ER_AC_END | ER_AC_ERROR)
  3088. : 0x7F;
  3089. int lf_x_start = s->mb_x;
  3090. s->mb_skip_run = -1;
  3091. h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME ||
  3092. s->codec_id != AV_CODEC_ID_H264 ||
  3093. (CONFIG_GRAY && (s->flags & CODEC_FLAG_GRAY));
  3094. if (h->pps.cabac) {
  3095. /* realign */
  3096. align_get_bits(&s->gb);
  3097. /* init cabac */
  3098. ff_init_cabac_states(&h->cabac);
  3099. ff_init_cabac_decoder(&h->cabac,
  3100. s->gb.buffer + get_bits_count(&s->gb) / 8,
  3101. (get_bits_left(&s->gb) + 7) / 8);
  3102. ff_h264_init_cabac_states(h);
  3103. for (;;) {
  3104. // START_TIMER
  3105. int ret = ff_h264_decode_mb_cabac(h);
  3106. int eos;
  3107. // STOP_TIMER("decode_mb_cabac")
  3108. if (ret >= 0)
  3109. ff_h264_hl_decode_mb(h);
  3110. // FIXME optimal? or let mb_decode decode 16x32 ?
  3111. if (ret >= 0 && FRAME_MBAFF) {
  3112. s->mb_y++;
  3113. ret = ff_h264_decode_mb_cabac(h);
  3114. if (ret >= 0)
  3115. ff_h264_hl_decode_mb(h);
  3116. s->mb_y--;
  3117. }
  3118. eos = get_cabac_terminate(&h->cabac);
  3119. if ((s->workaround_bugs & FF_BUG_TRUNCATED) &&
  3120. h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3121. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
  3122. s->mb_y, ER_MB_END & part_mask);
  3123. if (s->mb_x >= lf_x_start)
  3124. loop_filter(h, lf_x_start, s->mb_x + 1);
  3125. return 0;
  3126. }
  3127. if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3128. av_log(h->s.avctx, AV_LOG_ERROR,
  3129. "error while decoding MB %d %d, bytestream (%td)\n",
  3130. s->mb_x, s->mb_y,
  3131. h->cabac.bytestream_end - h->cabac.bytestream);
  3132. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
  3133. s->mb_y, ER_MB_ERROR & part_mask);
  3134. return -1;
  3135. }
  3136. if (++s->mb_x >= s->mb_width) {
  3137. loop_filter(h, lf_x_start, s->mb_x);
  3138. s->mb_x = lf_x_start = 0;
  3139. decode_finish_row(h);
  3140. ++s->mb_y;
  3141. if (FIELD_OR_MBAFF_PICTURE) {
  3142. ++s->mb_y;
  3143. if (FRAME_MBAFF && s->mb_y < s->mb_height)
  3144. predict_field_decoding_flag(h);
  3145. }
  3146. }
  3147. if (eos || s->mb_y >= s->mb_height) {
  3148. tprintf(s->avctx, "slice end %d %d\n",
  3149. get_bits_count(&s->gb), s->gb.size_in_bits);
  3150. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
  3151. s->mb_y, ER_MB_END & part_mask);
  3152. if (s->mb_x > lf_x_start)
  3153. loop_filter(h, lf_x_start, s->mb_x);
  3154. return 0;
  3155. }
  3156. }
  3157. } else {
  3158. for (;;) {
  3159. int ret = ff_h264_decode_mb_cavlc(h);
  3160. if (ret >= 0)
  3161. ff_h264_hl_decode_mb(h);
  3162. // FIXME optimal? or let mb_decode decode 16x32 ?
  3163. if (ret >= 0 && FRAME_MBAFF) {
  3164. s->mb_y++;
  3165. ret = ff_h264_decode_mb_cavlc(h);
  3166. if (ret >= 0)
  3167. ff_h264_hl_decode_mb(h);
  3168. s->mb_y--;
  3169. }
  3170. if (ret < 0) {
  3171. av_log(h->s.avctx, AV_LOG_ERROR,
  3172. "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  3173. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
  3174. s->mb_y, ER_MB_ERROR & part_mask);
  3175. return -1;
  3176. }
  3177. if (++s->mb_x >= s->mb_width) {
  3178. loop_filter(h, lf_x_start, s->mb_x);
  3179. s->mb_x = lf_x_start = 0;
  3180. decode_finish_row(h);
  3181. ++s->mb_y;
  3182. if (FIELD_OR_MBAFF_PICTURE) {
  3183. ++s->mb_y;
  3184. if (FRAME_MBAFF && s->mb_y < s->mb_height)
  3185. predict_field_decoding_flag(h);
  3186. }
  3187. if (s->mb_y >= s->mb_height) {
  3188. tprintf(s->avctx, "slice end %d %d\n",
  3189. get_bits_count(&s->gb), s->gb.size_in_bits);
  3190. if (get_bits_left(&s->gb) == 0) {
  3191. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
  3192. s->mb_x - 1, s->mb_y,
  3193. ER_MB_END & part_mask);
  3194. return 0;
  3195. } else {
  3196. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
  3197. s->mb_x - 1, s->mb_y,
  3198. ER_MB_END & part_mask);
  3199. return -1;
  3200. }
  3201. }
  3202. }
  3203. if (get_bits_left(&s->gb) <= 0 && s->mb_skip_run <= 0) {
  3204. tprintf(s->avctx, "slice end %d %d\n",
  3205. get_bits_count(&s->gb), s->gb.size_in_bits);
  3206. if (get_bits_left(&s->gb) == 0) {
  3207. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
  3208. s->mb_x - 1, s->mb_y,
  3209. ER_MB_END & part_mask);
  3210. if (s->mb_x > lf_x_start)
  3211. loop_filter(h, lf_x_start, s->mb_x);
  3212. return 0;
  3213. } else {
  3214. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
  3215. s->mb_y, ER_MB_ERROR & part_mask);
  3216. return -1;
  3217. }
  3218. }
  3219. }
  3220. }
  3221. }
  3222. /**
  3223. * Call decode_slice() for each context.
  3224. *
  3225. * @param h h264 master context
  3226. * @param context_count number of contexts to execute
  3227. */
  3228. static int execute_decode_slices(H264Context *h, int context_count)
  3229. {
  3230. MpegEncContext *const s = &h->s;
  3231. AVCodecContext *const avctx = s->avctx;
  3232. H264Context *hx;
  3233. int i;
  3234. if (s->avctx->hwaccel ||
  3235. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3236. return 0;
  3237. if (context_count == 1) {
  3238. return decode_slice(avctx, &h);
  3239. } else {
  3240. for (i = 1; i < context_count; i++) {
  3241. hx = h->thread_context[i];
  3242. hx->s.err_recognition = avctx->err_recognition;
  3243. hx->s.error_count = 0;
  3244. }
  3245. avctx->execute(avctx, decode_slice, h->thread_context,
  3246. NULL, context_count, sizeof(void *));
  3247. /* pull back stuff from slices to master context */
  3248. hx = h->thread_context[context_count - 1];
  3249. s->mb_x = hx->s.mb_x;
  3250. s->mb_y = hx->s.mb_y;
  3251. s->dropable = hx->s.dropable;
  3252. s->picture_structure = hx->s.picture_structure;
  3253. for (i = 1; i < context_count; i++)
  3254. h->s.error_count += h->thread_context[i]->s.error_count;
  3255. }
  3256. return 0;
  3257. }
  3258. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
  3259. {
  3260. MpegEncContext *const s = &h->s;
  3261. AVCodecContext *const avctx = s->avctx;
  3262. H264Context *hx; ///< thread context
  3263. int buf_index;
  3264. int context_count;
  3265. int next_avc;
  3266. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  3267. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  3268. int nal_index;
  3269. h->max_contexts = s->slice_context_count;
  3270. if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
  3271. h->current_slice = 0;
  3272. if (!s->first_field)
  3273. s->current_picture_ptr = NULL;
  3274. ff_h264_reset_sei(h);
  3275. }
  3276. for (; pass <= 1; pass++) {
  3277. buf_index = 0;
  3278. context_count = 0;
  3279. next_avc = h->is_avc ? 0 : buf_size;
  3280. nal_index = 0;
  3281. for (;;) {
  3282. int consumed;
  3283. int dst_length;
  3284. int bit_length;
  3285. const uint8_t *ptr;
  3286. int i, nalsize = 0;
  3287. int err;
  3288. if (buf_index >= next_avc) {
  3289. if (buf_index >= buf_size - h->nal_length_size)
  3290. break;
  3291. nalsize = 0;
  3292. for (i = 0; i < h->nal_length_size; i++)
  3293. nalsize = (nalsize << 8) | buf[buf_index++];
  3294. if (nalsize <= 0 || nalsize > buf_size - buf_index) {
  3295. av_log(h->s.avctx, AV_LOG_ERROR,
  3296. "AVC: nal size %d\n", nalsize);
  3297. break;
  3298. }
  3299. next_avc = buf_index + nalsize;
  3300. } else {
  3301. // start code prefix search
  3302. for (; buf_index + 3 < next_avc; buf_index++)
  3303. // This should always succeed in the first iteration.
  3304. if (buf[buf_index] == 0 &&
  3305. buf[buf_index + 1] == 0 &&
  3306. buf[buf_index + 2] == 1)
  3307. break;
  3308. if (buf_index + 3 >= buf_size) {
  3309. buf_index = buf_size;
  3310. break;
  3311. }
  3312. buf_index += 3;
  3313. if (buf_index >= next_avc)
  3314. continue;
  3315. }
  3316. hx = h->thread_context[context_count];
  3317. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  3318. &consumed, next_avc - buf_index);
  3319. if (ptr == NULL || dst_length < 0) {
  3320. buf_index = -1;
  3321. goto end;
  3322. }
  3323. i = buf_index + consumed;
  3324. if ((s->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  3325. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  3326. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  3327. s->workaround_bugs |= FF_BUG_TRUNCATED;
  3328. if (!(s->workaround_bugs & FF_BUG_TRUNCATED))
  3329. while (ptr[dst_length - 1] == 0 && dst_length > 0)
  3330. dst_length--;
  3331. bit_length = !dst_length ? 0
  3332. : (8 * dst_length -
  3333. decode_rbsp_trailing(h, ptr + dst_length - 1));
  3334. if (s->avctx->debug & FF_DEBUG_STARTCODE)
  3335. av_log(h->s.avctx, AV_LOG_DEBUG,
  3336. "NAL %d at %d/%d length %d\n",
  3337. hx->nal_unit_type, buf_index, buf_size, dst_length);
  3338. if (h->is_avc && (nalsize != consumed) && nalsize)
  3339. av_log(h->s.avctx, AV_LOG_DEBUG,
  3340. "AVC: Consumed only %d bytes instead of %d\n",
  3341. consumed, nalsize);
  3342. buf_index += consumed;
  3343. nal_index++;
  3344. if (pass == 0) {
  3345. /* packets can sometimes contain multiple PPS/SPS,
  3346. * e.g. two PAFF field pictures in one packet, or a demuxer
  3347. * which splits NALs strangely if so, when frame threading we
  3348. * can't start the next thread until we've read all of them */
  3349. switch (hx->nal_unit_type) {
  3350. case NAL_SPS:
  3351. case NAL_PPS:
  3352. nals_needed = nal_index;
  3353. break;
  3354. case NAL_IDR_SLICE:
  3355. case NAL_SLICE:
  3356. init_get_bits(&hx->s.gb, ptr, bit_length);
  3357. if (!get_ue_golomb(&hx->s.gb))
  3358. nals_needed = nal_index;
  3359. }
  3360. continue;
  3361. }
  3362. // FIXME do not discard SEI id
  3363. if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
  3364. continue;
  3365. again:
  3366. err = 0;
  3367. switch (hx->nal_unit_type) {
  3368. case NAL_IDR_SLICE:
  3369. if (h->nal_unit_type != NAL_IDR_SLICE) {
  3370. av_log(h->s.avctx, AV_LOG_ERROR,
  3371. "Invalid mix of idr and non-idr slices\n");
  3372. buf_index = -1;
  3373. goto end;
  3374. }
  3375. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  3376. case NAL_SLICE:
  3377. init_get_bits(&hx->s.gb, ptr, bit_length);
  3378. hx->intra_gb_ptr =
  3379. hx->inter_gb_ptr = &hx->s.gb;
  3380. hx->s.data_partitioning = 0;
  3381. if ((err = decode_slice_header(hx, h)))
  3382. break;
  3383. s->current_picture_ptr->f.key_frame |=
  3384. (hx->nal_unit_type == NAL_IDR_SLICE) ||
  3385. (h->sei_recovery_frame_cnt >= 0);
  3386. if (h->current_slice == 1) {
  3387. if (!(s->flags2 & CODEC_FLAG2_CHUNKS))
  3388. decode_postinit(h, nal_index >= nals_needed);
  3389. if (s->avctx->hwaccel &&
  3390. s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
  3391. return -1;
  3392. if (CONFIG_H264_VDPAU_DECODER &&
  3393. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3394. ff_vdpau_h264_picture_start(s);
  3395. }
  3396. if (hx->redundant_pic_count == 0 &&
  3397. (avctx->skip_frame < AVDISCARD_NONREF ||
  3398. hx->nal_ref_idc) &&
  3399. (avctx->skip_frame < AVDISCARD_BIDIR ||
  3400. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  3401. (avctx->skip_frame < AVDISCARD_NONKEY ||
  3402. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  3403. avctx->skip_frame < AVDISCARD_ALL) {
  3404. if (avctx->hwaccel) {
  3405. if (avctx->hwaccel->decode_slice(avctx,
  3406. &buf[buf_index - consumed],
  3407. consumed) < 0)
  3408. return -1;
  3409. } else if (CONFIG_H264_VDPAU_DECODER &&
  3410. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  3411. static const uint8_t start_code[] = {
  3412. 0x00, 0x00, 0x01 };
  3413. ff_vdpau_add_data_chunk(s, start_code,
  3414. sizeof(start_code));
  3415. ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed],
  3416. consumed);
  3417. } else
  3418. context_count++;
  3419. }
  3420. break;
  3421. case NAL_DPA:
  3422. init_get_bits(&hx->s.gb, ptr, bit_length);
  3423. hx->intra_gb_ptr =
  3424. hx->inter_gb_ptr = NULL;
  3425. if ((err = decode_slice_header(hx, h)) < 0)
  3426. break;
  3427. hx->s.data_partitioning = 1;
  3428. break;
  3429. case NAL_DPB:
  3430. init_get_bits(&hx->intra_gb, ptr, bit_length);
  3431. hx->intra_gb_ptr = &hx->intra_gb;
  3432. break;
  3433. case NAL_DPC:
  3434. init_get_bits(&hx->inter_gb, ptr, bit_length);
  3435. hx->inter_gb_ptr = &hx->inter_gb;
  3436. if (hx->redundant_pic_count == 0 &&
  3437. hx->intra_gb_ptr &&
  3438. hx->s.data_partitioning &&
  3439. s->current_picture_ptr &&
  3440. s->context_initialized &&
  3441. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  3442. (avctx->skip_frame < AVDISCARD_BIDIR ||
  3443. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  3444. (avctx->skip_frame < AVDISCARD_NONKEY ||
  3445. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  3446. avctx->skip_frame < AVDISCARD_ALL)
  3447. context_count++;
  3448. break;
  3449. case NAL_SEI:
  3450. init_get_bits(&s->gb, ptr, bit_length);
  3451. ff_h264_decode_sei(h);
  3452. break;
  3453. case NAL_SPS:
  3454. init_get_bits(&s->gb, ptr, bit_length);
  3455. if (ff_h264_decode_seq_parameter_set(h) < 0 &&
  3456. h->is_avc && (nalsize != consumed) && nalsize) {
  3457. av_log(h->s.avctx, AV_LOG_DEBUG,
  3458. "SPS decoding failure, trying again with the complete NAL\n");
  3459. init_get_bits(&s->gb, buf + buf_index + 1 - consumed,
  3460. 8 * (nalsize - 1));
  3461. ff_h264_decode_seq_parameter_set(h);
  3462. }
  3463. if (s->flags & CODEC_FLAG_LOW_DELAY ||
  3464. (h->sps.bitstream_restriction_flag &&
  3465. !h->sps.num_reorder_frames)) {
  3466. if (s->avctx->has_b_frames > 1 || h->delayed_pic[0])
  3467. av_log(avctx, AV_LOG_WARNING, "Delayed frames seen "
  3468. "reenabling low delay requires a codec "
  3469. "flush.\n");
  3470. else
  3471. s->low_delay = 1;
  3472. }
  3473. if (avctx->has_b_frames < 2)
  3474. avctx->has_b_frames = !s->low_delay;
  3475. if (avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  3476. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  3477. if (s->avctx->codec &&
  3478. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU
  3479. && (h->sps.bit_depth_luma != 8 ||
  3480. h->sps.chroma_format_idc > 1)) {
  3481. av_log(avctx, AV_LOG_ERROR,
  3482. "VDPAU decoding does not support video "
  3483. "colorspace\n");
  3484. buf_index = -1;
  3485. goto end;
  3486. }
  3487. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
  3488. avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  3489. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  3490. h->pixel_shift = h->sps.bit_depth_luma > 8;
  3491. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  3492. h->sps.chroma_format_idc);
  3493. ff_h264_pred_init(&h->hpc, s->codec_id,
  3494. h->sps.bit_depth_luma,
  3495. h->sps.chroma_format_idc);
  3496. s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
  3497. ff_dsputil_init(&s->dsp, s->avctx);
  3498. } else {
  3499. av_log(avctx, AV_LOG_ERROR,
  3500. "Unsupported bit depth: %d\n",
  3501. h->sps.bit_depth_luma);
  3502. buf_index = -1;
  3503. goto end;
  3504. }
  3505. }
  3506. break;
  3507. case NAL_PPS:
  3508. init_get_bits(&s->gb, ptr, bit_length);
  3509. ff_h264_decode_picture_parameter_set(h, bit_length);
  3510. break;
  3511. case NAL_AUD:
  3512. case NAL_END_SEQUENCE:
  3513. case NAL_END_STREAM:
  3514. case NAL_FILLER_DATA:
  3515. case NAL_SPS_EXT:
  3516. case NAL_AUXILIARY_SLICE:
  3517. break;
  3518. default:
  3519. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  3520. hx->nal_unit_type, bit_length);
  3521. }
  3522. if (context_count == h->max_contexts) {
  3523. execute_decode_slices(h, context_count);
  3524. context_count = 0;
  3525. }
  3526. if (err < 0)
  3527. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  3528. else if (err == 1) {
  3529. /* Slice could not be decoded in parallel mode, copy down
  3530. * NAL unit stuff to context 0 and restart. Note that
  3531. * rbsp_buffer is not transferred, but since we no longer
  3532. * run in parallel mode this should not be an issue. */
  3533. h->nal_unit_type = hx->nal_unit_type;
  3534. h->nal_ref_idc = hx->nal_ref_idc;
  3535. hx = h;
  3536. goto again;
  3537. }
  3538. }
  3539. }
  3540. if (context_count)
  3541. execute_decode_slices(h, context_count);
  3542. end:
  3543. /* clean up */
  3544. if (s->current_picture_ptr && s->current_picture_ptr->owner2 == s &&
  3545. !s->dropable) {
  3546. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
  3547. s->picture_structure == PICT_BOTTOM_FIELD);
  3548. }
  3549. return buf_index;
  3550. }
  3551. /**
  3552. * Return the number of bytes consumed for building the current frame.
  3553. */
  3554. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size)
  3555. {
  3556. if (pos == 0)
  3557. pos = 1; // avoid infinite loops (i doubt that is needed but ...)
  3558. if (pos + 10 > buf_size)
  3559. pos = buf_size; // oops ;)
  3560. return pos;
  3561. }
  3562. static int decode_frame(AVCodecContext *avctx, void *data,
  3563. int *got_frame, AVPacket *avpkt)
  3564. {
  3565. const uint8_t *buf = avpkt->data;
  3566. int buf_size = avpkt->size;
  3567. H264Context *h = avctx->priv_data;
  3568. MpegEncContext *s = &h->s;
  3569. AVFrame *pict = data;
  3570. int buf_index = 0;
  3571. s->flags = avctx->flags;
  3572. s->flags2 = avctx->flags2;
  3573. /* end of stream, output what is still in the buffers */
  3574. out:
  3575. if (buf_size == 0) {
  3576. Picture *out;
  3577. int i, out_idx;
  3578. s->current_picture_ptr = NULL;
  3579. // FIXME factorize this with the output code below
  3580. out = h->delayed_pic[0];
  3581. out_idx = 0;
  3582. for (i = 1;
  3583. h->delayed_pic[i] &&
  3584. !h->delayed_pic[i]->f.key_frame &&
  3585. !h->delayed_pic[i]->mmco_reset;
  3586. i++)
  3587. if (h->delayed_pic[i]->poc < out->poc) {
  3588. out = h->delayed_pic[i];
  3589. out_idx = i;
  3590. }
  3591. for (i = out_idx; h->delayed_pic[i]; i++)
  3592. h->delayed_pic[i] = h->delayed_pic[i + 1];
  3593. if (out) {
  3594. *got_frame = 1;
  3595. *pict = out->f;
  3596. }
  3597. return buf_index;
  3598. }
  3599. buf_index = decode_nal_units(h, buf, buf_size);
  3600. if (buf_index < 0)
  3601. return -1;
  3602. if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  3603. buf_size = 0;
  3604. goto out;
  3605. }
  3606. if (!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr) {
  3607. if (avctx->skip_frame >= AVDISCARD_NONREF)
  3608. return 0;
  3609. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  3610. return -1;
  3611. }
  3612. if (!(s->flags2 & CODEC_FLAG2_CHUNKS) ||
  3613. (s->mb_y >= s->mb_height && s->mb_height)) {
  3614. if (s->flags2 & CODEC_FLAG2_CHUNKS)
  3615. decode_postinit(h, 1);
  3616. field_end(h, 0);
  3617. if (!h->next_output_pic) {
  3618. /* Wait for second field. */
  3619. *got_frame = 0;
  3620. } else {
  3621. *got_frame = 1;
  3622. *pict = h->next_output_pic->f;
  3623. }
  3624. }
  3625. assert(pict->data[0] || !*got_frame);
  3626. ff_print_debug_info(s, pict);
  3627. return get_consumed_bytes(s, buf_index, buf_size);
  3628. }
  3629. av_cold void ff_h264_free_context(H264Context *h)
  3630. {
  3631. int i;
  3632. free_tables(h, 1); // FIXME cleanup init stuff perhaps
  3633. for (i = 0; i < MAX_SPS_COUNT; i++)
  3634. av_freep(h->sps_buffers + i);
  3635. for (i = 0; i < MAX_PPS_COUNT; i++)
  3636. av_freep(h->pps_buffers + i);
  3637. }
  3638. static av_cold int h264_decode_end(AVCodecContext *avctx)
  3639. {
  3640. H264Context *h = avctx->priv_data;
  3641. MpegEncContext *s = &h->s;
  3642. ff_h264_free_context(h);
  3643. ff_MPV_common_end(s);
  3644. // memset(h, 0, sizeof(H264Context));
  3645. return 0;
  3646. }
  3647. static const AVProfile profiles[] = {
  3648. { FF_PROFILE_H264_BASELINE, "Baseline" },
  3649. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  3650. { FF_PROFILE_H264_MAIN, "Main" },
  3651. { FF_PROFILE_H264_EXTENDED, "Extended" },
  3652. { FF_PROFILE_H264_HIGH, "High" },
  3653. { FF_PROFILE_H264_HIGH_10, "High 10" },
  3654. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  3655. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  3656. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  3657. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  3658. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  3659. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  3660. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  3661. { FF_PROFILE_UNKNOWN },
  3662. };
  3663. AVCodec ff_h264_decoder = {
  3664. .name = "h264",
  3665. .type = AVMEDIA_TYPE_VIDEO,
  3666. .id = AV_CODEC_ID_H264,
  3667. .priv_data_size = sizeof(H264Context),
  3668. .init = ff_h264_decode_init,
  3669. .close = h264_decode_end,
  3670. .decode = decode_frame,
  3671. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  3672. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  3673. CODEC_CAP_FRAME_THREADS,
  3674. .flush = flush_dpb,
  3675. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  3676. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  3677. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  3678. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3679. };
  3680. #if CONFIG_H264_VDPAU_DECODER
  3681. AVCodec ff_h264_vdpau_decoder = {
  3682. .name = "h264_vdpau",
  3683. .type = AVMEDIA_TYPE_VIDEO,
  3684. .id = AV_CODEC_ID_H264,
  3685. .priv_data_size = sizeof(H264Context),
  3686. .init = ff_h264_decode_init,
  3687. .close = h264_decode_end,
  3688. .decode = decode_frame,
  3689. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  3690. .flush = flush_dpb,
  3691. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  3692. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  3693. AV_PIX_FMT_NONE},
  3694. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3695. };
  3696. #endif