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.

4133 lines
159KB

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