1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2005-06-14
 * Description : A JPEG IO file for DImg framework - save operations
 *
 * SPDX-FileCopyrightText: 2005      by Renchi Raju <renchi dot raju at gmail dot com>
 * SPDX-FileCopyrightText: 2005-2024 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#define XMD_H

#include "dimgjpegloader.h"

// C ANSI includes

extern "C"
{
#include "iccjpeg.h"
}

// Qt includes

#include <QFile>
#include <QByteArray>

// Local includes

#include "digikam_debug.h"
#include "digikam_config.h"
#include "dimgloaderobserver.h"

#ifdef Q_OS_WIN
#   include "jpegwin.h"
#endif

namespace DigikamJPEGDImgPlugin
{

bool DImgJPEGLoader::save(const QString& filePath, DImgLoaderObserver* const observer)
{
#ifdef Q_OS_WIN

    FILE* const file = _wfopen((const wchar_t*)filePath.utf16(), L"wb");

#else

    FILE* const file = fopen(filePath.toUtf8().constData(), "wb");

#endif

    if (!file)
    {
        return false;
    }

    struct jpeg_compress_struct cinfo;
    struct jpeg_error_mgr       jerr;

    // -------------------------------------------------------------------
    // JPEG error handling.

    cinfo.err                 = jpeg_std_error(&jerr);
    cinfo.err->error_exit     = dimg_jpeg_error_exit;
    cinfo.err->emit_message   = dimg_jpeg_emit_message;
    cinfo.err->output_message = dimg_jpeg_output_message;

    // try/catch cleanup

    class Q_DECL_HIDDEN CleanupData
    {
    public:

        CleanupData() = default;

        ~CleanupData()
        {
            deleteLine();

            if (f)
            {
                fclose(f);
            }
        }

        void setLine(uchar* const l)
        {
            line = l;
        }

        void setFile(FILE* const file)
        {
            f = file;
        }

        void deleteLine()
        {
            delete [] line;
            line = nullptr;
        }

    public:

        uchar* line = nullptr;
        FILE*  f    = nullptr;
    };

    CleanupData* const cleanupData = new CleanupData;
    cleanupData->setFile(file);

    try
    {
        // -------------------------------------------------------------------
        // Set JPEG compressor instance

        jpeg_create_compress(&cinfo);
        jpeg_stdio_dest(&cinfo, file);

        uint&              w   = imageWidth();<--- Variable 'w' can be declared as reference to const
        uint&              h   = imageHeight();<--- Variable 'h' can be declared as reference to const
        unsigned char*& data   = imageData();

        // Size of image.

        cinfo.image_width      = w;
        cinfo.image_height     = h;

        // Color components of image in RGB.

        cinfo.input_components = 3;
        cinfo.in_color_space   = JCS_RGB;

        QVariant qualityAttr   = imageGetAttribute(QLatin1String("quality"));
        int quality            = qualityAttr.isValid() ? qualityAttr.toInt() : 90;

        if (quality < 0)
        {
            quality = 90;
        }

        if (quality > 100)
        {
            quality = 100;
        }

        QVariant subSamplingAttr = imageGetAttribute(QLatin1String("subsampling"));
        int subsampling          = subSamplingAttr.isValid() ? subSamplingAttr.toInt() : 1;  // Medium

        jpeg_set_defaults(&cinfo);

        // bug #149578: set horizontal and vertical chroma subsampling factor to encoder.
        // See this page for details: https://en.wikipedia.org/wiki/Chroma_subsampling

        switch (subsampling)
        {
            case 1:  // 2x1, 1x1, 1x1 (4:2:2)
            {
                qCDebug(DIGIKAM_DIMG_LOG_JPEG) << "Using LibJPEG chroma-subsampling 4:2:2";
                cinfo.comp_info[0].h_samp_factor = 2;
                cinfo.comp_info[0].v_samp_factor = 1;
                cinfo.comp_info[1].h_samp_factor = 1;
                cinfo.comp_info[1].v_samp_factor = 1;
                cinfo.comp_info[2].h_samp_factor = 1;
                cinfo.comp_info[2].v_samp_factor = 1;
                break;
            }

            case 2:  // 2x2, 1x1, 1x1 (4:2:0)
            {
                qCDebug(DIGIKAM_DIMG_LOG_JPEG) << "Using LibJPEG chroma-subsampling 4:2:0";
                cinfo.comp_info[0].h_samp_factor = 2;
                cinfo.comp_info[0].v_samp_factor = 2;
                cinfo.comp_info[1].h_samp_factor = 1;
                cinfo.comp_info[1].v_samp_factor = 1;
                cinfo.comp_info[2].h_samp_factor = 1;
                cinfo.comp_info[2].v_samp_factor = 1;
                break;
            }

            case 3:  // 4x1, 1x1, 1x1 (4:1:1)
            {
                qCDebug(DIGIKAM_DIMG_LOG_JPEG) << "Using LibJPEG chroma-subsampling 4:1:1";
                cinfo.comp_info[0].h_samp_factor = 4;
                cinfo.comp_info[0].v_samp_factor = 1;
                cinfo.comp_info[1].h_samp_factor = 1;
                cinfo.comp_info[1].v_samp_factor = 1;
                cinfo.comp_info[2].h_samp_factor = 1;
                cinfo.comp_info[2].v_samp_factor = 1;
                break;
            }

            default: // 1x1, 1x1, 1x1 (4:4:4)
            {
                qCDebug(DIGIKAM_DIMG_LOG_JPEG) << "Using LibJPEG chroma-subsampling 4:4:4";
                cinfo.comp_info[0].h_samp_factor = 1;
                cinfo.comp_info[0].v_samp_factor = 1;
                cinfo.comp_info[1].h_samp_factor = 1;
                cinfo.comp_info[1].v_samp_factor = 1;
                cinfo.comp_info[2].h_samp_factor = 1;
                cinfo.comp_info[2].v_samp_factor = 1;
                break;
            }
        }

        jpeg_set_quality(&cinfo, quality, boolean(true));
        jpeg_start_compress(&cinfo, boolean(true));

        qCDebug(DIGIKAM_DIMG_LOG_JPEG) << "Using LibJPEG quality compression value: " << quality;

        if (observer)
        {
            observer->progressInfo(0.1F);
        }

        // -------------------------------------------------------------------
        // Write ICC profile.

        QByteArray profile_rawdata = m_image->getIccProfile().data();

        if (!profile_rawdata.isEmpty())
        {
            purgeExifWorkingColorSpace();
            write_icc_profile(&cinfo, (JOCTET*)profile_rawdata.data(), profile_rawdata.size());
        }

        if (observer)
        {
            observer->progressInfo(0.2F);
        }

        // -------------------------------------------------------------------
        // Write Image data.

        uchar* line       = new uchar[w * 3];
        uchar* dstPtr     = nullptr;
        uint   checkPoint = 0;
        cleanupData->setLine(line);

        if (!imageSixteenBit())     // 8 bits image.
        {
            uchar* srcPtr = data;

            for (uint j = 0 ; j < h ; ++j)
            {

                if (observer && j == checkPoint)
                {
                    checkPoint += granularity(observer, h, 0.8F);

                    if (!observer->continueQuery())
                    {
                        jpeg_destroy_compress(&cinfo);
                        delete cleanupData;

                        return false;
                    }

                    // use 0-20% for pseudo-progress, now fill 20-100%

                    observer->progressInfo(0.2F + (0.8F * (((float)j) / ((float)h))));
                }

                dstPtr = line;

                for (uint i = 0 ; i < w ; ++i)
                {
                    dstPtr[2] = srcPtr[0];  // Blue
                    dstPtr[1] = srcPtr[1];  // Green
                    dstPtr[0] = srcPtr[2];  // Red

                    srcPtr   += 4;
                    dstPtr   += 3;
                }

                jpeg_write_scanlines(&cinfo, &line, 1);
            }
        }
        else
        {
            unsigned short* srcPtr = reinterpret_cast<unsigned short*>(data);

            for (uint j = 0 ; j < h ; ++j)
            {

                if (observer && j == checkPoint)
                {
                    checkPoint += granularity(observer, h, 0.8F);

                    if (!observer->continueQuery())
                    {
                        jpeg_destroy_compress(&cinfo);
                        delete cleanupData;

                        return false;
                    }

                    // use 0-20% for pseudo-progress, now fill 20-100%

                    observer->progressInfo(0.2F + (0.8F * (((float)j) / ((float)h))));
                }

                dstPtr = line;

                for (uint i = 0 ; i < w ; ++i)
                {
                    dstPtr[2] = (srcPtr[0] * 255UL) / 65535UL;  // Blue
                    dstPtr[1] = (srcPtr[1] * 255UL) / 65535UL;  // Green
                    dstPtr[0] = (srcPtr[2] * 255UL) / 65535UL;  // Red

                    srcPtr   += 4;
                    dstPtr   += 3;
                }

                jpeg_write_scanlines(&cinfo, &line, 1);
            }
        }

        cleanupData->deleteLine();

        // -------------------------------------------------------------------

        jpeg_finish_compress(&cinfo);
        jpeg_destroy_compress(&cinfo);
        delete cleanupData;

        imageSetAttribute(QLatin1String("savedFormat"), QLatin1String("JPG"));

        saveMetadata(filePath);

        return true;
    }
    catch (std::runtime_error&)
    {
        jpeg_destroy_compress(&cinfo);
        delete cleanupData;

        return false;
    }
}

} // namespace DigikamJPEGDImgPlugin