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.

1638 lines
55KB

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