1 /*
2  * jcmarker.c
3  *
4  * Copyright (C) 1991-1998, Thomas G. Lane.
5  * This file is part of the Independent JPEG Group's software.
6  * For conditions of distribution and use, see the accompanying README file.
7  *
8  * This file contains routines to write JPEG datastream markers.
9  */
10 
11 #define JPEG_INTERNALS
12 #include "jinclude.h"
13 #include "jpeglib.h"
14 
15 
16 
17 /* Private state */
18 
19 typedef struct {
20   struct jpeg_marker_writer pub; /* public fields */
21 
22   unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
23 } my_marker_writer;
24 
25 typedef my_marker_writer * my_marker_ptr;
26 
27 
28 /*
29  * Basic output routines.
30  *
31  * Note that we do not support suspension while writing a marker.
32  * Therefore, an application using suspension must ensure that there is
33  * enough buffer space for the initial markers (typ. 600-700 bytes) before
34  * calling jpeg_start_compress, and enough space to write the trailing EOI
35  * (a few bytes) before calling jpeg_finish_compress.  Multipass compression
36  * modes are not supported at all with suspension, so those two are the only
37  * points where markers will be written.
38  */
39 
40 LOCAL(void)
emit_byte(j_compress_ptr cinfo,int val)41 emit_byte (j_compress_ptr cinfo, int val)
42 /* Emit a byte */
43 {
44   struct jpeg_destination_mgr * dest = cinfo->dest;
45 
46   *(dest->next_output_byte)++ = (JOCTET) val;
47   if (--dest->free_in_buffer == 0) {
48     if (! (*dest->empty_output_buffer) (cinfo))
49       ERREXIT(cinfo, JERR_CANT_SUSPEND);
50   }
51 }
52 
53 
54 LOCAL(void)
emit_marker(j_compress_ptr cinfo,JPEG_MARKER mark)55 emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
56 /* Emit a marker code */
57 {
58   emit_byte(cinfo, 0xFF);
59   emit_byte(cinfo, (int) mark);
60 }
61 
62 
63 LOCAL(void)
emit_2bytes(j_compress_ptr cinfo,int value)64 emit_2bytes (j_compress_ptr cinfo, int value)
65 /* Emit a 2-byte integer; these are always MSB first in JPEG files */
66 {
67   emit_byte(cinfo, (value >> 8) & 0xFF);
68   emit_byte(cinfo, value & 0xFF);
69 }
70 
71 
72 /*
73  * Routines to write specific marker types.
74  */
75 
76 LOCAL(int)
emit_dqt(j_compress_ptr cinfo,int index)77 emit_dqt (j_compress_ptr cinfo, int index)
78 /* Emit a DQT marker */
79 /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
80 {
81   JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
82   int prec;
83   int i;
84 
85   if (qtbl == NULL)
86     ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
87 
88   prec = 0;
89   for (i = 0; i < DCTSIZE2; i++) {
90     if (qtbl->quantval[i] > 255)
91       prec = 1;
92   }
93 
94   if (! qtbl->sent_table) {
95     emit_marker(cinfo, M_DQT);
96 
97     emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
98 
99     emit_byte(cinfo, index + (prec<<4));
100 
101     for (i = 0; i < DCTSIZE2; i++) {
102       /* The table entries must be emitted in zigzag order. */
103       unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
104       if (prec)
105 	emit_byte(cinfo, (int) (qval >> 8));
106       emit_byte(cinfo, (int) (qval & 0xFF));
107     }
108 
109     qtbl->sent_table = TRUE;
110   }
111 
112   return prec;
113 }
114 
115 
116 LOCAL(void)
emit_dht(j_compress_ptr cinfo,int index,boolean is_ac)117 emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
118 /* Emit a DHT marker */
119 {
120   JHUFF_TBL * htbl;
121   int length, i;
122 
123   if (is_ac) {
124     htbl = cinfo->ac_huff_tbl_ptrs[index];
125     index += 0x10;		/* output index has AC bit set */
126   } else {
127     htbl = cinfo->dc_huff_tbl_ptrs[index];
128   }
129 
130   if (htbl == NULL)
131     ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
132 
133   if (! htbl->sent_table) {
134     emit_marker(cinfo, M_DHT);
135 
136     length = 0;
137     for (i = 1; i <= 16; i++)
138       length += htbl->bits[i];
139 
140     emit_2bytes(cinfo, length + 2 + 1 + 16);
141     emit_byte(cinfo, index);
142 
143     for (i = 1; i <= 16; i++)
144       emit_byte(cinfo, htbl->bits[i]);
145 
146     for (i = 0; i < length; i++)
147       emit_byte(cinfo, htbl->huffval[i]);
148 
149     htbl->sent_table = TRUE;
150   }
151 }
152 
153 
154 LOCAL(void)
emit_dac(j_compress_ptr)155 emit_dac (j_compress_ptr)
156 /* Emit a DAC marker */
157 /* Since the useful info is so small, we want to emit all the tables in */
158 /* one DAC marker.  Therefore this routine does its own scan of the table. */
159 {
160 #ifdef C_ARITH_CODING_SUPPORTED
161   char dc_in_use[NUM_ARITH_TBLS];
162   char ac_in_use[NUM_ARITH_TBLS];
163   int length, i;
164   jpeg_component_info *compptr;
165 
166   for (i = 0; i < NUM_ARITH_TBLS; i++)
167     dc_in_use[i] = ac_in_use[i] = 0;
168 
169   for (i = 0; i < cinfo->comps_in_scan; i++) {
170     compptr = cinfo->cur_comp_info[i];
171     dc_in_use[compptr->dc_tbl_no] = 1;
172     ac_in_use[compptr->ac_tbl_no] = 1;
173   }
174 
175   length = 0;
176   for (i = 0; i < NUM_ARITH_TBLS; i++)
177     length += dc_in_use[i] + ac_in_use[i];
178 
179   emit_marker(cinfo, M_DAC);
180 
181   emit_2bytes(cinfo, length*2 + 2);
182 
183   for (i = 0; i < NUM_ARITH_TBLS; i++) {
184     if (dc_in_use[i]) {
185       emit_byte(cinfo, i);
186       emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
187     }
188     if (ac_in_use[i]) {
189       emit_byte(cinfo, i + 0x10);
190       emit_byte(cinfo, cinfo->arith_ac_K[i]);
191     }
192   }
193 #endif /* C_ARITH_CODING_SUPPORTED */
194 }
195 
196 
197 LOCAL(void)
emit_dri(j_compress_ptr cinfo)198 emit_dri (j_compress_ptr cinfo)
199 /* Emit a DRI marker */
200 {
201   emit_marker(cinfo, M_DRI);
202 
203   emit_2bytes(cinfo, 4);	/* fixed length */
204 
205   emit_2bytes(cinfo, (int) cinfo->restart_interval);
206 }
207 
208 
209 LOCAL(void)
emit_sof(j_compress_ptr cinfo,JPEG_MARKER code)210 emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
211 /* Emit a SOF marker */
212 {
213   int ci;
214   jpeg_component_info *compptr;
215 
216   emit_marker(cinfo, code);
217 
218   emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
219 
220   /* Make sure image isn't bigger than SOF field can handle */
221   if ((long) cinfo->image_height > 65535L ||
222       (long) cinfo->image_width > 65535L)
223     ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
224 
225   emit_byte(cinfo, cinfo->data_precision);
226   emit_2bytes(cinfo, (int) cinfo->image_height);
227   emit_2bytes(cinfo, (int) cinfo->image_width);
228 
229   emit_byte(cinfo, cinfo->num_components);
230 
231   for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
232        ci++, compptr++) {
233     emit_byte(cinfo, compptr->component_id);
234     emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
235     emit_byte(cinfo, compptr->quant_tbl_no);
236   }
237 }
238 
239 
240 LOCAL(void)
emit_sos(j_compress_ptr cinfo)241 emit_sos (j_compress_ptr cinfo)
242 /* Emit a SOS marker */
243 {
244   int i, td, ta;
245   jpeg_component_info *compptr;
246 
247   emit_marker(cinfo, M_SOS);
248 
249   emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
250 
251   emit_byte(cinfo, cinfo->comps_in_scan);
252 
253   for (i = 0; i < cinfo->comps_in_scan; i++) {
254     compptr = cinfo->cur_comp_info[i];
255     emit_byte(cinfo, compptr->component_id);
256     td = compptr->dc_tbl_no;
257     ta = compptr->ac_tbl_no;
258     if (cinfo->progressive_mode) {
259       /* Progressive mode: only DC or only AC tables are used in one scan;
260        * furthermore, Huffman coding of DC refinement uses no table at all.
261        * We emit 0 for unused field(s); this is recommended by the P&M text
262        * but does not seem to be specified in the standard.
263        */
264       if (cinfo->Ss == 0) {
265 	ta = 0;			/* DC scan */
266 	if (cinfo->Ah != 0 && !cinfo->arith_code)
267 	  td = 0;		/* no DC table either */
268       } else {
269 	td = 0;			/* AC scan */
270       }
271     }
272     emit_byte(cinfo, (td << 4) + ta);
273   }
274 
275   emit_byte(cinfo, cinfo->Ss);
276   emit_byte(cinfo, cinfo->Se);
277   emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
278 }
279 
280 
281 LOCAL(void)
emit_jfif_app0(j_compress_ptr cinfo)282 emit_jfif_app0 (j_compress_ptr cinfo)
283 /* Emit a JFIF-compliant APP0 marker */
284 {
285   /*
286    * Length of APP0 block	(2 bytes)
287    * Block ID			(4 bytes - ASCII "JFIF")
288    * Zero byte			(1 byte to terminate the ID string)
289    * Version Major, Minor	(2 bytes - major first)
290    * Units			(1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
291    * Xdpu			(2 bytes - dots per unit horizontal)
292    * Ydpu			(2 bytes - dots per unit vertical)
293    * Thumbnail X size		(1 byte)
294    * Thumbnail Y size		(1 byte)
295    */
296 
297   emit_marker(cinfo, M_APP0);
298 
299   emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
300 
301   emit_byte(cinfo, 0x4A);	/* Identifier: ASCII "JFIF" */
302   emit_byte(cinfo, 0x46);
303   emit_byte(cinfo, 0x49);
304   emit_byte(cinfo, 0x46);
305   emit_byte(cinfo, 0);
306   emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
307   emit_byte(cinfo, cinfo->JFIF_minor_version);
308   emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
309   emit_2bytes(cinfo, (int) cinfo->X_density);
310   emit_2bytes(cinfo, (int) cinfo->Y_density);
311   emit_byte(cinfo, 0);		/* No thumbnail image */
312   emit_byte(cinfo, 0);
313 }
314 
315 
316 LOCAL(void)
emit_adobe_app14(j_compress_ptr cinfo)317 emit_adobe_app14 (j_compress_ptr cinfo)
318 /* Emit an Adobe APP14 marker */
319 {
320   /*
321    * Length of APP14 block	(2 bytes)
322    * Block ID			(5 bytes - ASCII "Adobe")
323    * Version Number		(2 bytes - currently 100)
324    * Flags0			(2 bytes - currently 0)
325    * Flags1			(2 bytes - currently 0)
326    * Color transform		(1 byte)
327    *
328    * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
329    * now in circulation seem to use Version = 100, so that's what we write.
330    *
331    * We write the color transform byte as 1 if the JPEG color space is
332    * YCbCr, 2 if it's YCCK, 0 otherwise.  Adobe's definition has to do with
333    * whether the encoder performed a transformation, which is pretty useless.
334    */
335 
336   emit_marker(cinfo, M_APP14);
337 
338   emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
339 
340   emit_byte(cinfo, 0x41);	/* Identifier: ASCII "Adobe" */
341   emit_byte(cinfo, 0x64);
342   emit_byte(cinfo, 0x6F);
343   emit_byte(cinfo, 0x62);
344   emit_byte(cinfo, 0x65);
345   emit_2bytes(cinfo, 100);	/* Version */
346   emit_2bytes(cinfo, 0);	/* Flags0 */
347   emit_2bytes(cinfo, 0);	/* Flags1 */
348   switch (cinfo->jpeg_color_space) {
349   case JCS_YCbCr:
350     emit_byte(cinfo, 1);	/* Color transform = 1 */
351     break;
352   case JCS_YCCK:
353     emit_byte(cinfo, 2);	/* Color transform = 2 */
354     break;
355   default:
356     emit_byte(cinfo, 0);	/* Color transform = 0 */
357     break;
358   }
359 }
360 
361 
362 /*
363  * These routines allow writing an arbitrary marker with parameters.
364  * The only intended use is to emit COM or APPn markers after calling
365  * write_file_header and before calling write_frame_header.
366  * Other uses are not guaranteed to produce desirable results.
367  * Counting the parameter bytes properly is the caller's responsibility.
368  */
369 
370 METHODDEF(void)
write_marker_header(j_compress_ptr cinfo,int marker,unsigned int datalen)371 write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
372 /* Emit an arbitrary marker header */
373 {
374   if (datalen > (unsigned int) 65533)		/* safety check */
375     ERREXIT(cinfo, JERR_BAD_LENGTH);
376 
377   emit_marker(cinfo, (JPEG_MARKER) marker);
378 
379   emit_2bytes(cinfo, (int) (datalen + 2));	/* total length */
380 }
381 
382 METHODDEF(void)
write_marker_byte(j_compress_ptr cinfo,int val)383 write_marker_byte (j_compress_ptr cinfo, int val)
384 /* Emit one byte of marker parameters following write_marker_header */
385 {
386   emit_byte(cinfo, val);
387 }
388 
389 
390 /*
391  * Write datastream header.
392  * This consists of an SOI and optional APPn markers.
393  * We recommend use of the JFIF marker, but not the Adobe marker,
394  * when using YCbCr or grayscale data.  The JFIF marker should NOT
395  * be used for any other JPEG colorspace.  The Adobe marker is helpful
396  * to distinguish RGB, CMYK, and YCCK colorspaces.
397  * Note that an application can write additional header markers after
398  * jpeg_start_compress returns.
399  */
400 
401 METHODDEF(void)
write_file_header(j_compress_ptr cinfo)402 write_file_header (j_compress_ptr cinfo)
403 {
404   my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
405 
406   emit_marker(cinfo, M_SOI);	/* first the SOI */
407 
408   /* SOI is defined to reset restart interval to 0 */
409   marker->last_restart_interval = 0;
410 
411   if (cinfo->write_JFIF_header)	/* next an optional JFIF APP0 */
412     emit_jfif_app0(cinfo);
413   if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
414     emit_adobe_app14(cinfo);
415 }
416 
417 
418 /*
419  * Write frame header.
420  * This consists of DQT and SOFn markers.
421  * Note that we do not emit the SOF until we have emitted the DQT(s).
422  * This avoids compatibility problems with incorrect implementations that
423  * try to error-check the quant table numbers as soon as they see the SOF.
424  */
425 
426 METHODDEF(void)
write_frame_header(j_compress_ptr cinfo)427 write_frame_header (j_compress_ptr cinfo)
428 {
429   int ci, prec;
430   boolean is_baseline;
431   jpeg_component_info *compptr;
432 
433   /* Emit DQT for each quantization table.
434    * Note that emit_dqt() suppresses any duplicate tables.
435    */
436   prec = 0;
437   for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
438        ci++, compptr++) {
439     prec += emit_dqt(cinfo, compptr->quant_tbl_no);
440   }
441   /* now prec is nonzero iff there are any 16-bit quant tables. */
442 
443   /* Check for a non-baseline specification.
444    * Note we assume that Huffman table numbers won't be changed later.
445    */
446   if (cinfo->arith_code || cinfo->progressive_mode ||
447       cinfo->data_precision != 8) {
448     is_baseline = FALSE;
449   } else {
450     is_baseline = TRUE;
451     for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
452 	 ci++, compptr++) {
453       if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
454 	is_baseline = FALSE;
455     }
456     if (prec && is_baseline) {
457       is_baseline = FALSE;
458       /* If it's baseline except for quantizer size, warn the user */
459       TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
460     }
461   }
462 
463   /* Emit the proper SOF marker */
464   if (cinfo->arith_code) {
465     emit_sof(cinfo, M_SOF9);	/* SOF code for arithmetic coding */
466   } else {
467     if (cinfo->progressive_mode)
468       emit_sof(cinfo, M_SOF2);	/* SOF code for progressive Huffman */
469     else if (is_baseline)
470       emit_sof(cinfo, M_SOF0);	/* SOF code for baseline implementation */
471     else
472       emit_sof(cinfo, M_SOF1);	/* SOF code for non-baseline Huffman file */
473   }
474 }
475 
476 
477 /*
478  * Write scan header.
479  * This consists of DHT or DAC markers, optional DRI, and SOS.
480  * Compressed data will be written following the SOS.
481  */
482 
483 METHODDEF(void)
write_scan_header(j_compress_ptr cinfo)484 write_scan_header (j_compress_ptr cinfo)
485 {
486   my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
487   int i;
488   jpeg_component_info *compptr;
489 
490   if (cinfo->arith_code) {
491     /* Emit arith conditioning info.  We may have some duplication
492      * if the file has multiple scans, but it's so small it's hardly
493      * worth worrying about.
494      */
495     emit_dac(cinfo);
496   } else {
497     /* Emit Huffman tables.
498      * Note that emit_dht() suppresses any duplicate tables.
499      */
500     for (i = 0; i < cinfo->comps_in_scan; i++) {
501       compptr = cinfo->cur_comp_info[i];
502       if (cinfo->progressive_mode) {
503 	/* Progressive mode: only DC or only AC tables are used in one scan */
504 	if (cinfo->Ss == 0) {
505 	  if (cinfo->Ah == 0)	/* DC needs no table for refinement scan */
506 	    emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
507 	} else {
508 	  emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
509 	}
510       } else {
511 	/* Sequential mode: need both DC and AC tables */
512 	emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
513 	emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
514       }
515     }
516   }
517 
518   /* Emit DRI if required --- note that DRI value could change for each scan.
519    * We avoid wasting space with unnecessary DRIs, however.
520    */
521   if (cinfo->restart_interval != marker->last_restart_interval) {
522     emit_dri(cinfo);
523     marker->last_restart_interval = cinfo->restart_interval;
524   }
525 
526   emit_sos(cinfo);
527 }
528 
529 
530 /*
531  * Write datastream trailer.
532  */
533 
534 METHODDEF(void)
write_file_trailer(j_compress_ptr cinfo)535 write_file_trailer (j_compress_ptr cinfo)
536 {
537   emit_marker(cinfo, M_EOI);
538 }
539 
540 
541 /*
542  * Write an abbreviated table-specification datastream.
543  * This consists of SOI, DQT and DHT tables, and EOI.
544  * Any table that is defined and not marked sent_table = TRUE will be
545  * emitted.  Note that all tables will be marked sent_table = TRUE at exit.
546  */
547 
548 METHODDEF(void)
write_tables_only(j_compress_ptr cinfo)549 write_tables_only (j_compress_ptr cinfo)
550 {
551   int i;
552 
553   emit_marker(cinfo, M_SOI);
554 
555   for (i = 0; i < NUM_QUANT_TBLS; i++) {
556     if (cinfo->quant_tbl_ptrs[i] != NULL)
557       (void) emit_dqt(cinfo, i);
558   }
559 
560   if (! cinfo->arith_code) {
561     for (i = 0; i < NUM_HUFF_TBLS; i++) {
562       if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
563 	emit_dht(cinfo, i, FALSE);
564       if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
565 	emit_dht(cinfo, i, TRUE);
566     }
567   }
568 
569   emit_marker(cinfo, M_EOI);
570 }
571 
572 
573 /*
574  * Initialize the marker writer module.
575  */
576 
577 GLOBAL(void)
jinit_marker_writer(j_compress_ptr cinfo)578 jinit_marker_writer (j_compress_ptr cinfo)
579 {
580   my_marker_ptr marker;
581 
582   /* Create the subobject */
583   marker = (my_marker_ptr)
584     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
585 				SIZEOF(my_marker_writer));
586   cinfo->marker = (struct jpeg_marker_writer *) marker;
587   /* Initialize method pointers */
588   marker->pub.write_file_header = write_file_header;
589   marker->pub.write_frame_header = write_frame_header;
590   marker->pub.write_scan_header = write_scan_header;
591   marker->pub.write_file_trailer = write_file_trailer;
592   marker->pub.write_tables_only = write_tables_only;
593   marker->pub.write_marker_header = write_marker_header;
594   marker->pub.write_marker_byte = write_marker_byte;
595   /* Initialize private state */
596   marker->last_restart_interval = 0;
597 }
598