+/*
+ * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
+ * the TIFF tags, but still use non-default (2,2) values within the jpeg
+ * data stream itself. In order for TIFF applications to work properly
+ * - for instance to get the strip buffer size right - it is imperative
+ * that the subsampling be available before we start reading the image
+ * data normally. This function will attempt to load the first strip in
+ * order to get the sampling values from the jpeg data stream. Various
+ * hacks are various places are done to ensure this function gets called
+ * before the td_ycbcrsubsampling values are used from the directory structure,
+ * including calling TIFFGetField() for the YCBCRSUBSAMPLING field from
+ * TIFFStripSize(), and the printing code in tif_print.c.
+ *
+ * Note that JPEGPreDeocode() will produce a fairly loud warning when the
+ * discovered sampling does not match the default sampling (2,2) or whatever
+ * was actually in the tiff tags.
+ *
+ * Problems:
+ * o This code will cause one whole strip/tile of compressed data to be
+ * loaded just to get the tags right, even if the imagery is never read.
+ * It would be more efficient to just load a bit of the header, and
+ * initialize things from that.
+ *
+ * See the bug in bugzilla for details:
+ *
+ * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
+ *
+ * Frank Warmerdam, July 2002
+ */
+
+static void
+JPEGFixupTestSubsampling( TIFF * tif )
+{
+#if CHECK_JPEG_YCBCR_SUBSAMPLING == 1
+ JPEGState *sp = JState(tif);
+ TIFFDirectory *td = &tif->tif_dir;
+
+ JPEGInitializeLibJPEG( tif );
+
+ /*
+ * Some JPEG-in-TIFF files don't provide the ycbcrsampling tags,
+ * and use a sampling schema other than the default 2,2. To handle
+ * this we actually have to scan the header of a strip or tile of
+ * jpeg data to get the sampling.
+ */
+ if( !sp->cinfo.comm.is_decompressor
+ || sp->ycbcrsampling_fetched
+ || td->td_photometric != PHOTOMETRIC_YCBCR )
+ return;
+
+ sp->ycbcrsampling_fetched = 1;
+ if( TIFFIsTiled( tif ) )
+ {
+ if( !TIFFFillTile( tif, 0 ) )
+ return;
+ }
+ else
+ {
+ if( !TIFFFillStrip( tif, 0 ) )
+ return;
+ }
+
+ TIFFSetField( tif, TIFFTAG_YCBCRSUBSAMPLING,
+ (uint16) sp->h_sampling, (uint16) sp->v_sampling );
+#endif /* CHECK_JPEG_YCBCR_SUBSAMPLING == 1 */
+}
+