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.

1741 lines
59KB

  1. /*
  2. * MJPEG decoder
  3. * Copyright (c) 2000, 2001 Fabrice Bellard
  4. * Copyright (c) 2003 Alex Beregszaszi
  5. * Copyright (c) 2003-2004 Michael Niedermayer
  6. *
  7. * Support for external huffman table, various fixes (AVID workaround),
  8. * aspecting, new decode_frame mechanism and apple mjpeg-b support
  9. * by Alex Beregszaszi
  10. *
  11. * This file is part of Libav.
  12. *
  13. * Libav is free software; you can redistribute it and/or
  14. * modify it under the terms of the GNU Lesser General Public
  15. * License as published by the Free Software Foundation; either
  16. * version 2.1 of the License, or (at your option) any later version.
  17. *
  18. * Libav is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  21. * Lesser General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Lesser General Public
  24. * License along with Libav; if not, write to the Free Software
  25. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  26. */
  27. /**
  28. * @file
  29. * MJPEG decoder.
  30. */
  31. #include <assert.h>
  32. #include "libavutil/imgutils.h"
  33. #include "libavutil/opt.h"
  34. #include "avcodec.h"
  35. #include "blockdsp.h"
  36. #include "idctdsp.h"
  37. #include "internal.h"
  38. #include "mjpeg.h"
  39. #include "mjpegdec.h"
  40. #include "jpeglsdec.h"
  41. static int build_vlc(VLC *vlc, const uint8_t *bits_table,
  42. const uint8_t *val_table, int nb_codes,
  43. int use_static, int is_ac)
  44. {
  45. uint8_t huff_size[256] = { 0 };
  46. uint16_t huff_code[256];
  47. uint16_t huff_sym[256];
  48. int i;
  49. assert(nb_codes <= 256);
  50. ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
  51. for (i = 0; i < 256; i++)
  52. huff_sym[i] = i + 16 * is_ac;
  53. if (is_ac)
  54. huff_sym[0] = 16 * 256;
  55. return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
  56. huff_code, 2, 2, huff_sym, 2, 2, use_static);
  57. }
  58. static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)
  59. {
  60. build_vlc(&s->vlcs[0][0], avpriv_mjpeg_bits_dc_luminance,
  61. avpriv_mjpeg_val_dc, 12, 0, 0);
  62. build_vlc(&s->vlcs[0][1], avpriv_mjpeg_bits_dc_chrominance,
  63. avpriv_mjpeg_val_dc, 12, 0, 0);
  64. build_vlc(&s->vlcs[1][0], avpriv_mjpeg_bits_ac_luminance,
  65. avpriv_mjpeg_val_ac_luminance, 251, 0, 1);
  66. build_vlc(&s->vlcs[1][1], avpriv_mjpeg_bits_ac_chrominance,
  67. avpriv_mjpeg_val_ac_chrominance, 251, 0, 1);
  68. build_vlc(&s->vlcs[2][0], avpriv_mjpeg_bits_ac_luminance,
  69. avpriv_mjpeg_val_ac_luminance, 251, 0, 0);
  70. build_vlc(&s->vlcs[2][1], avpriv_mjpeg_bits_ac_chrominance,
  71. avpriv_mjpeg_val_ac_chrominance, 251, 0, 0);
  72. }
  73. av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
  74. {
  75. MJpegDecodeContext *s = avctx->priv_data;
  76. if (!s->picture_ptr) {
  77. s->picture = av_frame_alloc();
  78. if (!s->picture)
  79. return AVERROR(ENOMEM);
  80. s->picture_ptr = s->picture;
  81. }
  82. s->avctx = avctx;
  83. ff_blockdsp_init(&s->bdsp, avctx);
  84. ff_hpeldsp_init(&s->hdsp, avctx->flags);
  85. ff_idctdsp_init(&s->idsp, avctx);
  86. ff_init_scantable(s->idsp.idct_permutation, &s->scantable,
  87. ff_zigzag_direct);
  88. s->buffer_size = 0;
  89. s->buffer = NULL;
  90. s->start_code = -1;
  91. s->first_picture = 1;
  92. s->org_height = avctx->coded_height;
  93. avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
  94. avctx->colorspace = AVCOL_SPC_BT470BG;
  95. build_basic_mjpeg_vlc(s);
  96. if (s->extern_huff) {
  97. int ret;
  98. av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");
  99. init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
  100. if ((ret = ff_mjpeg_decode_dht(s))) {
  101. av_log(avctx, AV_LOG_ERROR,
  102. "mjpeg: error using external huffman table\n");
  103. return ret;
  104. }
  105. }
  106. if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
  107. s->interlace_polarity = 1; /* bottom field first */
  108. av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");
  109. }
  110. if (avctx->codec->id == AV_CODEC_ID_AMV)
  111. s->flipped = 1;
  112. return 0;
  113. }
  114. /* quantize tables */
  115. int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
  116. {
  117. int len, index, i, j;
  118. len = get_bits(&s->gb, 16) - 2;
  119. while (len >= 65) {
  120. /* only 8 bit precision handled */
  121. if (get_bits(&s->gb, 4) != 0) {
  122. av_log(s->avctx, AV_LOG_ERROR, "dqt: 16bit precision\n");
  123. return -1;
  124. }
  125. index = get_bits(&s->gb, 4);
  126. if (index >= 4)
  127. return -1;
  128. av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
  129. /* read quant table */
  130. for (i = 0; i < 64; i++) {
  131. j = s->scantable.permutated[i];
  132. s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
  133. }
  134. // XXX FIXME finetune, and perhaps add dc too
  135. s->qscale[index] = FFMAX(s->quant_matrixes[index][s->scantable.permutated[1]],
  136. s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
  137. av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
  138. index, s->qscale[index]);
  139. len -= 65;
  140. }
  141. return 0;
  142. }
  143. /* decode huffman tables and build VLC decoders */
  144. int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
  145. {
  146. int len, index, i, class, n, v, code_max;
  147. uint8_t bits_table[17];
  148. uint8_t val_table[256];
  149. int ret = 0;
  150. len = get_bits(&s->gb, 16) - 2;
  151. while (len > 0) {
  152. if (len < 17)
  153. return AVERROR_INVALIDDATA;
  154. class = get_bits(&s->gb, 4);
  155. if (class >= 2)
  156. return AVERROR_INVALIDDATA;
  157. index = get_bits(&s->gb, 4);
  158. if (index >= 4)
  159. return AVERROR_INVALIDDATA;
  160. n = 0;
  161. for (i = 1; i <= 16; i++) {
  162. bits_table[i] = get_bits(&s->gb, 8);
  163. n += bits_table[i];
  164. }
  165. len -= 17;
  166. if (len < n || n > 256)
  167. return AVERROR_INVALIDDATA;
  168. code_max = 0;
  169. for (i = 0; i < n; i++) {
  170. v = get_bits(&s->gb, 8);
  171. if (v > code_max)
  172. code_max = v;
  173. val_table[i] = v;
  174. }
  175. len -= n;
  176. /* build VLC and flush previous vlc if present */
  177. ff_free_vlc(&s->vlcs[class][index]);
  178. av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
  179. class, index, code_max + 1);
  180. if ((ret = build_vlc(&s->vlcs[class][index], bits_table, val_table,
  181. code_max + 1, 0, class > 0)) < 0)
  182. return ret;
  183. if (class > 0) {
  184. ff_free_vlc(&s->vlcs[2][index]);
  185. if ((ret = build_vlc(&s->vlcs[2][index], bits_table, val_table,
  186. code_max + 1, 0, 0)) < 0)
  187. return ret;
  188. }
  189. }
  190. return 0;
  191. }
  192. int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
  193. {
  194. int h_count[MAX_COMPONENTS] = { 0 };
  195. int v_count[MAX_COMPONENTS] = { 0 };
  196. int len, nb_components, i, width, height, bits, pix_fmt_id, ret;
  197. /* XXX: verify len field validity */
  198. len = get_bits(&s->gb, 16);
  199. bits = get_bits(&s->gb, 8);
  200. if (s->pegasus_rct)
  201. bits = 9;
  202. if (bits == 9 && !s->pegasus_rct)
  203. s->rct = 1; // FIXME ugly
  204. if (bits != 8 && !s->lossless) {
  205. av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
  206. return -1;
  207. }
  208. height = get_bits(&s->gb, 16);
  209. width = get_bits(&s->gb, 16);
  210. // HACK for odd_height.mov
  211. if (s->interlaced && s->width == width && s->height == height + 1)
  212. height= s->height;
  213. av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
  214. if (av_image_check_size(width, height, 0, s->avctx))
  215. return AVERROR_INVALIDDATA;
  216. nb_components = get_bits(&s->gb, 8);
  217. if (nb_components <= 0 ||
  218. nb_components > MAX_COMPONENTS)
  219. return -1;
  220. if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
  221. if (nb_components != s->nb_components) {
  222. av_log(s->avctx, AV_LOG_ERROR,
  223. "nb_components changing in interlaced picture\n");
  224. return AVERROR_INVALIDDATA;
  225. }
  226. }
  227. if (s->ls && !(bits <= 8 || nb_components == 1)) {
  228. avpriv_report_missing_feature(s->avctx,
  229. "JPEG-LS that is not <= 8 "
  230. "bits/component or 16-bit gray");
  231. return AVERROR_PATCHWELCOME;
  232. }
  233. s->nb_components = nb_components;
  234. s->h_max = 1;
  235. s->v_max = 1;
  236. for (i = 0; i < nb_components; i++) {
  237. /* component id */
  238. s->component_id[i] = get_bits(&s->gb, 8) - 1;
  239. h_count[i] = get_bits(&s->gb, 4);
  240. v_count[i] = get_bits(&s->gb, 4);
  241. /* compute hmax and vmax (only used in interleaved case) */
  242. if (h_count[i] > s->h_max)
  243. s->h_max = h_count[i];
  244. if (v_count[i] > s->v_max)
  245. s->v_max = v_count[i];
  246. s->quant_index[i] = get_bits(&s->gb, 8);
  247. if (s->quant_index[i] >= 4)
  248. return AVERROR_INVALIDDATA;
  249. if (!h_count[i] || !v_count[i]) {
  250. av_log(s->avctx, AV_LOG_ERROR,
  251. "Invalid sampling factor in component %d %d:%d\n",
  252. i, h_count[i], v_count[i]);
  253. return AVERROR_INVALIDDATA;
  254. }
  255. av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
  256. i, h_count[i], v_count[i],
  257. s->component_id[i], s->quant_index[i]);
  258. }
  259. if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
  260. avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
  261. return AVERROR_PATCHWELCOME;
  262. }
  263. if (s->v_max == 1 && s->h_max == 1 && s->lossless == 1)
  264. s->rgb = 1;
  265. /* if different size, realloc/alloc picture */
  266. if (width != s->width || height != s->height || bits != s->bits ||
  267. memcmp(s->h_count, h_count, sizeof(h_count)) ||
  268. memcmp(s->v_count, v_count, sizeof(v_count))) {
  269. s->width = width;
  270. s->height = height;
  271. s->bits = bits;
  272. memcpy(s->h_count, h_count, sizeof(h_count));
  273. memcpy(s->v_count, v_count, sizeof(v_count));
  274. s->interlaced = 0;
  275. /* test interlaced mode */
  276. if (s->first_picture &&
  277. s->org_height != 0 &&
  278. s->height < ((s->org_height * 3) / 4)) {
  279. s->interlaced = 1;
  280. s->bottom_field = s->interlace_polarity;
  281. s->picture_ptr->interlaced_frame = 1;
  282. s->picture_ptr->top_field_first = !s->interlace_polarity;
  283. height *= 2;
  284. }
  285. ret = ff_set_dimensions(s->avctx, width, height);
  286. if (ret < 0)
  287. return ret;
  288. s->first_picture = 0;
  289. }
  290. if (!(s->interlaced && (s->bottom_field == !s->interlace_polarity))) {
  291. /* XXX: not complete test ! */
  292. pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
  293. (s->h_count[1] << 20) | (s->v_count[1] << 16) |
  294. (s->h_count[2] << 12) | (s->v_count[2] << 8) |
  295. (s->h_count[3] << 4) | s->v_count[3];
  296. av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
  297. /* NOTE we do not allocate pictures large enough for the possible
  298. * padding of h/v_count being 4 */
  299. if (!(pix_fmt_id & 0xD0D0D0D0))
  300. pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
  301. if (!(pix_fmt_id & 0x0D0D0D0D))
  302. pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
  303. switch (pix_fmt_id) {
  304. case 0x11111100:
  305. if (s->rgb)
  306. s->avctx->pix_fmt = AV_PIX_FMT_BGRA;
  307. else {
  308. s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
  309. s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
  310. }
  311. assert(s->nb_components == 3);
  312. break;
  313. case 0x11000000:
  314. s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  315. break;
  316. case 0x12111100:
  317. s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
  318. s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
  319. break;
  320. case 0x21111100:
  321. s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
  322. s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
  323. break;
  324. case 0x22111100:
  325. s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
  326. s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
  327. break;
  328. default:
  329. av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
  330. return AVERROR_PATCHWELCOME;
  331. }
  332. if (s->ls) {
  333. if (s->nb_components > 1)
  334. s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
  335. else if (s->bits <= 8)
  336. s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  337. else
  338. s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
  339. }
  340. s->pix_desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
  341. if (!s->pix_desc) {
  342. av_log(s->avctx, AV_LOG_ERROR, "Could not get a pixel format descriptor.\n");
  343. return AVERROR_BUG;
  344. }
  345. av_frame_unref(s->picture_ptr);
  346. if (ff_get_buffer(s->avctx, s->picture_ptr, AV_GET_BUFFER_FLAG_REF) < 0) {
  347. av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  348. return -1;
  349. }
  350. s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
  351. s->picture_ptr->key_frame = 1;
  352. s->got_picture = 1;
  353. for (i = 0; i < 3; i++)
  354. s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
  355. av_dlog(s->avctx, "%d %d %d %d %d %d\n",
  356. s->width, s->height, s->linesize[0], s->linesize[1],
  357. s->interlaced, s->avctx->height);
  358. if (len != (8 + (3 * nb_components)))
  359. av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
  360. }
  361. /* totally blank picture as progressive JPEG will only add details to it */
  362. if (s->progressive) {
  363. int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
  364. int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
  365. for (i = 0; i < s->nb_components; i++) {
  366. int size = bw * bh * s->h_count[i] * s->v_count[i];
  367. av_freep(&s->blocks[i]);
  368. av_freep(&s->last_nnz[i]);
  369. s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
  370. s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
  371. s->block_stride[i] = bw * s->h_count[i];
  372. }
  373. memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
  374. }
  375. return 0;
  376. }
  377. static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
  378. {
  379. int code;
  380. code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
  381. if (code < 0) {
  382. av_log(s->avctx, AV_LOG_WARNING,
  383. "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
  384. 0, dc_index, &s->vlcs[0][dc_index]);
  385. return 0xffff;
  386. }
  387. if (code)
  388. return get_xbits(&s->gb, code);
  389. else
  390. return 0;
  391. }
  392. /* decode block and dequantize */
  393. static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
  394. int dc_index, int ac_index, int16_t *quant_matrix)
  395. {
  396. int code, i, j, level, val;
  397. /* DC coef */
  398. val = mjpeg_decode_dc(s, dc_index);
  399. if (val == 0xffff) {
  400. av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
  401. return AVERROR_INVALIDDATA;
  402. }
  403. val = val * quant_matrix[0] + s->last_dc[component];
  404. s->last_dc[component] = val;
  405. block[0] = val;
  406. /* AC coefs */
  407. i = 0;
  408. {OPEN_READER(re, &s->gb);
  409. do {
  410. UPDATE_CACHE(re, &s->gb);
  411. GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
  412. i += ((unsigned)code) >> 4;
  413. code &= 0xf;
  414. if (code) {
  415. if (code > MIN_CACHE_BITS - 16)
  416. UPDATE_CACHE(re, &s->gb);
  417. {
  418. int cache = GET_CACHE(re, &s->gb);
  419. int sign = (~cache) >> 31;
  420. level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
  421. }
  422. LAST_SKIP_BITS(re, &s->gb, code);
  423. if (i > 63) {
  424. av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
  425. return AVERROR_INVALIDDATA;
  426. }
  427. j = s->scantable.permutated[i];
  428. block[j] = level * quant_matrix[j];
  429. }
  430. } while (i < 63);
  431. CLOSE_READER(re, &s->gb);}
  432. return 0;
  433. }
  434. static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,
  435. int component, int dc_index,
  436. int16_t *quant_matrix, int Al)
  437. {
  438. int val;
  439. s->bdsp.clear_block(block);
  440. val = mjpeg_decode_dc(s, dc_index);
  441. if (val == 0xffff) {
  442. av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
  443. return AVERROR_INVALIDDATA;
  444. }
  445. val = (val * quant_matrix[0] << Al) + s->last_dc[component];
  446. s->last_dc[component] = val;
  447. block[0] = val;
  448. return 0;
  449. }
  450. /* decode block and dequantize - progressive JPEG version */
  451. static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
  452. uint8_t *last_nnz, int ac_index,
  453. int16_t *quant_matrix,
  454. int ss, int se, int Al, int *EOBRUN)
  455. {
  456. int code, i, j, level, val, run;
  457. if (*EOBRUN) {
  458. (*EOBRUN)--;
  459. return 0;
  460. }
  461. {
  462. OPEN_READER(re, &s->gb);
  463. for (i = ss; ; i++) {
  464. UPDATE_CACHE(re, &s->gb);
  465. GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
  466. run = ((unsigned) code) >> 4;
  467. code &= 0xF;
  468. if (code) {
  469. i += run;
  470. if (code > MIN_CACHE_BITS - 16)
  471. UPDATE_CACHE(re, &s->gb);
  472. {
  473. int cache = GET_CACHE(re, &s->gb);
  474. int sign = (~cache) >> 31;
  475. level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
  476. }
  477. LAST_SKIP_BITS(re, &s->gb, code);
  478. if (i >= se) {
  479. if (i == se) {
  480. j = s->scantable.permutated[se];
  481. block[j] = level * quant_matrix[j] << Al;
  482. break;
  483. }
  484. av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
  485. return AVERROR_INVALIDDATA;
  486. }
  487. j = s->scantable.permutated[i];
  488. block[j] = level * quant_matrix[j] << Al;
  489. } else {
  490. if (run == 0xF) {// ZRL - skip 15 coefficients
  491. i += 15;
  492. if (i >= se) {
  493. av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
  494. return AVERROR_INVALIDDATA;
  495. }
  496. } else {
  497. val = (1 << run);
  498. if (run) {
  499. UPDATE_CACHE(re, &s->gb);
  500. val += NEG_USR32(GET_CACHE(re, &s->gb), run);
  501. LAST_SKIP_BITS(re, &s->gb, run);
  502. }
  503. *EOBRUN = val - 1;
  504. break;
  505. }
  506. }
  507. }
  508. CLOSE_READER(re, &s->gb);
  509. }
  510. if (i > *last_nnz)
  511. *last_nnz = i;
  512. return 0;
  513. }
  514. #define REFINE_BIT(j) { \
  515. UPDATE_CACHE(re, &s->gb); \
  516. sign = block[j] >> 15; \
  517. block[j] += SHOW_UBITS(re, &s->gb, 1) * \
  518. ((quant_matrix[j] ^ sign) - sign) << Al; \
  519. LAST_SKIP_BITS(re, &s->gb, 1); \
  520. }
  521. #define ZERO_RUN \
  522. for (; ; i++) { \
  523. if (i > last) { \
  524. i += run; \
  525. if (i > se) { \
  526. av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
  527. return -1; \
  528. } \
  529. break; \
  530. } \
  531. j = s->scantable.permutated[i]; \
  532. if (block[j]) \
  533. REFINE_BIT(j) \
  534. else if (run-- == 0) \
  535. break; \
  536. }
  537. /* decode block and dequantize - progressive JPEG refinement pass */
  538. static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,
  539. uint8_t *last_nnz,
  540. int ac_index, int16_t *quant_matrix,
  541. int ss, int se, int Al, int *EOBRUN)
  542. {
  543. int code, i = ss, j, sign, val, run;
  544. int last = FFMIN(se, *last_nnz);
  545. OPEN_READER(re, &s->gb);
  546. if (*EOBRUN) {
  547. (*EOBRUN)--;
  548. } else {
  549. for (; ; i++) {
  550. UPDATE_CACHE(re, &s->gb);
  551. GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
  552. if (code & 0xF) {
  553. run = ((unsigned) code) >> 4;
  554. UPDATE_CACHE(re, &s->gb);
  555. val = SHOW_UBITS(re, &s->gb, 1);
  556. LAST_SKIP_BITS(re, &s->gb, 1);
  557. ZERO_RUN;
  558. j = s->scantable.permutated[i];
  559. val--;
  560. block[j] = ((quant_matrix[j]^val) - val) << Al;
  561. if (i == se) {
  562. if (i > *last_nnz)
  563. *last_nnz = i;
  564. CLOSE_READER(re, &s->gb);
  565. return 0;
  566. }
  567. } else {
  568. run = ((unsigned) code) >> 4;
  569. if (run == 0xF) {
  570. ZERO_RUN;
  571. } else {
  572. val = run;
  573. run = (1 << run);
  574. if (val) {
  575. UPDATE_CACHE(re, &s->gb);
  576. run += SHOW_UBITS(re, &s->gb, val);
  577. LAST_SKIP_BITS(re, &s->gb, val);
  578. }
  579. *EOBRUN = run - 1;
  580. break;
  581. }
  582. }
  583. }
  584. if (i > *last_nnz)
  585. *last_nnz = i;
  586. }
  587. for (; i <= last; i++) {
  588. j = s->scantable.permutated[i];
  589. if (block[j])
  590. REFINE_BIT(j)
  591. }
  592. CLOSE_READER(re, &s->gb);
  593. return 0;
  594. }
  595. #undef REFINE_BIT
  596. #undef ZERO_RUN
  597. static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor,
  598. int point_transform)
  599. {
  600. int i, mb_x, mb_y;
  601. uint16_t (*buffer)[4];
  602. int left[3], top[3], topleft[3];
  603. const int linesize = s->linesize[0];
  604. const int mask = (1 << s->bits) - 1;
  605. av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
  606. (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
  607. buffer = s->ljpeg_buffer;
  608. for (i = 0; i < 3; i++)
  609. buffer[0][i] = 1 << (s->bits + point_transform - 1);
  610. for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
  611. const int modified_predictor = mb_y ? predictor : 1;
  612. uint8_t *ptr = s->picture_ptr->data[0] + (linesize * mb_y);
  613. if (s->interlaced && s->bottom_field)
  614. ptr += linesize >> 1;
  615. for (i = 0; i < 3; i++)
  616. top[i] = left[i] = topleft[i] = buffer[0][i];
  617. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  618. if (s->restart_interval && !s->restart_count)
  619. s->restart_count = s->restart_interval;
  620. for (i = 0; i < 3; i++) {
  621. int pred;
  622. topleft[i] = top[i];
  623. top[i] = buffer[mb_x][i];
  624. PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
  625. left[i] = buffer[mb_x][i] =
  626. mask & (pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform));
  627. }
  628. if (s->restart_interval && !--s->restart_count) {
  629. align_get_bits(&s->gb);
  630. skip_bits(&s->gb, 16); /* skip RSTn */
  631. }
  632. }
  633. if (s->rct) {
  634. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  635. ptr[4 * mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
  636. ptr[4 * mb_x + 0] = buffer[mb_x][1] + ptr[4 * mb_x + 1];
  637. ptr[4 * mb_x + 2] = buffer[mb_x][2] + ptr[4 * mb_x + 1];
  638. }
  639. } else if (s->pegasus_rct) {
  640. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  641. ptr[4 * mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
  642. ptr[4 * mb_x + 0] = buffer[mb_x][1] + ptr[4 * mb_x + 1];
  643. ptr[4 * mb_x + 2] = buffer[mb_x][2] + ptr[4 * mb_x + 1];
  644. }
  645. } else {
  646. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  647. ptr[4 * mb_x + 0] = buffer[mb_x][2];
  648. ptr[4 * mb_x + 1] = buffer[mb_x][1];
  649. ptr[4 * mb_x + 2] = buffer[mb_x][0];
  650. }
  651. }
  652. }
  653. return 0;
  654. }
  655. static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
  656. int point_transform, int nb_components)
  657. {
  658. int i, mb_x, mb_y;
  659. for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
  660. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  661. if (s->restart_interval && !s->restart_count)
  662. s->restart_count = s->restart_interval;
  663. if (mb_x == 0 || mb_y == 0 || s->interlaced) {
  664. for (i = 0; i < nb_components; i++) {
  665. uint8_t *ptr;
  666. int n, h, v, x, y, c, j, linesize;
  667. n = s->nb_blocks[i];
  668. c = s->comp_index[i];
  669. h = s->h_scount[i];
  670. v = s->v_scount[i];
  671. x = 0;
  672. y = 0;
  673. linesize = s->linesize[c];
  674. for (j = 0; j < n; j++) {
  675. int pred;
  676. // FIXME optimize this crap
  677. ptr = s->picture_ptr->data[c] +
  678. (linesize * (v * mb_y + y)) +
  679. (h * mb_x + x);
  680. if (y == 0 && mb_y == 0) {
  681. if (x == 0 && mb_x == 0)
  682. pred = 128 << point_transform;
  683. else
  684. pred = ptr[-1];
  685. } else {
  686. if (x == 0 && mb_x == 0)
  687. pred = ptr[-linesize];
  688. else
  689. PREDICT(pred, ptr[-linesize - 1],
  690. ptr[-linesize], ptr[-1], predictor);
  691. }
  692. if (s->interlaced && s->bottom_field)
  693. ptr += linesize >> 1;
  694. *ptr = pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
  695. if (++x == h) {
  696. x = 0;
  697. y++;
  698. }
  699. }
  700. }
  701. } else {
  702. for (i = 0; i < nb_components; i++) {
  703. uint8_t *ptr;
  704. int n, h, v, x, y, c, j, linesize;
  705. n = s->nb_blocks[i];
  706. c = s->comp_index[i];
  707. h = s->h_scount[i];
  708. v = s->v_scount[i];
  709. x = 0;
  710. y = 0;
  711. linesize = s->linesize[c];
  712. for (j = 0; j < n; j++) {
  713. int pred;
  714. // FIXME optimize this crap
  715. ptr = s->picture_ptr->data[c] +
  716. (linesize * (v * mb_y + y)) +
  717. (h * mb_x + x);
  718. PREDICT(pred, ptr[-linesize - 1],
  719. ptr[-linesize], ptr[-1], predictor);
  720. *ptr = pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
  721. if (++x == h) {
  722. x = 0;
  723. y++;
  724. }
  725. }
  726. }
  727. }
  728. if (s->restart_interval && !--s->restart_count) {
  729. align_get_bits(&s->gb);
  730. skip_bits(&s->gb, 16); /* skip RSTn */
  731. }
  732. }
  733. }
  734. return 0;
  735. }
  736. static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
  737. int Al, const uint8_t *mb_bitmask,
  738. const AVFrame *reference)
  739. {
  740. int i, mb_x, mb_y;
  741. uint8_t *data[MAX_COMPONENTS];
  742. const uint8_t *reference_data[MAX_COMPONENTS];
  743. int linesize[MAX_COMPONENTS];
  744. GetBitContext mb_bitmask_gb;
  745. if (mb_bitmask)
  746. init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
  747. for (i = 0; i < nb_components; i++) {
  748. int c = s->comp_index[i];
  749. data[c] = s->picture_ptr->data[c];
  750. reference_data[c] = reference ? reference->data[c] : NULL;
  751. linesize[c] = s->linesize[c];
  752. s->coefs_finished[c] |= 1;
  753. }
  754. for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
  755. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  756. const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
  757. if (s->restart_interval && !s->restart_count)
  758. s->restart_count = s->restart_interval;
  759. if (get_bits_left(&s->gb) < 0) {
  760. av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
  761. -get_bits_left(&s->gb));
  762. return AVERROR_INVALIDDATA;
  763. }
  764. for (i = 0; i < nb_components; i++) {
  765. uint8_t *ptr;
  766. int n, h, v, x, y, c, j;
  767. int block_offset;
  768. n = s->nb_blocks[i];
  769. c = s->comp_index[i];
  770. h = s->h_scount[i];
  771. v = s->v_scount[i];
  772. x = 0;
  773. y = 0;
  774. for (j = 0; j < n; j++) {
  775. block_offset = ((linesize[c] * (v * mb_y + y) * 8) +
  776. (h * mb_x + x) * 8);
  777. if (s->interlaced && s->bottom_field)
  778. block_offset += linesize[c] >> 1;
  779. ptr = data[c] + block_offset;
  780. if (!s->progressive) {
  781. if (copy_mb)
  782. s->hdsp.put_pixels_tab[1][0](ptr,
  783. reference_data[c] + block_offset,
  784. linesize[c], 8);
  785. else {
  786. s->bdsp.clear_block(s->block);
  787. if (decode_block(s, s->block, i,
  788. s->dc_index[i], s->ac_index[i],
  789. s->quant_matrixes[s->quant_index[c]]) < 0) {
  790. av_log(s->avctx, AV_LOG_ERROR,
  791. "error y=%d x=%d\n", mb_y, mb_x);
  792. return AVERROR_INVALIDDATA;
  793. }
  794. s->idsp.idct_put(ptr, linesize[c], s->block);
  795. }
  796. } else {
  797. int block_idx = s->block_stride[c] * (v * mb_y + y) +
  798. (h * mb_x + x);
  799. int16_t *block = s->blocks[c][block_idx];
  800. if (Ah)
  801. block[0] += get_bits1(&s->gb) *
  802. s->quant_matrixes[s->quant_index[c]][0] << Al;
  803. else if (decode_dc_progressive(s, block, i, s->dc_index[i],
  804. s->quant_matrixes[s->quant_index[c]],
  805. Al) < 0) {
  806. av_log(s->avctx, AV_LOG_ERROR,
  807. "error y=%d x=%d\n", mb_y, mb_x);
  808. return AVERROR_INVALIDDATA;
  809. }
  810. }
  811. av_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
  812. av_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
  813. mb_x, mb_y, x, y, c, s->bottom_field,
  814. (v * mb_y + y) * 8, (h * mb_x + x) * 8);
  815. if (++x == h) {
  816. x = 0;
  817. y++;
  818. }
  819. }
  820. }
  821. if (s->restart_interval) {
  822. s->restart_count--;
  823. i = 8 + ((-get_bits_count(&s->gb)) & 7);
  824. /* skip RSTn */
  825. if (show_bits(&s->gb, i) == (1 << i) - 1) {
  826. int pos = get_bits_count(&s->gb);
  827. align_get_bits(&s->gb);
  828. while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
  829. skip_bits(&s->gb, 8);
  830. if ((get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
  831. for (i = 0; i < nb_components; i++) /* reset dc */
  832. s->last_dc[i] = 1024;
  833. } else
  834. skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
  835. }
  836. }
  837. }
  838. }
  839. return 0;
  840. }
  841. static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
  842. int se, int Ah, int Al,
  843. const uint8_t *mb_bitmask,
  844. const AVFrame *reference)
  845. {
  846. int mb_x, mb_y;
  847. int EOBRUN = 0;
  848. int c = s->comp_index[0];
  849. uint8_t *data = s->picture_ptr->data[c];
  850. const uint8_t *reference_data = reference ? reference->data[c] : NULL;
  851. int linesize = s->linesize[c];
  852. int last_scan = 0;
  853. int16_t *quant_matrix = s->quant_matrixes[s->quant_index[c]];
  854. GetBitContext mb_bitmask_gb;
  855. if (ss < 0 || ss >= 64 ||
  856. se < ss || se >= 64 ||
  857. Ah < 0 || Al < 0)
  858. return AVERROR_INVALIDDATA;
  859. if (mb_bitmask)
  860. init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
  861. if (!Al) {
  862. // s->coefs_finished is a bitmask for coefficients coded
  863. // ss and se are parameters telling start and end coefficients
  864. s->coefs_finished[c] |= (~0ULL >> (63 - (se - ss))) << ss;
  865. last_scan = !~s->coefs_finished[c];
  866. }
  867. if (s->interlaced && s->bottom_field) {
  868. int offset = linesize >> 1;
  869. data += offset;
  870. reference_data += offset;
  871. }
  872. for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
  873. int block_offset = mb_y * linesize * 8;
  874. uint8_t *ptr = data + block_offset;
  875. int block_idx = mb_y * s->block_stride[c];
  876. int16_t (*block)[64] = &s->blocks[c][block_idx];
  877. uint8_t *last_nnz = &s->last_nnz[c][block_idx];
  878. for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
  879. const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
  880. if (!copy_mb) {
  881. int ret;
  882. if (Ah)
  883. ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
  884. quant_matrix, ss, se, Al, &EOBRUN);
  885. else
  886. ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
  887. quant_matrix, ss, se, Al, &EOBRUN);
  888. if (ret < 0) {
  889. av_log(s->avctx, AV_LOG_ERROR,
  890. "error y=%d x=%d\n", mb_y, mb_x);
  891. return AVERROR_INVALIDDATA;
  892. }
  893. }
  894. if (last_scan) {
  895. if (copy_mb) {
  896. s->hdsp.put_pixels_tab[1][0](ptr,
  897. reference_data + block_offset,
  898. linesize, 8);
  899. } else {
  900. s->idsp.idct_put(ptr, linesize, *block);
  901. ptr += 8;
  902. }
  903. }
  904. }
  905. }
  906. return 0;
  907. }
  908. int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
  909. const AVFrame *reference)
  910. {
  911. int len, nb_components, i, h, v, predictor, point_transform;
  912. int index, id, ret;
  913. const int block_size = s->lossless ? 1 : 8;
  914. int ilv, prev_shift;
  915. /* XXX: verify len field validity */
  916. len = get_bits(&s->gb, 16);
  917. nb_components = get_bits(&s->gb, 8);
  918. if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
  919. av_log(s->avctx, AV_LOG_ERROR,
  920. "decode_sos: nb_components (%d) unsupported\n", nb_components);
  921. return AVERROR_PATCHWELCOME;
  922. }
  923. if (len != 6 + 2 * nb_components) {
  924. av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
  925. return AVERROR_INVALIDDATA;
  926. }
  927. for (i = 0; i < nb_components; i++) {
  928. id = get_bits(&s->gb, 8) - 1;
  929. av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
  930. /* find component index */
  931. for (index = 0; index < s->nb_components; index++)
  932. if (id == s->component_id[index])
  933. break;
  934. if (index == s->nb_components) {
  935. av_log(s->avctx, AV_LOG_ERROR,
  936. "decode_sos: index(%d) out of components\n", index);
  937. return AVERROR_INVALIDDATA;
  938. }
  939. /* Metasoft MJPEG codec has Cb and Cr swapped */
  940. if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
  941. && nb_components == 3 && s->nb_components == 3 && i)
  942. index = 3 - i;
  943. s->comp_index[i] = index;
  944. s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
  945. s->h_scount[i] = s->h_count[index];
  946. s->v_scount[i] = s->v_count[index];
  947. s->dc_index[i] = get_bits(&s->gb, 4);
  948. s->ac_index[i] = get_bits(&s->gb, 4);
  949. if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
  950. s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
  951. goto out_of_range;
  952. if (!s->vlcs[0][s->dc_index[i]].table ||
  953. !s->vlcs[1][s->ac_index[i]].table)
  954. goto out_of_range;
  955. }
  956. predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
  957. ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
  958. prev_shift = get_bits(&s->gb, 4); /* Ah */
  959. point_transform = get_bits(&s->gb, 4); /* Al */
  960. if (nb_components > 1) {
  961. /* interleaved stream */
  962. s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
  963. s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
  964. } else if (!s->ls) { /* skip this for JPEG-LS */
  965. h = s->h_max / s->h_scount[0];
  966. v = s->v_max / s->v_scount[0];
  967. s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
  968. s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
  969. s->nb_blocks[0] = 1;
  970. s->h_scount[0] = 1;
  971. s->v_scount[0] = 1;
  972. }
  973. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  974. av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d %s\n",
  975. s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
  976. predictor, point_transform, ilv, s->bits,
  977. s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
  978. /* mjpeg-b can have padding bytes between sos and image data, skip them */
  979. for (i = s->mjpb_skiptosod; i > 0; i--)
  980. skip_bits(&s->gb, 8);
  981. next_field:
  982. for (i = 0; i < nb_components; i++)
  983. s->last_dc[i] = 1024;
  984. if (s->lossless) {
  985. if (CONFIG_JPEGLS_DECODER && s->ls) {
  986. // for () {
  987. // reset_ls_coding_parameters(s, 0);
  988. if ((ret = ff_jpegls_decode_picture(s, predictor,
  989. point_transform, ilv)) < 0)
  990. return ret;
  991. } else {
  992. if (s->rgb) {
  993. if ((ret = ljpeg_decode_rgb_scan(s, predictor,
  994. point_transform)) < 0)
  995. return ret;
  996. } else {
  997. if ((ret = ljpeg_decode_yuv_scan(s, predictor,
  998. point_transform,
  999. nb_components)) < 0)
  1000. return ret;
  1001. }
  1002. }
  1003. } else {
  1004. if (s->progressive && predictor) {
  1005. if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
  1006. ilv, prev_shift,
  1007. point_transform,
  1008. mb_bitmask,
  1009. reference)) < 0)
  1010. return ret;
  1011. } else {
  1012. if ((ret = mjpeg_decode_scan(s, nb_components,
  1013. prev_shift, point_transform,
  1014. mb_bitmask, reference)) < 0)
  1015. return ret;
  1016. }
  1017. }
  1018. if (s->interlaced &&
  1019. get_bits_left(&s->gb) > 32 &&
  1020. show_bits(&s->gb, 8) == 0xFF) {
  1021. GetBitContext bak = s->gb;
  1022. align_get_bits(&bak);
  1023. if (show_bits(&bak, 16) == 0xFFD1) {
  1024. av_dlog(s->avctx, "AVRn interlaced picture marker found\n");
  1025. s->gb = bak;
  1026. skip_bits(&s->gb, 16);
  1027. s->bottom_field ^= 1;
  1028. goto next_field;
  1029. }
  1030. }
  1031. emms_c();
  1032. return 0;
  1033. out_of_range:
  1034. av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
  1035. return AVERROR_INVALIDDATA;
  1036. }
  1037. static int mjpeg_decode_dri(MJpegDecodeContext *s)
  1038. {
  1039. if (get_bits(&s->gb, 16) != 4)
  1040. return AVERROR_INVALIDDATA;
  1041. s->restart_interval = get_bits(&s->gb, 16);
  1042. s->restart_count = 0;
  1043. av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
  1044. s->restart_interval);
  1045. return 0;
  1046. }
  1047. static int mjpeg_decode_app(MJpegDecodeContext *s)
  1048. {
  1049. int len, id, i;
  1050. len = get_bits(&s->gb, 16);
  1051. if (len < 5)
  1052. return AVERROR_INVALIDDATA;
  1053. if (8 * len > get_bits_left(&s->gb))
  1054. return AVERROR_INVALIDDATA;
  1055. id = get_bits_long(&s->gb, 32);
  1056. id = av_be2ne32(id);
  1057. len -= 6;
  1058. if (s->avctx->debug & FF_DEBUG_STARTCODE)
  1059. av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
  1060. /* Buggy AVID, it puts EOI only at every 10th frame. */
  1061. /* Also, this fourcc is used by non-avid files too, it holds some
  1062. information, but it's always present in AVID-created files. */
  1063. if (id == AV_RL32("AVI1")) {
  1064. /* structure:
  1065. 4bytes AVI1
  1066. 1bytes polarity
  1067. 1bytes always zero
  1068. 4bytes field_size
  1069. 4bytes field_size_less_padding
  1070. */
  1071. s->buggy_avid = 1;
  1072. i = get_bits(&s->gb, 8);
  1073. if (i == 2)
  1074. s->bottom_field = 1;
  1075. else if (i == 1)
  1076. s->bottom_field = 0;
  1077. #if 0
  1078. skip_bits(&s->gb, 8);
  1079. skip_bits(&s->gb, 32);
  1080. skip_bits(&s->gb, 32);
  1081. len -= 10;
  1082. #endif
  1083. goto out;
  1084. }
  1085. // len -= 2;
  1086. if (id == AV_RL32("JFIF")) {
  1087. int t_w, t_h, v1, v2;
  1088. skip_bits(&s->gb, 8); /* the trailing zero-byte */
  1089. v1 = get_bits(&s->gb, 8);
  1090. v2 = get_bits(&s->gb, 8);
  1091. skip_bits(&s->gb, 8);
  1092. s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
  1093. s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
  1094. ff_set_sar(s->avctx, s->avctx->sample_aspect_ratio);
  1095. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1096. av_log(s->avctx, AV_LOG_INFO,
  1097. "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
  1098. v1, v2,
  1099. s->avctx->sample_aspect_ratio.num,
  1100. s->avctx->sample_aspect_ratio.den);
  1101. t_w = get_bits(&s->gb, 8);
  1102. t_h = get_bits(&s->gb, 8);
  1103. if (t_w && t_h) {
  1104. /* skip thumbnail */
  1105. if (len -10 - (t_w * t_h * 3) > 0)
  1106. len -= t_w * t_h * 3;
  1107. }
  1108. len -= 10;
  1109. goto out;
  1110. }
  1111. if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
  1112. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1113. av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
  1114. skip_bits(&s->gb, 16); /* version */
  1115. skip_bits(&s->gb, 16); /* flags0 */
  1116. skip_bits(&s->gb, 16); /* flags1 */
  1117. skip_bits(&s->gb, 8); /* transform */
  1118. len -= 7;
  1119. goto out;
  1120. }
  1121. if (id == AV_RL32("LJIF")) {
  1122. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1123. av_log(s->avctx, AV_LOG_INFO,
  1124. "Pegasus lossless jpeg header found\n");
  1125. skip_bits(&s->gb, 16); /* version ? */
  1126. skip_bits(&s->gb, 16); /* unknwon always 0? */
  1127. skip_bits(&s->gb, 16); /* unknwon always 0? */
  1128. skip_bits(&s->gb, 16); /* unknwon always 0? */
  1129. switch (get_bits(&s->gb, 8)) {
  1130. case 1:
  1131. s->rgb = 1;
  1132. s->pegasus_rct = 0;
  1133. break;
  1134. case 2:
  1135. s->rgb = 1;
  1136. s->pegasus_rct = 1;
  1137. break;
  1138. default:
  1139. av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
  1140. }
  1141. len -= 9;
  1142. goto out;
  1143. }
  1144. /* Apple MJPEG-A */
  1145. if ((s->start_code == APP1) && (len > (0x28 - 8))) {
  1146. id = get_bits_long(&s->gb, 32);
  1147. id = av_be2ne32(id);
  1148. len -= 4;
  1149. /* Apple MJPEG-A */
  1150. if (id == AV_RL32("mjpg")) {
  1151. #if 0
  1152. skip_bits(&s->gb, 32); /* field size */
  1153. skip_bits(&s->gb, 32); /* pad field size */
  1154. skip_bits(&s->gb, 32); /* next off */
  1155. skip_bits(&s->gb, 32); /* quant off */
  1156. skip_bits(&s->gb, 32); /* huff off */
  1157. skip_bits(&s->gb, 32); /* image off */
  1158. skip_bits(&s->gb, 32); /* scan off */
  1159. skip_bits(&s->gb, 32); /* data off */
  1160. #endif
  1161. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1162. av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
  1163. }
  1164. }
  1165. out:
  1166. /* slow but needed for extreme adobe jpegs */
  1167. if (len < 0)
  1168. av_log(s->avctx, AV_LOG_ERROR,
  1169. "mjpeg: error, decode_app parser read over the end\n");
  1170. while (--len > 0)
  1171. skip_bits(&s->gb, 8);
  1172. return 0;
  1173. }
  1174. static int mjpeg_decode_com(MJpegDecodeContext *s)
  1175. {
  1176. int len = get_bits(&s->gb, 16);
  1177. if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
  1178. char *cbuf = av_malloc(len - 1);
  1179. if (cbuf) {
  1180. int i;
  1181. for (i = 0; i < len - 2; i++)
  1182. cbuf[i] = get_bits(&s->gb, 8);
  1183. if (i > 0 && cbuf[i - 1] == '\n')
  1184. cbuf[i - 1] = 0;
  1185. else
  1186. cbuf[i] = 0;
  1187. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1188. av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
  1189. /* buggy avid, it puts EOI only at every 10th frame */
  1190. if (!strcmp(cbuf, "AVID")) {
  1191. s->buggy_avid = 1;
  1192. } else if (!strcmp(cbuf, "CS=ITU601"))
  1193. s->cs_itu601 = 1;
  1194. else if ((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
  1195. (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
  1196. s->flipped = 1;
  1197. av_free(cbuf);
  1198. }
  1199. }
  1200. return 0;
  1201. }
  1202. /* return the 8 bit start code value and update the search
  1203. state. Return -1 if no start code found */
  1204. static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
  1205. {
  1206. const uint8_t *buf_ptr;
  1207. unsigned int v, v2;
  1208. int val;
  1209. #ifdef DEBUG
  1210. int skipped = 0;
  1211. #endif
  1212. buf_ptr = *pbuf_ptr;
  1213. while (buf_ptr < buf_end) {
  1214. v = *buf_ptr++;
  1215. v2 = *buf_ptr;
  1216. if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
  1217. val = *buf_ptr++;
  1218. goto found;
  1219. }
  1220. #ifdef DEBUG
  1221. skipped++;
  1222. #endif
  1223. }
  1224. val = -1;
  1225. found:
  1226. av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
  1227. *pbuf_ptr = buf_ptr;
  1228. return val;
  1229. }
  1230. int ff_mjpeg_find_marker(MJpegDecodeContext *s,
  1231. const uint8_t **buf_ptr, const uint8_t *buf_end,
  1232. const uint8_t **unescaped_buf_ptr,
  1233. int *unescaped_buf_size)
  1234. {
  1235. int start_code;
  1236. start_code = find_marker(buf_ptr, buf_end);
  1237. av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
  1238. if (!s->buffer)
  1239. return AVERROR(ENOMEM);
  1240. /* unescape buffer of SOS, use special treatment for JPEG-LS */
  1241. if (start_code == SOS && !s->ls) {
  1242. const uint8_t *src = *buf_ptr;
  1243. uint8_t *dst = s->buffer;
  1244. while (src < buf_end) {
  1245. uint8_t x = *(src++);
  1246. *(dst++) = x;
  1247. if (s->avctx->codec_id != AV_CODEC_ID_THP) {
  1248. if (x == 0xff) {
  1249. while (src < buf_end && x == 0xff)
  1250. x = *(src++);
  1251. if (x >= 0xd0 && x <= 0xd7)
  1252. *(dst++) = x;
  1253. else if (x)
  1254. break;
  1255. }
  1256. }
  1257. }
  1258. *unescaped_buf_ptr = s->buffer;
  1259. *unescaped_buf_size = dst - s->buffer;
  1260. memset(s->buffer + *unescaped_buf_size, 0,
  1261. FF_INPUT_BUFFER_PADDING_SIZE);
  1262. av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
  1263. (buf_end - *buf_ptr) - (dst - s->buffer));
  1264. } else if (start_code == SOS && s->ls) {
  1265. const uint8_t *src = *buf_ptr;
  1266. uint8_t *dst = s->buffer;
  1267. int bit_count = 0;
  1268. int t = 0, b = 0;
  1269. PutBitContext pb;
  1270. s->cur_scan++;
  1271. /* find marker */
  1272. while (src + t < buf_end) {
  1273. uint8_t x = src[t++];
  1274. if (x == 0xff) {
  1275. while ((src + t < buf_end) && x == 0xff)
  1276. x = src[t++];
  1277. if (x & 0x80) {
  1278. t -= 2;
  1279. break;
  1280. }
  1281. }
  1282. }
  1283. bit_count = t * 8;
  1284. init_put_bits(&pb, dst, t);
  1285. /* unescape bitstream */
  1286. while (b < t) {
  1287. uint8_t x = src[b++];
  1288. put_bits(&pb, 8, x);
  1289. if (x == 0xFF) {
  1290. x = src[b++];
  1291. put_bits(&pb, 7, x);
  1292. bit_count--;
  1293. }
  1294. }
  1295. flush_put_bits(&pb);
  1296. *unescaped_buf_ptr = dst;
  1297. *unescaped_buf_size = (bit_count + 7) >> 3;
  1298. memset(s->buffer + *unescaped_buf_size, 0,
  1299. FF_INPUT_BUFFER_PADDING_SIZE);
  1300. } else {
  1301. *unescaped_buf_ptr = *buf_ptr;
  1302. *unescaped_buf_size = buf_end - *buf_ptr;
  1303. }
  1304. return start_code;
  1305. }
  1306. int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
  1307. AVPacket *avpkt)
  1308. {
  1309. AVFrame *frame = data;
  1310. const uint8_t *buf = avpkt->data;
  1311. int buf_size = avpkt->size;
  1312. MJpegDecodeContext *s = avctx->priv_data;
  1313. const uint8_t *buf_end, *buf_ptr;
  1314. const uint8_t *unescaped_buf_ptr;
  1315. int unescaped_buf_size;
  1316. int start_code;
  1317. int ret = 0;
  1318. s->got_picture = 0; // picture from previous image can not be reused
  1319. buf_ptr = buf;
  1320. buf_end = buf + buf_size;
  1321. while (buf_ptr < buf_end) {
  1322. /* find start next marker */
  1323. start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
  1324. &unescaped_buf_ptr,
  1325. &unescaped_buf_size);
  1326. /* EOF */
  1327. if (start_code < 0) {
  1328. goto the_end;
  1329. } else if (unescaped_buf_size > INT_MAX / 8) {
  1330. av_log(avctx, AV_LOG_ERROR,
  1331. "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
  1332. start_code, unescaped_buf_size, buf_size);
  1333. return AVERROR_INVALIDDATA;
  1334. }
  1335. av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
  1336. start_code, buf_end - buf_ptr);
  1337. ret = init_get_bits(&s->gb, unescaped_buf_ptr,
  1338. unescaped_buf_size * 8);
  1339. if (ret < 0)
  1340. return ret;
  1341. s->start_code = start_code;
  1342. if (s->avctx->debug & FF_DEBUG_STARTCODE)
  1343. av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
  1344. /* process markers */
  1345. if (start_code >= 0xd0 && start_code <= 0xd7)
  1346. av_log(avctx, AV_LOG_DEBUG,
  1347. "restart marker: %d\n", start_code & 0x0f);
  1348. /* APP fields */
  1349. else if (start_code >= APP0 && start_code <= APP15)
  1350. mjpeg_decode_app(s);
  1351. /* Comment */
  1352. else if (start_code == COM)
  1353. mjpeg_decode_com(s);
  1354. if (!CONFIG_JPEGLS_DECODER &&
  1355. (start_code == SOF48 || start_code == LSE)) {
  1356. av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
  1357. return AVERROR(ENOSYS);
  1358. }
  1359. switch (start_code) {
  1360. case SOI:
  1361. s->restart_interval = 0;
  1362. s->restart_count = 0;
  1363. /* nothing to do on SOI */
  1364. break;
  1365. case DQT:
  1366. ff_mjpeg_decode_dqt(s);
  1367. break;
  1368. case DHT:
  1369. if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
  1370. av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
  1371. return ret;
  1372. }
  1373. break;
  1374. case SOF0:
  1375. case SOF1:
  1376. s->lossless = 0;
  1377. s->ls = 0;
  1378. s->progressive = 0;
  1379. if ((ret = ff_mjpeg_decode_sof(s)) < 0)
  1380. return ret;
  1381. break;
  1382. case SOF2:
  1383. s->lossless = 0;
  1384. s->ls = 0;
  1385. s->progressive = 1;
  1386. if ((ret = ff_mjpeg_decode_sof(s)) < 0)
  1387. return ret;
  1388. break;
  1389. case SOF3:
  1390. s->lossless = 1;
  1391. s->ls = 0;
  1392. s->progressive = 0;
  1393. if ((ret = ff_mjpeg_decode_sof(s)) < 0)
  1394. return ret;
  1395. break;
  1396. case SOF48:
  1397. s->lossless = 1;
  1398. s->ls = 1;
  1399. s->progressive = 0;
  1400. if ((ret = ff_mjpeg_decode_sof(s)) < 0)
  1401. return ret;
  1402. break;
  1403. case LSE:
  1404. if (!CONFIG_JPEGLS_DECODER ||
  1405. (ret = ff_jpegls_decode_lse(s)) < 0)
  1406. return ret;
  1407. break;
  1408. case EOI:
  1409. s->cur_scan = 0;
  1410. if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
  1411. break;
  1412. eoi_parser:
  1413. if (!s->got_picture) {
  1414. av_log(avctx, AV_LOG_WARNING,
  1415. "Found EOI before any SOF, ignoring\n");
  1416. break;
  1417. }
  1418. if (s->interlaced) {
  1419. s->bottom_field ^= 1;
  1420. /* if not bottom field, do not output image yet */
  1421. if (s->bottom_field == !s->interlace_polarity)
  1422. goto not_the_end;
  1423. }
  1424. if ((ret = av_frame_ref(frame, s->picture_ptr)) < 0)
  1425. return ret;
  1426. if (s->flipped) {
  1427. int i;
  1428. for (i = 0; frame->data[i]; i++) {
  1429. int h = frame->height >> ((i == 1 || i == 2) ?
  1430. s->pix_desc->log2_chroma_h : 0);
  1431. frame->data[i] += frame->linesize[i] * (h - 1);
  1432. frame->linesize[i] *= -1;
  1433. }
  1434. }
  1435. *got_frame = 1;
  1436. if (!s->lossless &&
  1437. avctx->debug & FF_DEBUG_QP) {
  1438. av_log(avctx, AV_LOG_DEBUG,
  1439. "QP: %d\n", FFMAX3(s->qscale[0],
  1440. s->qscale[1],
  1441. s->qscale[2]));
  1442. }
  1443. goto the_end;
  1444. case SOS:
  1445. if (!s->got_picture) {
  1446. av_log(avctx, AV_LOG_WARNING,
  1447. "Can not process SOS before SOF, skipping\n");
  1448. break;
  1449. }
  1450. if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
  1451. (avctx->err_recognition & AV_EF_EXPLODE))
  1452. return ret;
  1453. /* buggy avid puts EOI every 10-20th frame */
  1454. /* if restart period is over process EOI */
  1455. if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
  1456. goto eoi_parser;
  1457. break;
  1458. case DRI:
  1459. mjpeg_decode_dri(s);
  1460. break;
  1461. case SOF5:
  1462. case SOF6:
  1463. case SOF7:
  1464. case SOF9:
  1465. case SOF10:
  1466. case SOF11:
  1467. case SOF13:
  1468. case SOF14:
  1469. case SOF15:
  1470. case JPG:
  1471. av_log(avctx, AV_LOG_ERROR,
  1472. "mjpeg: unsupported coding type (%x)\n", start_code);
  1473. break;
  1474. }
  1475. not_the_end:
  1476. /* eof process start code */
  1477. buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
  1478. av_log(avctx, AV_LOG_DEBUG,
  1479. "marker parser used %d bytes (%d bits)\n",
  1480. (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
  1481. }
  1482. if (s->got_picture) {
  1483. av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
  1484. goto eoi_parser;
  1485. }
  1486. av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
  1487. return AVERROR_INVALIDDATA;
  1488. the_end:
  1489. av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n",
  1490. buf_end - buf_ptr);
  1491. // return buf_end - buf_ptr;
  1492. return buf_ptr - buf;
  1493. }
  1494. av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
  1495. {
  1496. MJpegDecodeContext *s = avctx->priv_data;
  1497. int i, j;
  1498. if (s->picture) {
  1499. av_frame_free(&s->picture);
  1500. s->picture_ptr = NULL;
  1501. } else if (s->picture_ptr)
  1502. av_frame_unref(s->picture_ptr);
  1503. av_free(s->buffer);
  1504. av_freep(&s->ljpeg_buffer);
  1505. s->ljpeg_buffer_size = 0;
  1506. for (i = 0; i < 3; i++) {
  1507. for (j = 0; j < 4; j++)
  1508. ff_free_vlc(&s->vlcs[i][j]);
  1509. }
  1510. for (i = 0; i < MAX_COMPONENTS; i++) {
  1511. av_freep(&s->blocks[i]);
  1512. av_freep(&s->last_nnz[i]);
  1513. }
  1514. return 0;
  1515. }
  1516. #define OFFSET(x) offsetof(MJpegDecodeContext, x)
  1517. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1518. static const AVOption options[] = {
  1519. { "extern_huff", "Use external huffman table.",
  1520. OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
  1521. { NULL },
  1522. };
  1523. static const AVClass mjpegdec_class = {
  1524. .class_name = "MJPEG decoder",
  1525. .item_name = av_default_item_name,
  1526. .option = options,
  1527. .version = LIBAVUTIL_VERSION_INT,
  1528. };
  1529. AVCodec ff_mjpeg_decoder = {
  1530. .name = "mjpeg",
  1531. .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
  1532. .type = AVMEDIA_TYPE_VIDEO,
  1533. .id = AV_CODEC_ID_MJPEG,
  1534. .priv_data_size = sizeof(MJpegDecodeContext),
  1535. .init = ff_mjpeg_decode_init,
  1536. .close = ff_mjpeg_decode_end,
  1537. .decode = ff_mjpeg_decode_frame,
  1538. .capabilities = CODEC_CAP_DR1,
  1539. .priv_class = &mjpegdec_class,
  1540. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1541. };
  1542. AVCodec ff_thp_decoder = {
  1543. .name = "thp",
  1544. .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
  1545. .type = AVMEDIA_TYPE_VIDEO,
  1546. .id = AV_CODEC_ID_THP,
  1547. .priv_data_size = sizeof(MJpegDecodeContext),
  1548. .init = ff_mjpeg_decode_init,
  1549. .close = ff_mjpeg_decode_end,
  1550. .decode = ff_mjpeg_decode_frame,
  1551. .capabilities = CODEC_CAP_DR1,
  1552. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1553. };