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.

4117 lines
158KB

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