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.

4284 lines
166KB

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