FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
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 FFmpeg.
12  *
13  * FFmpeg is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Lesser General Public
15  * License as published by the Free Software Foundation; either
16  * version 2.1 of the License, or (at your option) any later version.
17  *
18  * FFmpeg is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21  * Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public
24  * License along with FFmpeg; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26  */
27 
28 /**
29  * @file
30  * MJPEG decoder.
31  */
32 
33 #include "libavutil/imgutils.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/opt.h"
36 #include "avcodec.h"
37 #include "copy_block.h"
38 #include "internal.h"
39 #include "mjpeg.h"
40 #include "mjpegdec.h"
41 #include "jpeglsdec.h"
42 
43 
44 static int build_vlc(VLC *vlc, const uint8_t *bits_table,
45  const uint8_t *val_table, int nb_codes,
46  int use_static, int is_ac)
47 {
48  uint8_t huff_size[256] = { 0 };
49  uint16_t huff_code[256];
50  uint16_t huff_sym[256];
51  int i;
52 
53  av_assert0(nb_codes <= 256);
54 
55  ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
56 
57  for (i = 0; i < 256; i++)
58  huff_sym[i] = i + 16 * is_ac;
59 
60  if (is_ac)
61  huff_sym[0] = 16 * 256;
62 
63  return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
64  huff_code, 2, 2, huff_sym, 2, 2, use_static);
65 }
66 
68 {
70  avpriv_mjpeg_val_dc, 12, 0, 0);
72  avpriv_mjpeg_val_dc, 12, 0, 0);
81 }
82 
84 {
85  MJpegDecodeContext *s = avctx->priv_data;
86 
87  if (!s->picture_ptr)
88  s->picture_ptr = &s->picture;
90 
91  s->avctx = avctx;
92  ff_hpeldsp_init(&s->hdsp, avctx->flags);
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->got_picture = 0;
100  s->org_height = avctx->coded_height;
102 
104 
105  if (s->extern_huff) {
106  av_log(avctx, AV_LOG_INFO, "using external huffman table\n");
107  init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
108  if (ff_mjpeg_decode_dht(s)) {
109  av_log(avctx, AV_LOG_ERROR,
110  "error using external huffman table, switching back to internal\n");
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, "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  int pr = get_bits(&s->gb, 4);
134  if (pr > 1) {
135  av_log(s->avctx, AV_LOG_ERROR, "dqt: invalid precision\n");
136  return AVERROR_INVALIDDATA;
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, pr ? 16 : 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  int h_count[MAX_COMPONENTS];
217  int v_count[MAX_COMPONENTS];
218 
219  s->cur_scan = 0;
220  s->upscale_h = s->upscale_v = 0;
221 
222  /* XXX: verify len field validity */
223  len = get_bits(&s->gb, 16);
224  s->bits = get_bits(&s->gb, 8);
225 
226  if (s->pegasus_rct)
227  s->bits = 9;
228  if (s->bits == 9 && !s->pegasus_rct)
229  s->rct = 1; // FIXME ugly
230 
231  if (s->bits != 8 && !s->lossless) {
232  av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
233  return -1;
234  }
235 
236  if(s->lossless && s->avctx->lowres){
237  av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
238  return -1;
239  }
240 
241  height = get_bits(&s->gb, 16);
242  width = get_bits(&s->gb, 16);
243 
244  // HACK for odd_height.mov
245  if (s->interlaced && s->width == width && s->height == height + 1)
246  height= s->height;
247 
248  av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
249  if (av_image_check_size(width, height, 0, s->avctx))
250  return AVERROR_INVALIDDATA;
251 
252  nb_components = get_bits(&s->gb, 8);
253  if (nb_components <= 0 ||
254  nb_components > MAX_COMPONENTS)
255  return -1;
256  if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
257  if (nb_components != s->nb_components) {
258  av_log(s->avctx, AV_LOG_ERROR, "nb_components changing in interlaced picture\n");
259  return AVERROR_INVALIDDATA;
260  }
261  }
262  if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
264  "JPEG-LS that is not <= 8 "
265  "bits/component or 16-bit gray");
266  return AVERROR_PATCHWELCOME;
267  }
268  s->nb_components = nb_components;
269  s->h_max = 1;
270  s->v_max = 1;
271  memset(h_count, 0, sizeof(h_count));
272  memset(v_count, 0, sizeof(v_count));
273  for (i = 0; i < nb_components; i++) {
274  /* component id */
275  s->component_id[i] = get_bits(&s->gb, 8) - 1;
276  h_count[i] = get_bits(&s->gb, 4);
277  v_count[i] = get_bits(&s->gb, 4);
278  /* compute hmax and vmax (only used in interleaved case) */
279  if (h_count[i] > s->h_max)
280  s->h_max = h_count[i];
281  if (v_count[i] > s->v_max)
282  s->v_max = v_count[i];
283  s->quant_index[i] = get_bits(&s->gb, 8);
284  if (s->quant_index[i] >= 4) {
285  av_log(s->avctx, AV_LOG_ERROR, "quant_index is invalid\n");
286  return AVERROR_INVALIDDATA;
287  }
288  if (!h_count[i] || !v_count[i]) {
290  "Invalid sampling factor in component %d %d:%d\n",
291  i, h_count[i], v_count[i]);
292  return AVERROR_INVALIDDATA;
293  }
294 
295  av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
296  i, h_count[i], v_count[i],
297  s->component_id[i], s->quant_index[i]);
298  }
299 
300  if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
301  avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
302  return AVERROR_PATCHWELCOME;
303  }
304 
305 
306  /* if different size, realloc/alloc picture */
307  if ( width != s->width || height != s->height
308  || memcmp(s->h_count, h_count, sizeof(h_count))
309  || memcmp(s->v_count, v_count, sizeof(v_count))) {
310 
311  s->width = width;
312  s->height = height;
313  memcpy(s->h_count, h_count, sizeof(h_count));
314  memcpy(s->v_count, v_count, sizeof(v_count));
315  s->interlaced = 0;
316  s->got_picture = 0;
317 
318  /* test interlaced mode */
319  if (s->first_picture &&
320  s->org_height != 0 &&
321  s->height < ((s->org_height * 3) / 4)) {
322  s->interlaced = 1;
326  height *= 2;
327  }
328 
329  avcodec_set_dimensions(s->avctx, width, height);
330 
331  s->first_picture = 0;
332  }
333 
334  if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
335  if (s->progressive) {
336  avpriv_request_sample(s->avctx, "progressively coded interlaced picture");
337  return AVERROR_INVALIDDATA;
338  }
339  } else{
340  if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && nb_components==3)
341  s->rgb = 1;
342  else if (!s->lossless)
343  s->rgb = 0;
344  /* XXX: not complete test ! */
345  pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
346  (s->h_count[1] << 20) | (s->v_count[1] << 16) |
347  (s->h_count[2] << 12) | (s->v_count[2] << 8) |
348  (s->h_count[3] << 4) | s->v_count[3];
349  av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
350  /* NOTE we do not allocate pictures large enough for the possible
351  * padding of h/v_count being 4 */
352  if (!(pix_fmt_id & 0xD0D0D0D0))
353  pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
354  if (!(pix_fmt_id & 0x0D0D0D0D))
355  pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
356 
357  switch (pix_fmt_id) {
358  case 0x11111100:
359  if (s->rgb)
361  else {
362  if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
364  } else {
367  }
368  }
369  av_assert0(s->nb_components == 3);
370  break;
371  case 0x12121100:
372  case 0x22122100:
375  s->upscale_v = 2;
376  s->upscale_h = (pix_fmt_id == 0x22122100);
377  s->chroma_height = s->height;
378  break;
379  case 0x21211100:
380  case 0x22211200:
383  s->upscale_v = (pix_fmt_id == 0x22211200);
384  s->upscale_h = 2;
385  s->chroma_height = s->height;
386  break;
387  case 0x22221100:
390  s->upscale_v = 2;
391  s->upscale_h = 2;
392  s->chroma_height = s->height / 2;
393  break;
394  case 0x11000000:
395  case 0x13000000:
396  case 0x14000000:
397  case 0x31000000:
398  case 0x33000000:
399  case 0x34000000:
400  case 0x41000000:
401  case 0x43000000:
402  case 0x44000000:
403  if(s->bits <= 8)
405  else
407  break;
408  case 0x12111100:
409  case 0x22211100:
410  case 0x22112100:
413  s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
414  s->chroma_height = s->height / 2;
415  break;
416  case 0x21111100:
419  break;
420  case 0x22121100:
421  case 0x22111200:
424  s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
425  break;
426  case 0x22111100:
429  break;
430  case 0x41111100:
433  break;
434  default:
435  av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
436  return AVERROR_PATCHWELCOME;
437  }
438  if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
439  av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
440  return AVERROR_PATCHWELCOME;
441  }
442  if (s->ls) {
443  s->upscale_h = s->upscale_v = 0;
444  if (s->nb_components > 1)
446  else if (s->bits <= 8)
448  else
450  }
451 
454  return -1;
456  s->picture_ptr->key_frame = 1;
457  s->got_picture = 1;
458 
459  for (i = 0; i < 3; i++)
460  s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
461 
462  av_dlog(s->avctx, "%d %d %d %d %d %d\n",
463  s->width, s->height, s->linesize[0], s->linesize[1],
464  s->interlaced, s->avctx->height);
465 
466  if (len != (8 + (3 * nb_components)))
467  av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
468  }
469 
470  if (s->rgb && !s->lossless && !s->ls) {
471  av_log(s->avctx, AV_LOG_ERROR, "Unsupported coding and pixel format combination\n");
472  return AVERROR_PATCHWELCOME;
473  }
474 
475  /* totally blank picture as progressive JPEG will only add details to it */
476  if (s->progressive) {
477  int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
478  int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
479  for (i = 0; i < s->nb_components; i++) {
480  int size = bw * bh * s->h_count[i] * s->v_count[i];
481  av_freep(&s->blocks[i]);
482  av_freep(&s->last_nnz[i]);
483  s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
484  s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
485  s->block_stride[i] = bw * s->h_count[i];
486  }
487  memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
488  }
489  return 0;
490 }
491 
492 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
493 {
494  int code;
495  code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
496  if (code < 0 || code > 16) {
498  "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
499  0, dc_index, &s->vlcs[0][dc_index]);
500  return 0xffff;
501  }
502 
503  if (code)
504  return get_xbits(&s->gb, code);
505  else
506  return 0;
507 }
508 
509 /* decode block and dequantize */
510 static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
511  int dc_index, int ac_index, int16_t *quant_matrix)
512 {
513  int code, i, j, level, val;
514 
515  /* DC coef */
516  val = mjpeg_decode_dc(s, dc_index);
517  if (val == 0xffff) {
518  av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
519  return AVERROR_INVALIDDATA;
520  }
521  val = val * quant_matrix[0] + s->last_dc[component];
522  s->last_dc[component] = val;
523  block[0] = val;
524  /* AC coefs */
525  i = 0;
526  {OPEN_READER(re, &s->gb);
527  do {
528  UPDATE_CACHE(re, &s->gb);
529  GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
530 
531  i += ((unsigned)code) >> 4;
532  code &= 0xf;
533  if (code) {
534  if (code > MIN_CACHE_BITS - 16)
535  UPDATE_CACHE(re, &s->gb);
536 
537  {
538  int cache = GET_CACHE(re, &s->gb);
539  int sign = (~cache) >> 31;
540  level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
541  }
542 
543  LAST_SKIP_BITS(re, &s->gb, code);
544 
545  if (i > 63) {
546  av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
547  return AVERROR_INVALIDDATA;
548  }
549  j = s->scantable.permutated[i];
550  block[j] = level * quant_matrix[j];
551  }
552  } while (i < 63);
553  CLOSE_READER(re, &s->gb);}
554 
555  return 0;
556 }
557 
559  int component, int dc_index,
560  int16_t *quant_matrix, int Al)
561 {
562  int val;
563  s->dsp.clear_block(block);
564  val = mjpeg_decode_dc(s, dc_index);
565  if (val == 0xffff) {
566  av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
567  return AVERROR_INVALIDDATA;
568  }
569  val = (val * quant_matrix[0] << Al) + s->last_dc[component];
570  s->last_dc[component] = val;
571  block[0] = val;
572  return 0;
573 }
574 
575 /* decode block and dequantize - progressive JPEG version */
577  uint8_t *last_nnz, int ac_index,
578  int16_t *quant_matrix,
579  int ss, int se, int Al, int *EOBRUN)
580 {
581  int code, i, j, level, val, run;
582 
583  if (*EOBRUN) {
584  (*EOBRUN)--;
585  return 0;
586  }
587 
588  {
589  OPEN_READER(re, &s->gb);
590  for (i = ss; ; i++) {
591  UPDATE_CACHE(re, &s->gb);
592  GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
593 
594  run = ((unsigned) code) >> 4;
595  code &= 0xF;
596  if (code) {
597  i += run;
598  if (code > MIN_CACHE_BITS - 16)
599  UPDATE_CACHE(re, &s->gb);
600 
601  {
602  int cache = GET_CACHE(re, &s->gb);
603  int sign = (~cache) >> 31;
604  level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
605  }
606 
607  LAST_SKIP_BITS(re, &s->gb, code);
608 
609  if (i >= se) {
610  if (i == se) {
611  j = s->scantable.permutated[se];
612  block[j] = level * quant_matrix[j] << Al;
613  break;
614  }
615  av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
616  return AVERROR_INVALIDDATA;
617  }
618  j = s->scantable.permutated[i];
619  block[j] = level * quant_matrix[j] << Al;
620  } else {
621  if (run == 0xF) {// ZRL - skip 15 coefficients
622  i += 15;
623  if (i >= se) {
624  av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
625  return AVERROR_INVALIDDATA;
626  }
627  } else {
628  val = (1 << run);
629  if (run) {
630  UPDATE_CACHE(re, &s->gb);
631  val += NEG_USR32(GET_CACHE(re, &s->gb), run);
632  LAST_SKIP_BITS(re, &s->gb, run);
633  }
634  *EOBRUN = val - 1;
635  break;
636  }
637  }
638  }
639  CLOSE_READER(re, &s->gb);
640  }
641 
642  if (i > *last_nnz)
643  *last_nnz = i;
644 
645  return 0;
646 }
647 
648 #define REFINE_BIT(j) { \
649  UPDATE_CACHE(re, &s->gb); \
650  sign = block[j] >> 15; \
651  block[j] += SHOW_UBITS(re, &s->gb, 1) * \
652  ((quant_matrix[j] ^ sign) - sign) << Al; \
653  LAST_SKIP_BITS(re, &s->gb, 1); \
654 }
655 
656 #define ZERO_RUN \
657 for (; ; i++) { \
658  if (i > last) { \
659  i += run; \
660  if (i > se) { \
661  av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
662  return -1; \
663  } \
664  break; \
665  } \
666  j = s->scantable.permutated[i]; \
667  if (block[j]) \
668  REFINE_BIT(j) \
669  else if (run-- == 0) \
670  break; \
671 }
672 
673 /* decode block and dequantize - progressive JPEG refinement pass */
675  uint8_t *last_nnz,
676  int ac_index, int16_t *quant_matrix,
677  int ss, int se, int Al, int *EOBRUN)
678 {
679  int code, i = ss, j, sign, val, run;
680  int last = FFMIN(se, *last_nnz);
681 
682  OPEN_READER(re, &s->gb);
683  if (*EOBRUN) {
684  (*EOBRUN)--;
685  } else {
686  for (; ; i++) {
687  UPDATE_CACHE(re, &s->gb);
688  GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
689 
690  if (code & 0xF) {
691  run = ((unsigned) code) >> 4;
692  UPDATE_CACHE(re, &s->gb);
693  val = SHOW_UBITS(re, &s->gb, 1);
694  LAST_SKIP_BITS(re, &s->gb, 1);
695  ZERO_RUN;
696  j = s->scantable.permutated[i];
697  val--;
698  block[j] = ((quant_matrix[j]^val) - val) << Al;
699  if (i == se) {
700  if (i > *last_nnz)
701  *last_nnz = i;
702  CLOSE_READER(re, &s->gb);
703  return 0;
704  }
705  } else {
706  run = ((unsigned) code) >> 4;
707  if (run == 0xF) {
708  ZERO_RUN;
709  } else {
710  val = run;
711  run = (1 << run);
712  if (val) {
713  UPDATE_CACHE(re, &s->gb);
714  run += SHOW_UBITS(re, &s->gb, val);
715  LAST_SKIP_BITS(re, &s->gb, val);
716  }
717  *EOBRUN = run - 1;
718  break;
719  }
720  }
721  }
722 
723  if (i > *last_nnz)
724  *last_nnz = i;
725  }
726 
727  for (; i <= last; i++) {
728  j = s->scantable.permutated[i];
729  if (block[j])
730  REFINE_BIT(j)
731  }
732  CLOSE_READER(re, &s->gb);
733 
734  return 0;
735 }
736 #undef REFINE_BIT
737 #undef ZERO_RUN
738 
739 static int handle_rstn(MJpegDecodeContext *s, int nb_components)
740 {
741  int i;
742  int reset = 0;
743 
744  if (s->restart_interval) {
745  s->restart_count--;
746  if(s->restart_count == 0 && s->avctx->codec_id == AV_CODEC_ID_THP){
747  align_get_bits(&s->gb);
748  for (i = 0; i < nb_components; i++) /* reset dc */
749  s->last_dc[i] = 1024;
750  }
751 
752  i = 8 + ((-get_bits_count(&s->gb)) & 7);
753  /* skip RSTn */
754  if (s->restart_count == 0) {
755  if( show_bits(&s->gb, i) == (1 << i) - 1
756  || show_bits(&s->gb, i) == 0xFF) {
757  int pos = get_bits_count(&s->gb);
758  align_get_bits(&s->gb);
759  while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
760  skip_bits(&s->gb, 8);
761  if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
762  for (i = 0; i < nb_components; i++) /* reset dc */
763  s->last_dc[i] = 1024;
764  reset = 1;
765  } else
766  skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
767  }
768  }
769  }
770  return reset;
771 }
772 
773 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
774 {
775  int i, mb_x, mb_y;
776  uint16_t (*buffer)[4];
777  int left[3], top[3], topleft[3];
778  const int linesize = s->linesize[0];
779  const int mask = (1 << s->bits) - 1;
780  int resync_mb_y = 0;
781  int resync_mb_x = 0;
782 
784 
786  (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
787  buffer = s->ljpeg_buffer;
788 
789  for (i = 0; i < 3; i++)
790  buffer[0][i] = 1 << (s->bits - 1);
791 
792  for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
793  uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
794 
795  if (s->interlaced && s->bottom_field)
796  ptr += linesize >> 1;
797 
798  for (i = 0; i < 3; i++)
799  top[i] = left[i] = topleft[i] = buffer[0][i];
800 
801  for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
802  int modified_predictor = predictor;
803 
804  if (s->restart_interval && !s->restart_count){
806  resync_mb_x = mb_x;
807  resync_mb_y = mb_y;
808  for(i=0; i<3; i++)
809  top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
810  }
811  if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
812  modified_predictor = 1;
813 
814  for (i=0;i<nb_components;i++) {
815  int pred, dc;
816 
817  topleft[i] = top[i];
818  top[i] = buffer[mb_x][i];
819 
820  PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
821 
822  dc = mjpeg_decode_dc(s, s->dc_index[i]);
823  if(dc == 0xFFFF)
824  return -1;
825 
826  left[i] = buffer[mb_x][i] =
827  mask & (pred + (dc << point_transform));
828  }
829 
830  if (s->restart_interval && !--s->restart_count) {
831  align_get_bits(&s->gb);
832  skip_bits(&s->gb, 16); /* skip RSTn */
833  }
834  }
835 
836  if (s->rct) {
837  for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
838  ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
839  ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
840  ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
841  }
842  } else if (s->pegasus_rct) {
843  for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
844  ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
845  ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
846  ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
847  }
848  } else {
849  for(i=0; i<nb_components; i++) {
850  int c= s->comp_index[i];
851  for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
852  ptr[3*mb_x+2-c] = buffer[mb_x][i];
853  }
854  }
855  }
856  }
857  return 0;
858 }
859 
861  int point_transform, int nb_components)
862 {
863  int i, mb_x, mb_y;
864  int bits= (s->bits+7)&~7;
865  int resync_mb_y = 0;
866  int resync_mb_x = 0;
867 
868  point_transform += bits - s->bits;
869 
870  av_assert0(nb_components>=1 && nb_components<=3);
871 
872  for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
873  for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
874  if (s->restart_interval && !s->restart_count){
876  resync_mb_x = mb_x;
877  resync_mb_y = mb_y;
878  }
879 
880  if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
881  int toprow = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
882  int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
883  for (i = 0; i < nb_components; i++) {
884  uint8_t *ptr;
885  uint16_t *ptr16;
886  int n, h, v, x, y, c, j, linesize;
887  n = s->nb_blocks[i];
888  c = s->comp_index[i];
889  h = s->h_scount[i];
890  v = s->v_scount[i];
891  x = 0;
892  y = 0;
893  linesize= s->linesize[c];
894 
895  if(bits>8) linesize /= 2;
896 
897  for(j=0; j<n; j++) {
898  int pred, dc;
899 
900  dc = mjpeg_decode_dc(s, s->dc_index[i]);
901  if(dc == 0xFFFF)
902  return -1;
903  if(bits<=8){
904  ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
905  if(y==0 && toprow){
906  if(x==0 && leftcol){
907  pred= 1 << (bits - 1);
908  }else{
909  pred= ptr[-1];
910  }
911  }else{
912  if(x==0 && leftcol){
913  pred= ptr[-linesize];
914  }else{
915  PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
916  }
917  }
918 
919  if (s->interlaced && s->bottom_field)
920  ptr += linesize >> 1;
921  pred &= (-1)<<(8-s->bits);
922  *ptr= pred + (dc << point_transform);
923  }else{
924  ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
925  if(y==0 && toprow){
926  if(x==0 && leftcol){
927  pred= 1 << (bits - 1);
928  }else{
929  pred= ptr16[-1];
930  }
931  }else{
932  if(x==0 && leftcol){
933  pred= ptr16[-linesize];
934  }else{
935  PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
936  }
937  }
938 
939  if (s->interlaced && s->bottom_field)
940  ptr16 += linesize >> 1;
941  pred &= (-1)<<(16-s->bits);
942  *ptr16= pred + (dc << point_transform);
943  }
944  if (++x == h) {
945  x = 0;
946  y++;
947  }
948  }
949  }
950  } else {
951  for (i = 0; i < nb_components; i++) {
952  uint8_t *ptr;
953  uint16_t *ptr16;
954  int n, h, v, x, y, c, j, linesize, dc;
955  n = s->nb_blocks[i];
956  c = s->comp_index[i];
957  h = s->h_scount[i];
958  v = s->v_scount[i];
959  x = 0;
960  y = 0;
961  linesize = s->linesize[c];
962 
963  if(bits>8) linesize /= 2;
964 
965  for (j = 0; j < n; j++) {
966  int pred;
967 
968  dc = mjpeg_decode_dc(s, s->dc_index[i]);
969  if(dc == 0xFFFF)
970  return -1;
971  if(bits<=8){
972  ptr = s->picture.data[c] +
973  (linesize * (v * mb_y + y)) +
974  (h * mb_x + x); //FIXME optimize this crap
975  PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
976 
977  pred &= (-1)<<(8-s->bits);
978  *ptr = pred + (dc << point_transform);
979  }else{
980  ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
981  PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
982 
983  pred &= (-1)<<(16-s->bits);
984  *ptr16= pred + (dc << point_transform);
985  }
986 
987  if (++x == h) {
988  x = 0;
989  y++;
990  }
991  }
992  }
993  }
994  if (s->restart_interval && !--s->restart_count) {
995  align_get_bits(&s->gb);
996  skip_bits(&s->gb, 16); /* skip RSTn */
997  }
998  }
999  }
1000  return 0;
1001 }
1002 
1004  uint8_t *dst, const uint8_t *src,
1005  int linesize, int lowres)
1006 {
1007  switch (lowres) {
1008  case 0: s->hdsp.put_pixels_tab[1][0](dst, src, linesize, 8);
1009  break;
1010  case 1: copy_block4(dst, src, linesize, linesize, 4);
1011  break;
1012  case 2: copy_block2(dst, src, linesize, linesize, 2);
1013  break;
1014  case 3: *dst = *src;
1015  break;
1016  }
1017 }
1018 
1019 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
1020  int Al, const uint8_t *mb_bitmask,
1021  const AVFrame *reference)
1022 {
1023  int i, mb_x, mb_y;
1025  const uint8_t *reference_data[MAX_COMPONENTS];
1026  int linesize[MAX_COMPONENTS];
1027  GetBitContext mb_bitmask_gb;
1028 
1029  if (mb_bitmask)
1030  init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
1031 
1032  if (s->flipped && s->avctx->lowres) {
1033  av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with lowres\n");
1034  s->flipped = 0;
1035  }
1036  s->restart_count = 0;
1037  for (i = 0; i < nb_components; i++) {
1038  int c = s->comp_index[i];
1039  data[c] = s->picture_ptr->data[c];
1040  reference_data[c] = reference ? reference->data[c] : NULL;
1041  linesize[c] = s->linesize[c];
1042  s->coefs_finished[c] |= 1;
1043  if (s->flipped && !(s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1044  // picture should be flipped upside-down for this codec
1045  int offset = (linesize[c] * (s->v_scount[i] *
1046  (8 * s->mb_height - ((s->height / s->v_max) & 7)) - 1));
1047  data[c] += offset;
1048  reference_data[c] += offset;
1049  linesize[c] *= -1;
1050  }
1051  }
1052 
1053  for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1054  for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1055  const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
1056 
1057  if (s->restart_interval && !s->restart_count)
1059 
1060  if (get_bits_left(&s->gb) < 0) {
1061  av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1062  -get_bits_left(&s->gb));
1063  return AVERROR_INVALIDDATA;
1064  }
1065  for (i = 0; i < nb_components; i++) {
1066  uint8_t *ptr;
1067  int n, h, v, x, y, c, j;
1068  int block_offset;
1069  n = s->nb_blocks[i];
1070  c = s->comp_index[i];
1071  h = s->h_scount[i];
1072  v = s->v_scount[i];
1073  x = 0;
1074  y = 0;
1075  for (j = 0; j < n; j++) {
1076  block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1077  (h * mb_x + x) * 8) >> s->avctx->lowres);
1078 
1079  if (s->interlaced && s->bottom_field)
1080  block_offset += linesize[c] >> 1;
1081  ptr = data[c] + block_offset;
1082  if (!s->progressive) {
1083  if (copy_mb)
1084  mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
1085  linesize[c], s->avctx->lowres);
1086 
1087  else {
1088  s->dsp.clear_block(s->block);
1089  if (decode_block(s, s->block, i,
1090  s->dc_index[i], s->ac_index[i],
1091  s->quant_matrixes[s->quant_index[c]]) < 0) {
1093  "error y=%d x=%d\n", mb_y, mb_x);
1094  return AVERROR_INVALIDDATA;
1095  }
1096  s->dsp.idct_put(ptr, linesize[c], s->block);
1097  }
1098  } else {
1099  int block_idx = s->block_stride[c] * (v * mb_y + y) +
1100  (h * mb_x + x);
1101  int16_t *block = s->blocks[c][block_idx];
1102  if (Ah)
1103  block[0] += get_bits1(&s->gb) *
1104  s->quant_matrixes[s->quant_index[c]][0] << Al;
1105  else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1106  s->quant_matrixes[s->quant_index[c]],
1107  Al) < 0) {
1109  "error y=%d x=%d\n", mb_y, mb_x);
1110  return AVERROR_INVALIDDATA;
1111  }
1112  }
1113  av_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
1114  av_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
1115  mb_x, mb_y, x, y, c, s->bottom_field,
1116  (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1117  if (++x == h) {
1118  x = 0;
1119  y++;
1120  }
1121  }
1122  }
1123 
1124  handle_rstn(s, nb_components);
1125  }
1126  }
1127  return 0;
1128 }
1129 
1131  int se, int Ah, int Al)
1132 {
1133  int mb_x, mb_y;
1134  int EOBRUN = 0;
1135  int c = s->comp_index[0];
1136  uint8_t *data = s->picture.data[c];
1137  int linesize = s->linesize[c];
1138  int last_scan = 0;
1139  int16_t *quant_matrix = s->quant_matrixes[s->quant_index[c]];
1140 
1141  av_assert0(ss>=0 && Ah>=0 && Al>=0);
1142  if (se < ss || se > 63) {
1143  av_log(s->avctx, AV_LOG_ERROR, "SS/SE %d/%d is invalid\n", ss, se);
1144  return AVERROR_INVALIDDATA;
1145  }
1146 
1147  if (!Al) {
1148  s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
1149  last_scan = !~s->coefs_finished[c];
1150  }
1151 
1152  if (s->interlaced && s->bottom_field)
1153  data += linesize >> 1;
1154 
1155  s->restart_count = 0;
1156 
1157  for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1158  uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1159  int block_idx = mb_y * s->block_stride[c];
1160  int16_t (*block)[64] = &s->blocks[c][block_idx];
1161  uint8_t *last_nnz = &s->last_nnz[c][block_idx];
1162  for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1163  int ret;
1164  if (s->restart_interval && !s->restart_count)
1166 
1167  if (Ah)
1168  ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1169  quant_matrix, ss, se, Al, &EOBRUN);
1170  else
1171  ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1172  quant_matrix, ss, se, Al, &EOBRUN);
1173  if (ret < 0) {
1175  "error y=%d x=%d\n", mb_y, mb_x);
1176  return AVERROR_INVALIDDATA;
1177  }
1178 
1179  if (last_scan) {
1180  s->dsp.idct_put(ptr, linesize, *block);
1181  ptr += 8 >> s->avctx->lowres;
1182  }
1183  if (handle_rstn(s, 0))
1184  EOBRUN = 0;
1185  }
1186  }
1187  return 0;
1188 }
1189 
1191  const AVFrame *reference)
1192 {
1193  int len, nb_components, i, h, v, predictor, point_transform;
1194  int index, id, ret;
1195  const int block_size = s->lossless ? 1 : 8;
1196  int ilv, prev_shift;
1197 
1198  if (!s->got_picture) {
1200  "Can not process SOS before SOF, skipping\n");
1201  return -1;
1202  }
1203 
1204  av_assert0(s->picture_ptr->data[0]);
1205  /* XXX: verify len field validity */
1206  len = get_bits(&s->gb, 16);
1207  nb_components = get_bits(&s->gb, 8);
1208  if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1210  "decode_sos: nb_components (%d) unsupported\n", nb_components);
1211  return AVERROR_PATCHWELCOME;
1212  }
1213  if (len != 6 + 2 * nb_components) {
1214  av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1215  return AVERROR_INVALIDDATA;
1216  }
1217  for (i = 0; i < nb_components; i++) {
1218  id = get_bits(&s->gb, 8) - 1;
1219  av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1220  /* find component index */
1221  for (index = 0; index < s->nb_components; index++)
1222  if (id == s->component_id[index])
1223  break;
1224  if (index == s->nb_components) {
1226  "decode_sos: index(%d) out of components\n", index);
1227  return AVERROR_INVALIDDATA;
1228  }
1229  /* Metasoft MJPEG codec has Cb and Cr swapped */
1230  if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1231  && nb_components == 3 && s->nb_components == 3 && i)
1232  index = 3 - i;
1233 
1234  if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1235  index = (i+2)%3;
1236  if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1237  index = (index+2)%3;
1238 
1239  s->comp_index[i] = index;
1240 
1241  s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1242  s->h_scount[i] = s->h_count[index];
1243  s->v_scount[i] = s->v_count[index];
1244 
1245  s->dc_index[i] = get_bits(&s->gb, 4);
1246  s->ac_index[i] = get_bits(&s->gb, 4);
1247 
1248  if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1249  s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1250  goto out_of_range;
1251  if (!s->vlcs[0][s->dc_index[i]].table || !(s->progressive ? s->vlcs[2][s->ac_index[0]].table : s->vlcs[1][s->ac_index[i]].table))
1252  goto out_of_range;
1253  }
1254 
1255  predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1256  ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1257  if(s->avctx->codec_tag != AV_RL32("CJPG")){
1258  prev_shift = get_bits(&s->gb, 4); /* Ah */
1259  point_transform = get_bits(&s->gb, 4); /* Al */
1260  }else
1261  prev_shift = point_transform = 0;
1262 
1263  if (nb_components > 1) {
1264  /* interleaved stream */
1265  s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1266  s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1267  } else if (!s->ls) { /* skip this for JPEG-LS */
1268  h = s->h_max / s->h_scount[0];
1269  v = s->v_max / s->v_scount[0];
1270  s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1271  s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1272  s->nb_blocks[0] = 1;
1273  s->h_scount[0] = 1;
1274  s->v_scount[0] = 1;
1275  }
1276 
1277  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1278  av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1279  s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1280  predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1281  s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1282 
1283 
1284  /* mjpeg-b can have padding bytes between sos and image data, skip them */
1285  for (i = s->mjpb_skiptosod; i > 0; i--)
1286  skip_bits(&s->gb, 8);
1287 
1288 next_field:
1289  for (i = 0; i < nb_components; i++)
1290  s->last_dc[i] = 1024;
1291 
1292  if (s->lossless) {
1293  av_assert0(s->picture_ptr == &s->picture);
1294  if (CONFIG_JPEGLS_DECODER && s->ls) {
1295 // for () {
1296 // reset_ls_coding_parameters(s, 0);
1297 
1298  if ((ret = ff_jpegls_decode_picture(s, predictor,
1299  point_transform, ilv)) < 0)
1300  return ret;
1301  } else {
1302  if (s->rgb) {
1303  if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
1304  return ret;
1305  } else {
1306  if ((ret = ljpeg_decode_yuv_scan(s, predictor,
1307  point_transform,
1308  nb_components)) < 0)
1309  return ret;
1310  }
1311  }
1312  } else {
1313  if (s->progressive && predictor) {
1314  av_assert0(s->picture_ptr == &s->picture);
1315  if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1316  ilv, prev_shift,
1317  point_transform)) < 0)
1318  return ret;
1319  } else {
1320  if ((ret = mjpeg_decode_scan(s, nb_components,
1321  prev_shift, point_transform,
1322  mb_bitmask, reference)) < 0)
1323  return ret;
1324  }
1325  }
1326 
1327  if (s->interlaced &&
1328  get_bits_left(&s->gb) > 32 &&
1329  show_bits(&s->gb, 8) == 0xFF) {
1330  GetBitContext bak = s->gb;
1331  align_get_bits(&bak);
1332  if (show_bits(&bak, 16) == 0xFFD1) {
1333  av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1334  s->gb = bak;
1335  skip_bits(&s->gb, 16);
1336  s->bottom_field ^= 1;
1337 
1338  goto next_field;
1339  }
1340  }
1341 
1342  emms_c();
1343  return 0;
1344  out_of_range:
1345  av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1346  return AVERROR_INVALIDDATA;
1347 }
1348 
1350 {
1351  if (get_bits(&s->gb, 16) != 4)
1352  return AVERROR_INVALIDDATA;
1353  s->restart_interval = get_bits(&s->gb, 16);
1354  s->restart_count = 0;
1355  av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1356  s->restart_interval);
1357 
1358  return 0;
1359 }
1360 
1362 {
1363  int len, id, i;
1364 
1365  len = get_bits(&s->gb, 16);
1366  if (len < 5)
1367  return AVERROR_INVALIDDATA;
1368  if (8 * len > get_bits_left(&s->gb))
1369  return AVERROR_INVALIDDATA;
1370 
1371  id = get_bits_long(&s->gb, 32);
1372  len -= 6;
1373 
1374  if (s->avctx->debug & FF_DEBUG_STARTCODE)
1375  av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1376 
1377  /* Buggy AVID, it puts EOI only at every 10th frame. */
1378  /* Also, this fourcc is used by non-avid files too, it holds some
1379  information, but it's always present in AVID-created files. */
1380  if (id == AV_RB32("AVI1")) {
1381  /* structure:
1382  4bytes AVI1
1383  1bytes polarity
1384  1bytes always zero
1385  4bytes field_size
1386  4bytes field_size_less_padding
1387  */
1388  s->buggy_avid = 1;
1389  i = get_bits(&s->gb, 8); len--;
1390  av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1391 #if 0
1392  skip_bits(&s->gb, 8);
1393  skip_bits(&s->gb, 32);
1394  skip_bits(&s->gb, 32);
1395  len -= 10;
1396 #endif
1397  goto out;
1398  }
1399 
1400 // len -= 2;
1401 
1402  if (id == AV_RB32("JFIF")) {
1403  int t_w, t_h, v1, v2;
1404  skip_bits(&s->gb, 8); /* the trailing zero-byte */
1405  v1 = get_bits(&s->gb, 8);
1406  v2 = get_bits(&s->gb, 8);
1407  skip_bits(&s->gb, 8);
1408 
1409  s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1410  s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1411 
1412  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1413  av_log(s->avctx, AV_LOG_INFO,
1414  "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1415  v1, v2,
1418 
1419  t_w = get_bits(&s->gb, 8);
1420  t_h = get_bits(&s->gb, 8);
1421  if (t_w && t_h) {
1422  /* skip thumbnail */
1423  if (len -10 - (t_w * t_h * 3) > 0)
1424  len -= t_w * t_h * 3;
1425  }
1426  len -= 10;
1427  goto out;
1428  }
1429 
1430  if (id == AV_RB32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1431  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1432  av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1433  skip_bits(&s->gb, 16); /* version */
1434  skip_bits(&s->gb, 16); /* flags0 */
1435  skip_bits(&s->gb, 16); /* flags1 */
1436  skip_bits(&s->gb, 8); /* transform */
1437  len -= 7;
1438  goto out;
1439  }
1440 
1441  if (id == AV_RB32("LJIF")) {
1442  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1443  av_log(s->avctx, AV_LOG_INFO,
1444  "Pegasus lossless jpeg header found\n");
1445  skip_bits(&s->gb, 16); /* version ? */
1446  skip_bits(&s->gb, 16); /* unknown always 0? */
1447  skip_bits(&s->gb, 16); /* unknown always 0? */
1448  skip_bits(&s->gb, 16); /* unknown always 0? */
1449  switch (get_bits(&s->gb, 8)) {
1450  case 1:
1451  s->rgb = 1;
1452  s->pegasus_rct = 0;
1453  break;
1454  case 2:
1455  s->rgb = 1;
1456  s->pegasus_rct = 1;
1457  break;
1458  default:
1459  av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1460  }
1461  len -= 9;
1462  goto out;
1463  }
1464 
1465  /* Apple MJPEG-A */
1466  if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1467  id = get_bits_long(&s->gb, 32);
1468  len -= 4;
1469  /* Apple MJPEG-A */
1470  if (id == AV_RB32("mjpg")) {
1471 #if 0
1472  skip_bits(&s->gb, 32); /* field size */
1473  skip_bits(&s->gb, 32); /* pad field size */
1474  skip_bits(&s->gb, 32); /* next off */
1475  skip_bits(&s->gb, 32); /* quant off */
1476  skip_bits(&s->gb, 32); /* huff off */
1477  skip_bits(&s->gb, 32); /* image off */
1478  skip_bits(&s->gb, 32); /* scan off */
1479  skip_bits(&s->gb, 32); /* data off */
1480 #endif
1481  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1482  av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1483  }
1484  }
1485 
1486 out:
1487  /* slow but needed for extreme adobe jpegs */
1488  if (len < 0)
1490  "mjpeg: error, decode_app parser read over the end\n");
1491  while (--len > 0)
1492  skip_bits(&s->gb, 8);
1493 
1494  return 0;
1495 }
1496 
1498 {
1499  int len = get_bits(&s->gb, 16);
1500  if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1501  char *cbuf = av_malloc(len - 1);
1502  if (cbuf) {
1503  int i;
1504  for (i = 0; i < len - 2; i++)
1505  cbuf[i] = get_bits(&s->gb, 8);
1506  if (i > 0 && cbuf[i - 1] == '\n')
1507  cbuf[i - 1] = 0;
1508  else
1509  cbuf[i] = 0;
1510 
1511  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1512  av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
1513 
1514  /* buggy avid, it puts EOI only at every 10th frame */
1515  if (!strncmp(cbuf, "AVID", 4)) {
1516  s->buggy_avid = 1;
1517  if (len > 14 && cbuf[12] == 1) /* 1 - NTSC, 2 - PAL */
1518  s->interlace_polarity = 1;
1519  } else if (!strcmp(cbuf, "CS=ITU601"))
1520  s->cs_itu601 = 1;
1521  else if ((!strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32)) ||
1522  (!strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1523  s->flipped = 1;
1524 
1525  av_free(cbuf);
1526  }
1527  }
1528 
1529  return 0;
1530 }
1531 
1532 /* return the 8 bit start code value and update the search
1533  state. Return -1 if no start code found */
1534 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1535 {
1536  const uint8_t *buf_ptr;
1537  unsigned int v, v2;
1538  int val;
1539  int skipped = 0;
1540 
1541  buf_ptr = *pbuf_ptr;
1542  while (buf_ptr < buf_end) {
1543  v = *buf_ptr++;
1544  v2 = *buf_ptr;
1545  if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1546  val = *buf_ptr++;
1547  goto found;
1548  }
1549  skipped++;
1550  }
1551  val = -1;
1552 found:
1553  av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1554  *pbuf_ptr = buf_ptr;
1555  return val;
1556 }
1557 
1559  const uint8_t **buf_ptr, const uint8_t *buf_end,
1560  const uint8_t **unescaped_buf_ptr,
1561  int *unescaped_buf_size)
1562 {
1563  int start_code;
1564  start_code = find_marker(buf_ptr, buf_end);
1565 
1566  av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1567  if (!s->buffer)
1568  return AVERROR(ENOMEM);
1569 
1570  /* unescape buffer of SOS, use special treatment for JPEG-LS */
1571  if (start_code == SOS && !s->ls) {
1572  const uint8_t *src = *buf_ptr;
1573  uint8_t *dst = s->buffer;
1574 
1575  while (src < buf_end) {
1576  uint8_t x = *(src++);
1577 
1578  *(dst++) = x;
1579  if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1580  if (x == 0xff) {
1581  while (src < buf_end && x == 0xff)
1582  x = *(src++);
1583 
1584  if (x >= 0xd0 && x <= 0xd7)
1585  *(dst++) = x;
1586  else if (x)
1587  break;
1588  }
1589  }
1590  }
1591  *unescaped_buf_ptr = s->buffer;
1592  *unescaped_buf_size = dst - s->buffer;
1593  memset(s->buffer + *unescaped_buf_size, 0,
1595 
1596  av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1597  (buf_end - *buf_ptr) - (dst - s->buffer));
1598  } else if (start_code == SOS && s->ls) {
1599  const uint8_t *src = *buf_ptr;
1600  uint8_t *dst = s->buffer;
1601  int bit_count = 0;
1602  int t = 0, b = 0;
1603  PutBitContext pb;
1604 
1605  s->cur_scan++;
1606 
1607  /* find marker */
1608  while (src + t < buf_end) {
1609  uint8_t x = src[t++];
1610  if (x == 0xff) {
1611  while ((src + t < buf_end) && x == 0xff)
1612  x = src[t++];
1613  if (x & 0x80) {
1614  t -= FFMIN(2, t);
1615  break;
1616  }
1617  }
1618  }
1619  bit_count = t * 8;
1620  init_put_bits(&pb, dst, t);
1621 
1622  /* unescape bitstream */
1623  while (b < t) {
1624  uint8_t x = src[b++];
1625  put_bits(&pb, 8, x);
1626  if (x == 0xFF) {
1627  x = src[b++];
1628  put_bits(&pb, 7, x);
1629  bit_count--;
1630  }
1631  }
1632  flush_put_bits(&pb);
1633 
1634  *unescaped_buf_ptr = dst;
1635  *unescaped_buf_size = (bit_count + 7) >> 3;
1636  memset(s->buffer + *unescaped_buf_size, 0,
1638  } else {
1639  *unescaped_buf_ptr = *buf_ptr;
1640  *unescaped_buf_size = buf_end - *buf_ptr;
1641  }
1642 
1643  return start_code;
1644 }
1645 
1646 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
1647  AVPacket *avpkt)
1648 {
1649  const uint8_t *buf = avpkt->data;
1650  int buf_size = avpkt->size;
1651  MJpegDecodeContext *s = avctx->priv_data;
1652  const uint8_t *buf_end, *buf_ptr;
1653  const uint8_t *unescaped_buf_ptr;
1654  int hshift, vshift;
1655  int unescaped_buf_size;
1656  int start_code;
1657  int i, index;
1658  int ret = 0;
1659 
1660  buf_ptr = buf;
1661  buf_end = buf + buf_size;
1662  while (buf_ptr < buf_end) {
1663  /* find start next marker */
1664  start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1665  &unescaped_buf_ptr,
1666  &unescaped_buf_size);
1667  /* EOF */
1668  if (start_code < 0) {
1669  goto the_end;
1670  } else if (unescaped_buf_size > INT_MAX / 8) {
1671  av_log(avctx, AV_LOG_ERROR,
1672  "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
1673  start_code, unescaped_buf_size, buf_size);
1674  return AVERROR_INVALIDDATA;
1675  }
1676  av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1677  start_code, buf_end - buf_ptr);
1678 
1679  ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);
1680 
1681  if (ret < 0) {
1682  av_log(avctx, AV_LOG_ERROR, "invalid buffer\n");
1683  goto fail;
1684  }
1685 
1686  s->start_code = start_code;
1687  if (s->avctx->debug & FF_DEBUG_STARTCODE)
1688  av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1689 
1690  /* process markers */
1691  if (start_code >= 0xd0 && start_code <= 0xd7)
1692  av_log(avctx, AV_LOG_DEBUG,
1693  "restart marker: %d\n", start_code & 0x0f);
1694  /* APP fields */
1695  else if (start_code >= APP0 && start_code <= APP15)
1696  mjpeg_decode_app(s);
1697  /* Comment */
1698  else if (start_code == COM)
1699  mjpeg_decode_com(s);
1700 
1701  ret = -1;
1702 
1703  if (!CONFIG_JPEGLS_DECODER &&
1704  (start_code == SOF48 || start_code == LSE)) {
1705  av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
1706  return AVERROR(ENOSYS);
1707  }
1708 
1709  switch (start_code) {
1710  case SOI:
1711  s->restart_interval = 0;
1712  s->restart_count = 0;
1713  /* nothing to do on SOI */
1714  break;
1715  case DQT:
1717  break;
1718  case DHT:
1719  if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1720  av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1721  goto fail;
1722  }
1723  break;
1724  case SOF0:
1725  case SOF1:
1726  s->lossless = 0;
1727  s->ls = 0;
1728  s->progressive = 0;
1729  if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1730  goto fail;
1731  break;
1732  case SOF2:
1733  s->lossless = 0;
1734  s->ls = 0;
1735  s->progressive = 1;
1736  if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1737  goto fail;
1738  break;
1739  case SOF3:
1740  s->lossless = 1;
1741  s->ls = 0;
1742  s->progressive = 0;
1743  if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1744  goto fail;
1745  break;
1746  case SOF48:
1747  s->lossless = 1;
1748  s->ls = 1;
1749  s->progressive = 0;
1750  if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1751  goto fail;
1752  break;
1753  case LSE:
1754  if (!CONFIG_JPEGLS_DECODER ||
1755  (ret = ff_jpegls_decode_lse(s)) < 0)
1756  goto fail;
1757  break;
1758  case EOI:
1759 eoi_parser:
1760  s->cur_scan = 0;
1761  if (!s->got_picture) {
1762  av_log(avctx, AV_LOG_WARNING,
1763  "Found EOI before any SOF, ignoring\n");
1764  break;
1765  }
1766  if (s->interlaced) {
1767  s->bottom_field ^= 1;
1768  /* if not bottom field, do not output image yet */
1769  if (s->bottom_field == !s->interlace_polarity)
1770  break;
1771  }
1772  if ((ret = av_frame_ref(data, s->picture_ptr)) < 0)
1773  return ret;
1774  *got_frame = 1;
1775  s->got_picture = 0;
1776 
1777  if (!s->lossless) {
1778  int qp = FFMAX3(s->qscale[0],
1779  s->qscale[1],
1780  s->qscale[2]);
1781  int qpw = (s->width + 15) / 16;
1782  AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);
1783  if (qp_table_buf) {
1784  memset(qp_table_buf->data, qp, qpw);
1785  av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);
1786  }
1787 
1788  if(avctx->debug & FF_DEBUG_QP)
1789  av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);
1790  }
1791 
1792  goto the_end;
1793  case SOS:
1794  if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
1795  (avctx->err_recognition & AV_EF_EXPLODE))
1796  goto fail;
1797  break;
1798  case DRI:
1799  mjpeg_decode_dri(s);
1800  break;
1801  case SOF5:
1802  case SOF6:
1803  case SOF7:
1804  case SOF9:
1805  case SOF10:
1806  case SOF11:
1807  case SOF13:
1808  case SOF14:
1809  case SOF15:
1810  case JPG:
1811  av_log(avctx, AV_LOG_ERROR,
1812  "mjpeg: unsupported coding type (%x)\n", start_code);
1813  break;
1814  }
1815 
1816  /* eof process start code */
1817  buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1818  av_log(avctx, AV_LOG_DEBUG,
1819  "marker parser used %d bytes (%d bits)\n",
1820  (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1821  }
1822  if (s->got_picture) {
1823  av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1824  goto eoi_parser;
1825  }
1826  av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1827  return AVERROR_INVALIDDATA;
1828 fail:
1829  s->got_picture = 0;
1830  return ret;
1831 the_end:
1832  if (s->upscale_h) {
1833  uint8_t *line = s->picture_ptr->data[s->upscale_h];
1835  avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1836  avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
1837  avctx->pix_fmt == AV_PIX_FMT_YUV440P);
1838  for (i = 0; i < s->chroma_height; i++) {
1839  for (index = s->width - 1; index; index--)
1840  line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1841  line += s->linesize[s->upscale_h];
1842  }
1843  }
1844  if (s->upscale_v) {
1845  uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1846  int w;
1847  avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1848  w = s->width >> hshift;
1850  avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1851  avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
1852  avctx->pix_fmt == AV_PIX_FMT_YUV422P);
1853  for (i = s->height - 1; i; i--) {
1854  uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1855  uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1856  if (src1 == src2) {
1857  memcpy(dst, src1, w);
1858  } else {
1859  for (index = 0; index < w; index++)
1860  dst[index] = (src1[index] + src2[index]) >> 1;
1861  }
1862  dst -= s->linesize[s->upscale_v];
1863  }
1864  }
1865  if (s->flipped && (s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1866  int j;
1867  avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1868  for (index=0; index<4; index++) {
1869  uint8_t *dst = s->picture_ptr->data[index];
1870  int w = s->width;
1871  int h = s->height;
1872  if(index && index<3){
1873  w = FF_CEIL_RSHIFT(w, hshift);
1874  h = FF_CEIL_RSHIFT(h, vshift);
1875  }
1876  if(dst){
1877  uint8_t *dst2 = dst + s->linesize[index]*(h-1);
1878  for (i=0; i<h/2; i++) {
1879  for (j=0; j<w; j++)
1880  FFSWAP(int, dst[j], dst2[j]);
1881  dst += s->linesize[index];
1882  dst2 -= s->linesize[index];
1883  }
1884  }
1885  }
1886  }
1887 
1888  av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",
1889  buf_end - buf_ptr);
1890 // return buf_end - buf_ptr;
1891  return buf_ptr - buf;
1892 }
1893 
1895 {
1896  MJpegDecodeContext *s = avctx->priv_data;
1897  int i, j;
1898 
1899  if (s->picture_ptr)
1901 
1902  av_free(s->buffer);
1903  av_freep(&s->ljpeg_buffer);
1904  s->ljpeg_buffer_size = 0;
1905 
1906  for (i = 0; i < 3; i++) {
1907  for (j = 0; j < 4; j++)
1908  ff_free_vlc(&s->vlcs[i][j]);
1909  }
1910  for (i = 0; i < MAX_COMPONENTS; i++) {
1911  av_freep(&s->blocks[i]);
1912  av_freep(&s->last_nnz[i]);
1913  }
1914  return 0;
1915 }
1916 
1917 static void decode_flush(AVCodecContext *avctx)
1918 {
1919  MJpegDecodeContext *s = avctx->priv_data;
1920  s->got_picture = 0;
1921 }
1922 
1923 #if CONFIG_MJPEG_DECODER
1924 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
1925 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1926 static const AVOption options[] = {
1927  { "extern_huff", "Use external huffman table.",
1928  OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1929  { NULL },
1930 };
1931 
1932 static const AVClass mjpegdec_class = {
1933  .class_name = "MJPEG decoder",
1934  .item_name = av_default_item_name,
1935  .option = options,
1936  .version = LIBAVUTIL_VERSION_INT,
1937 };
1938 
1939 AVCodec ff_mjpeg_decoder = {
1940  .name = "mjpeg",
1941  .type = AVMEDIA_TYPE_VIDEO,
1942  .id = AV_CODEC_ID_MJPEG,
1943  .priv_data_size = sizeof(MJpegDecodeContext),
1947  .flush = decode_flush,
1948  .capabilities = CODEC_CAP_DR1,
1949  .max_lowres = 3,
1950  .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1951  .priv_class = &mjpegdec_class,
1952 };
1953 #endif
1954 #if CONFIG_THP_DECODER
1955 AVCodec ff_thp_decoder = {
1956  .name = "thp",
1957  .type = AVMEDIA_TYPE_VIDEO,
1958  .id = AV_CODEC_ID_THP,
1959  .priv_data_size = sizeof(MJpegDecodeContext),
1963  .flush = decode_flush,
1964  .capabilities = CODEC_CAP_DR1,
1965  .max_lowres = 3,
1966  .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
1967 };
1968 #endif