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