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