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.

4353 lines
168KB

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