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.

4518 lines
173KB

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