1 /*
2   libheif example application "convert".
3 
4   MIT License
5 
6   Copyright (c) 2017 struktur AG, Joachim Bauch <bauch@struktur.de>
7 
8   Permission is hereby granted, free of charge, to any person obtaining a copy
9   of this software and associated documentation files (the "Software"), to deal
10   in the Software without restriction, including without limitation the rights
11   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12   copies of the Software, and to permit persons to whom the Software is
13   furnished to do so, subject to the following conditions:
14 
15   The above copyright notice and this permission notice shall be included in all
16   copies or substantial portions of the Software.
17 
18   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24   SOFTWARE.
25 */
26 #if defined(HAVE_CONFIG_H)
27 #include "config.h"
28 #endif
29 
30 #include <assert.h>
31 #include <errno.h>
32 #include <string.h>
33 
34 #include <iostream>
35 
36 #include "encoder_jpeg.h"
37 
JpegEncoder(int quality)38 JpegEncoder::JpegEncoder(int quality) : quality_(quality)
39 {
40   if (quality_ < 0 || quality_ > 100) {
41     quality_ = kDefaultQuality;
42   }
43 }
44 
UpdateDecodingOptions(const struct heif_image_handle * handle,struct heif_decoding_options * options) const45 void JpegEncoder::UpdateDecodingOptions(const struct heif_image_handle* handle,
46                                         struct heif_decoding_options* options) const
47 {
48   if (HasExifMetaData(handle)) {
49     options->ignore_transformations = 1;
50   }
51 
52   options->convert_hdr_to_8bit = 1;
53 }
54 
55 // static
OnJpegError(j_common_ptr cinfo)56 void JpegEncoder::OnJpegError(j_common_ptr cinfo)
57 {
58   ErrorHandler* handler = reinterpret_cast<ErrorHandler*>(cinfo->err);
59   longjmp(handler->setjmp_buffer, 1);
60 }
61 
62 #if !defined(HAVE_JPEG_WRITE_ICC_PROFILE)
63 
64 #define ICC_MARKER  (JPEG_APP0 + 2)     /* JPEG marker code for ICC */
65 #define ICC_OVERHEAD_LEN  14            /* size of non-profile data in APP2 */
66 #define MAX_BYTES_IN_MARKER  65533      /* maximum data len of a JPEG marker */
67 #define MAX_DATA_BYTES_IN_MARKER (MAX_BYTES_IN_MARKER - ICC_OVERHEAD_LEN)
68 
69 /*
70 * This routine writes the given ICC profile data into a JPEG file.  It *must*
71 * be called AFTER calling jpeg_start_compress() and BEFORE the first call to
72 * jpeg_write_scanlines().  (This ordering ensures that the APP2 marker(s) will
73 * appear after the SOI and JFIF or Adobe markers, but before all else.)
74 */
75 
76 /* This function is copied almost as is from libjpeg-turbo */
77 
78 static
jpeg_write_icc_profile(j_compress_ptr cinfo,const JOCTET * icc_data_ptr,unsigned int icc_data_len)79 void jpeg_write_icc_profile(j_compress_ptr cinfo, const JOCTET* icc_data_ptr,
80                             unsigned int icc_data_len)
81 {
82   unsigned int num_markers;     /* total number of markers we'll write */
83   int cur_marker = 1;           /* per spec, counting starts at 1 */
84   unsigned int length;          /* number of bytes to write in this marker */
85 
86   /* Calculate the number of markers we'll need, rounding up of course */
87   num_markers = icc_data_len / MAX_DATA_BYTES_IN_MARKER;
88   if (num_markers * MAX_DATA_BYTES_IN_MARKER != icc_data_len)
89     num_markers++;
90 
91   while (icc_data_len > 0) {
92     /* length of profile to put in this marker */
93     length = icc_data_len;
94     if (length > MAX_DATA_BYTES_IN_MARKER)
95       length = MAX_DATA_BYTES_IN_MARKER;
96     icc_data_len -= length;
97 
98     /* Write the JPEG marker header (APP2 code and marker length) */
99     jpeg_write_m_header(cinfo, ICC_MARKER,
100                         (unsigned int) (length + ICC_OVERHEAD_LEN));
101 
102     /* Write the marker identifying string "ICC_PROFILE" (null-terminated).  We
103      * code it in this less-than-transparent way so that the code works even if
104      * the local character set is not ASCII.
105      */
106     jpeg_write_m_byte(cinfo, 0x49);
107     jpeg_write_m_byte(cinfo, 0x43);
108     jpeg_write_m_byte(cinfo, 0x43);
109     jpeg_write_m_byte(cinfo, 0x5F);
110     jpeg_write_m_byte(cinfo, 0x50);
111     jpeg_write_m_byte(cinfo, 0x52);
112     jpeg_write_m_byte(cinfo, 0x4F);
113     jpeg_write_m_byte(cinfo, 0x46);
114     jpeg_write_m_byte(cinfo, 0x49);
115     jpeg_write_m_byte(cinfo, 0x4C);
116     jpeg_write_m_byte(cinfo, 0x45);
117     jpeg_write_m_byte(cinfo, 0x0);
118 
119     /* Add the sequencing info */
120     jpeg_write_m_byte(cinfo, cur_marker);
121     jpeg_write_m_byte(cinfo, (int) num_markers);
122 
123     /* Add the profile data */
124     while (length--) {
125       jpeg_write_m_byte(cinfo, *icc_data_ptr);
126       icc_data_ptr++;
127     }
128     cur_marker++;
129   }
130 }
131 
132 #endif  // !defined(HAVE_JPEG_WRITE_ICC_PROFILE)
133 
Encode(const struct heif_image_handle * handle,const struct heif_image * image,const std::string & filename)134 bool JpegEncoder::Encode(const struct heif_image_handle* handle,
135                          const struct heif_image* image, const std::string& filename)
136 {
137   FILE* fp = fopen(filename.c_str(), "wb");
138   if (!fp) {
139     fprintf(stderr, "Can't open %s: %s\n", filename.c_str(), strerror(errno));
140     return false;
141   }
142 
143   struct jpeg_compress_struct cinfo;
144   struct ErrorHandler jerr;
145   cinfo.err = jpeg_std_error(reinterpret_cast<struct jpeg_error_mgr*>(&jerr));
146   jerr.pub.error_exit = &JpegEncoder::OnJpegError;
147   if (setjmp(jerr.setjmp_buffer)) {
148     cinfo.err->output_message(reinterpret_cast<j_common_ptr>(&cinfo));
149     jpeg_destroy_compress(&cinfo);
150     fclose(fp);
151     return false;
152   }
153 
154   jpeg_create_compress(&cinfo);
155   jpeg_stdio_dest(&cinfo, fp);
156 
157   cinfo.image_width = heif_image_get_width(image, heif_channel_Y);
158   cinfo.image_height = heif_image_get_height(image, heif_channel_Y);
159   cinfo.input_components = 3;
160   cinfo.in_color_space = JCS_YCbCr;
161   jpeg_set_defaults(&cinfo);
162   static const boolean kForceBaseline = TRUE;
163   jpeg_set_quality(&cinfo, quality_, kForceBaseline);
164   static const boolean kWriteAllTables = TRUE;
165   jpeg_start_compress(&cinfo, kWriteAllTables);
166 
167   size_t exifsize = 0;
168   uint8_t* exifdata = GetExifMetaData(handle, &exifsize);
169   if (exifdata && exifsize > 4) {
170     static const uint8_t kExifMarker = JPEG_APP0 + 1;
171     jpeg_write_marker(&cinfo, kExifMarker, exifdata + 4,
172                       static_cast<unsigned int>(exifsize - 4));
173     free(exifdata);
174   }
175 
176   size_t profile_size = heif_image_handle_get_raw_color_profile_size(handle);
177   if (profile_size > 0) {
178     uint8_t* profile_data = static_cast<uint8_t*>(malloc(profile_size));
179     heif_image_handle_get_raw_color_profile(handle, profile_data);
180     jpeg_write_icc_profile(&cinfo, profile_data, (unsigned int) profile_size);
181     free(profile_data);
182   }
183 
184 
185   if (heif_image_get_bits_per_pixel(image, heif_channel_Y) != 8) {
186     fprintf(stderr, "JPEG writer cannot handle image with >8 bpp.\n");
187     return false;
188   }
189 
190 
191   int stride_y;
192   const uint8_t* row_y = heif_image_get_plane_readonly(image, heif_channel_Y,
193                                                        &stride_y);
194   int stride_u;
195   const uint8_t* row_u = heif_image_get_plane_readonly(image, heif_channel_Cb,
196                                                        &stride_u);
197   int stride_v;
198   const uint8_t* row_v = heif_image_get_plane_readonly(image, heif_channel_Cr,
199                                                        &stride_v);
200 
201   JSAMPARRAY buffer = cinfo.mem->alloc_sarray(
202       reinterpret_cast<j_common_ptr>(&cinfo), JPOOL_IMAGE,
203       cinfo.image_width * cinfo.input_components, 1);
204   JSAMPROW row[1] = {buffer[0]};
205 
206   while (cinfo.next_scanline < cinfo.image_height) {
207     size_t offset_y = cinfo.next_scanline * stride_y;
208     const uint8_t* start_y = &row_y[offset_y];
209     size_t offset_u = (cinfo.next_scanline / 2) * stride_u;
210     const uint8_t* start_u = &row_u[offset_u];
211     size_t offset_v = (cinfo.next_scanline / 2) * stride_v;
212     const uint8_t* start_v = &row_v[offset_v];
213 
214     JOCTET* bufp = buffer[0];
215     for (JDIMENSION x = 0; x < cinfo.image_width; ++x) {
216       *bufp++ = start_y[x];
217       *bufp++ = start_u[x / 2];
218       *bufp++ = start_v[x / 2];
219     }
220     jpeg_write_scanlines(&cinfo, row, 1);
221   }
222   jpeg_finish_compress(&cinfo);
223   fclose(fp);
224   jpeg_destroy_compress(&cinfo);
225   return true;
226 }
227