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.

4184 lines
161KB

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