jpeg-load.c 60.4 KB
Newer Older
Elliot Lee's avatar
Elliot Lee committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* The GIMP -- an image manipulation program
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
16
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Elliot Lee's avatar
Elliot Lee committed
17
18
19
20
21
22
23
24
25
26
 */

/* JPEG loading and saving file filter for the GIMP
 *  -Peter Mattis
 *
 * This filter is heavily based upon the "example.c" file in libjpeg.
 * In fact most of the loading and saving code was simply cut-and-pasted
 *  from that file. The filter, therefore, also uses libjpeg.
 */

27
28
29
30
31
32
33
34
35
36
37
/* 11-JAN-99 - Added support for JPEG comments and Progressive saves.
 *  -pete whiting <pwhiting@sprint.net>
 *
 * Comments of size up to 32k can be stored in the header of jpeg
 * files.  (They are not compressed.)  The JPEG specs and libraries
 * support the storing of multiple comments.  The behavior of this
 * code is to merge all comments in a loading image into a single
 * comment (putting \n between each) and attach that string as a
 * parasite - gimp-comment - to the image.  When saving, the image is
 * checked to see if it has the gimp-comment parasite - if so, that is
 * used as the default comment in the save dialog.  Further, the other
38
 * jpeg parameters (quality, smoothing, compression and progressive)
39
40
 * are attached to the image as a parasite.  This allows the
 * parameters to remain consistent between saves.  I was not able to
41
 * figure out how to determine the quality, smoothing or compression
42
43
44
45
46
47
 * values of an image as it is being loaded, but the code is there to
 * support it if anyone knows how.  Progressive mode is a method of
 * saving the image such that as a browser (or other app supporting
 * progressive loads - gimp doesn't) loads the image it first gets a
 * low res version displayed and then the image is progressively
 * enhanced until you get the final version.  It doesn't add any size
48
49
50
 * to the image (actually it often results in smaller file size) - the
 * only draw backs are that progressive jpegs are not supported by some
 * older viewers/browsers, and some might find it annoying.
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
/* 
 * 21-AUG-99 - Added support for JPEG previews, subsampling,
 *             non-baseline JPEGs, restart markers and DCT method choice
 * - Steinar H. Gunderson <sgunderson@bigfoot.com>
 *
 * A small preview appears and changes according to the changes to the
 * compression options. The image itself works as a much bigger preview.
 * For slower machines, the save operation (not the load operation) is
 * done in the background, with a standard GTK+ idle loop, which turned
 * out to be the most portable way. Win32 porters shouldn't have much
 * difficulty porting my changes (at least I hope so...).
 *
 * Subsampling is a pretty obscure feature, but I thought it might be nice
 * to have it in anyway, for people to play with :-) Does anybody have
 * any better suggestions than the ones I've put in the menu? (See wizard.doc
 * from the libjpeg distribution for a tiny bit of information on subsampling.)
 *
 * A baseline JPEG is often larger and/or of worse quality than a non-baseline
 * one (especially at low quality settings), but all decoders are guaranteed
 * to read baseline JPEGs (I think). Not all will read a non-baseline one.
 *
 * Restart markers are useful if you are transmitting the image over an
 * unreliable network. If a file gets corrupted, it will only be corrupted
 * up to the next restart marker. Of course, if there are no restart markers,
 * the rest of the image will be corrupted. Restart markers take up extra
 * space. The libjpeg developers recommend a restart every 1 row for
 * transmitting images over unreliable networks, such as Usenet.
 *
 * The DCT method is said by the libjpeg docs to _only_ influence quality vs.
 * speed, and nothing else. However, I've found that there _are_ size
 * differences. Fast integer, on the other hand, is faster than integer,
 * which in turn is faster than FP. According to the libjpeg docs (and I
 * believe it's true), FP has only a theoretical advantage in quality, and
 * will be slower than the two other methods, unless you're blessed with
 * very a fast FPU. (In addition, images might not be identical on
 * different types of FP hardware.)
 *
 * ...and thus ends my additions to the JPEG plug-in. I hope. *sigh* :-)
 */

93
94
95
96
97
98
99
100
101
102
103
104
105
/* 
 * 21-AUG-99 - Bunch O' Fixes.
 * - Adam D. Moss <adam@gimp.org>
 *
 * We now correctly create an alpha-padded layer for our preview --
 * having a non-background non-alpha layer is a no-no in GIMP.
 *
 * I've also tweaked the GIMP undo API a little and changed the JPEG
 * plugin to use gimp_image_{freeze,thaw}_undo so that it doesn't store
 * up a whole load of superfluous tile data every time the preview is
 * changed.
 */

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
 * 22-DEC-99 - volatiles added
 * - Austin Donnelly <austin@gimp.org>
 *
 * When gcc complains a variable may be clobbered by a longjmp or
 * vfork, it means the following: setjmp() was called by the JPEG
 * library for error recovery purposes, but gcc is keeping some
 * variables in registers without updating the memory locations on the
 * stack consistently.  If JPEG error recovery is every invoked, the
 * values of these variable will be inconsistent.  This is almost
 * always a bug, but not one that's commonly seen unless JPEG recovery
 * code is exercised frequently.  The correct solution is to tell gcc
 * to keep the stack version of the affected variables up to date, by
 * using the "volatile" keyword.   Here endeth the lesson.
 */

122
123
124
125
126
127
128
129
/*
 * 4-SEP-01 - remove the use of GtkText
 * - DindinX <David@dindinx.org>
 *
 * The new version of GTK+ does not support GtkText anymore.
 * I've just replaced the one used for the image comment by
 * a GtkTextView/GtkTextBuffer couple;
 */
130

131
132
133
134
135
136
137
138
139
140
141
/*
 * 22-JUN-03 - add support for keeping EXIF information
 * - Dave Neary <bolsh@gimp.org>
 *
 * This is little more than a modified version fo a patch from the 
 * libexif owner (Lutz Muller) which attaches exif information to
 * a GimpImage, and if there is infoprmation available at save 
 * time, writes it out. No modification of the exif data is 
 * currently possible.
 */

Sven Neumann's avatar
Sven Neumann committed
142
#include "config.h"   /* configure cares about HAVE_PROGRESSIVE_JPEG */
Tor Lillqvist's avatar
Tor Lillqvist committed
143

Sven Neumann's avatar
Sven Neumann committed
144
145
146
#include <glib.h>     /* We want glib.h first because of some
		       * pretty obscure Win32 compilation issues.
		       */
147
#include <errno.h>
Elliot Lee's avatar
Elliot Lee committed
148
#include <setjmp.h>
149
#include <signal.h>
Elliot Lee's avatar
Elliot Lee committed
150
151
152
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
153
#include <sys/types.h>
154
#include <sys/stat.h>
Tor Lillqvist's avatar
Tor Lillqvist committed
155
#ifdef HAVE_UNISTD_H
156
#include <unistd.h>
Tor Lillqvist's avatar
Tor Lillqvist committed
157
#endif
Elliot Lee's avatar
Elliot Lee committed
158
#include <jpeglib.h>
159
#include <jerror.h>
160

161
162
163
164
#ifdef HAVE_EXIF
#include <libexif/exif-data.h>
#endif /* HAVE_EXIF */

Michael Natterer's avatar
Michael Natterer committed
165
166
#include <libgimp/gimp.h>
#include <libgimp/gimpui.h>
167

168
169
#include "libgimp/stdplugins-intl.h"

Sven Neumann's avatar
Sven Neumann committed
170
#define SCALE_WIDTH         125
Elliot Lee's avatar
Elliot Lee committed
171

172
173
/* if you are not compiling this from inside the gimp tree, you have to  */
/* take care yourself if your JPEG library supports progressive mode     */
174
/* #undef HAVE_PROGRESSIVE_JPEG   if your library doesn't support it     */
175
176
/* #define HAVE_PROGRESSIVE_JPEG  if your library knows how to handle it */

177
178
/* See bugs #63610 and #61088 for a discussion about the quality settings */
#define DEFAULT_QUALITY     0.85
Sven Neumann's avatar
Sven Neumann committed
179
180
#define DEFAULT_SMOOTHING   0.0
#define DEFAULT_OPTIMIZE    1
181
#define DEFAULT_PROGRESSIVE 0
Sven Neumann's avatar
Sven Neumann committed
182
183
184
185
#define DEFAULT_BASELINE    1
#define DEFAULT_SUBSMP      0
#define DEFAULT_RESTART     0
#define DEFAULT_DCT         0
186
#define DEFAULT_PREVIEW     0
187
#define DEFAULT_EXIF        1
188
189

/* sg - these should not be global... */
190
191
192
193
194
195
static gint32 volatile  image_ID_global       = -1;
static gint32           orig_image_ID_global  = -1;
static gint32           drawable_ID_global    = -1;
static gint32           layer_ID_global       = -1;
static GtkWidget       *preview_size          = NULL;
static GimpDrawable    *drawable_global       = NULL;
196
static gboolean         undo_touched          = FALSE;
197
 
Elliot Lee's avatar
Elliot Lee committed
198
199
200
201
typedef struct
{
  gdouble quality;
  gdouble smoothing;
202
203
204
205
206
207
208
  gint    optimize;
  gint    progressive;
  gint    baseline;
  gint    subsmp;
  gint    restart;
  gint    dct;
  gint    preview;
209
  gint    save_exif;
Elliot Lee's avatar
Elliot Lee committed
210
211
212
213
} JpegSaveVals;

typedef struct
{
214
  gboolean  run;
Elliot Lee's avatar
Elliot Lee committed
215
216
} JpegSaveInterface;

217
218
219
typedef struct 
{
  struct jpeg_compress_struct cinfo;
220
221
  gint          tile_height;
  FILE         *outfile;
222
  gboolean      has_alpha;
223
224
225
226
  gint          rowstride;
  guchar       *temp;
  guchar       *data;
  guchar       *src;
Sven Neumann's avatar
Sven Neumann committed
227
228
  GimpDrawable *drawable;
  GimpPixelRgn  pixel_rgn;
229
  const gchar  *file_name;
Sven Neumann's avatar
Sven Neumann committed
230
231
232
233
  gboolean      abort_me;
} PreviewPersistent;

static gboolean *abort_me = NULL;
Sven Neumann's avatar
Sven Neumann committed
234

235

Elliot Lee's avatar
Elliot Lee committed
236
237
/* Declare local functions.
 */
238
static void     query                     (void);
239
static void     run                       (const gchar      *name,
240
					   gint              nparams,
241
					   const GimpParam  *param,
242
243
					   gint             *nreturn_vals,
					   GimpParam       **return_vals);
244
static gint32   load_image                (const gchar      *filename, 
245
					   GimpRunMode       runmode, 
246
					   gboolean          preview);
247
static gboolean save_image                (const gchar      *filename,
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
					   gint32            image_ID,
					   gint32            drawable_ID,
					   gint32            orig_image_ID,
					   gboolean          preview);

static gboolean save_dialog                (void);

static void     save_close_callback        (GtkWidget       *widget,
					    gpointer         data);
static void     save_ok_callback           (GtkWidget       *widget,
					    gpointer         data);
static void     save_restart_toggle_update (GtkWidget       *toggle,
					    GtkAdjustment   *adjustment);
static void     save_restart_update        (GtkAdjustment   *adjustment,
					    GtkWidget       *toggle);

static void     make_preview               (void);
static void     destroy_preview            (void);

static void     menu_callback              (GtkWidget       *widget, 
					    gpointer         data);
269

Elliot Lee's avatar
Elliot Lee committed
270

Sven Neumann's avatar
Sven Neumann committed
271
GimpPlugInInfo PLUG_IN_INFO =
Elliot Lee's avatar
Elliot Lee committed
272
{
273
274
275
276
  NULL,  /* init_proc  */
  NULL,  /* quit_proc  */
  query, /* query_proc */
  run,   /* run_proc   */
Elliot Lee's avatar
Elliot Lee committed
277
278
279
280
};

static JpegSaveVals jsvals =
{
281
282
283
  DEFAULT_QUALITY,
  DEFAULT_SMOOTHING,
  DEFAULT_OPTIMIZE,
284
285
286
287
288
  DEFAULT_PROGRESSIVE,
  DEFAULT_BASELINE,
  DEFAULT_SUBSMP,
  DEFAULT_RESTART,
  DEFAULT_DCT,
289
290
  DEFAULT_PREVIEW,
  DEFAULT_EXIF
Elliot Lee's avatar
Elliot Lee committed
291
292
293
294
295
296
297
298
};

static JpegSaveInterface jsint =
{
  FALSE   /*  run  */
};


Sven Neumann's avatar
Sven Neumann committed
299
static gchar     *image_comment         = NULL;
300
301
302
static GtkWidget *restart_markers_scale = NULL;
static GtkWidget *restart_markers_label = NULL;

303
304
305
#ifdef HAVE_EXIF
static ExifData  *exif_data             = NULL;
#endif /* HAVE_EXIF */
Sven Neumann's avatar
Sven Neumann committed
306

Elliot Lee's avatar
Elliot Lee committed
307
308
309
MAIN ()

static void
310
query (void)
Elliot Lee's avatar
Elliot Lee committed
311
{
Sven Neumann's avatar
Sven Neumann committed
312
  static GimpParamDef load_args[] =
Elliot Lee's avatar
Elliot Lee committed
313
  {
Sven Neumann's avatar
Sven Neumann committed
314
315
316
    { GIMP_PDB_INT32,    "run_mode",     "Interactive, non-interactive" },
    { GIMP_PDB_STRING,   "filename",     "The name of the file to load" },
    { GIMP_PDB_STRING,   "raw_filename", "The name of the file to load" }
Elliot Lee's avatar
Elliot Lee committed
317
  };
Sven Neumann's avatar
Sven Neumann committed
318
  static GimpParamDef load_return_vals[] =
Elliot Lee's avatar
Elliot Lee committed
319
  {
Sven Neumann's avatar
Sven Neumann committed
320
    { GIMP_PDB_IMAGE,   "image",         "Output image" }
Elliot Lee's avatar
Elliot Lee committed
321
322
  };

Sven Neumann's avatar
Sven Neumann committed
323
  static GimpParamDef save_args[] =
Elliot Lee's avatar
Elliot Lee committed
324
  {
Sven Neumann's avatar
Sven Neumann committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    { GIMP_PDB_INT32,    "run_mode",     "Interactive, non-interactive" },
    { GIMP_PDB_IMAGE,    "image",        "Input image" },
    { GIMP_PDB_DRAWABLE, "drawable",     "Drawable to save" },
    { GIMP_PDB_STRING,   "filename",     "The name of the file to save the image in" },
    { GIMP_PDB_STRING,   "raw_filename", "The name of the file to save the image in" },
    { GIMP_PDB_FLOAT,    "quality",      "Quality of saved image (0 <= quality <= 1)" },
    { GIMP_PDB_FLOAT,    "smoothing",    "Smoothing factor for saved image (0 <= smoothing <= 1)" },
    { GIMP_PDB_INT32,    "optimize",     "Optimization of entropy encoding parameters (0/1)" },
    { GIMP_PDB_INT32,    "progressive",  "Enable progressive jpeg image loading - ignored if not compiled with HAVE_PROGRESSIVE_JPEG (0/1)" },
    { GIMP_PDB_STRING,   "comment",      "Image comment" },
    { GIMP_PDB_INT32,    "subsmp",       "The subsampling option number" },
    { GIMP_PDB_INT32,    "baseline",     "Force creation of a baseline JPEG (non-baseline JPEGs can't be read by all decoders) (0/1)" },
    { GIMP_PDB_INT32,    "restart",      "Frequency of restart markers (in rows, 0 = no restart markers)" },
    { GIMP_PDB_INT32,    "dct",          "DCT algorithm to use (speed/quality tradeoff)" }
Elliot Lee's avatar
Elliot Lee committed
339
340
341
  };

  gimp_install_procedure ("file_jpeg_load",
Marc Lehmann's avatar
Marc Lehmann committed
342
343
                          "loads files in the JPEG file format",
                          "loads files in the JPEG file format",
344
                          "Spencer Kimball, Peter Mattis & others",
Elliot Lee's avatar
Elliot Lee committed
345
                          "Spencer Kimball & Peter Mattis",
346
                          "1995-1999",
Elliot Lee's avatar
Elliot Lee committed
347
348
			  "<Load>/Jpeg",
			  NULL,
Sven Neumann's avatar
Sven Neumann committed
349
                          GIMP_PLUGIN,
350
351
                          G_N_ELEMENTS (load_args),
                          G_N_ELEMENTS (load_return_vals),
Elliot Lee's avatar
Elliot Lee committed
352
353
354
                          load_args, load_return_vals);

  gimp_install_procedure ("file_jpeg_save",
Marc Lehmann's avatar
Marc Lehmann committed
355
356
                          "saves files in the JPEG file format",
                          "saves files in the lossy, widely supported JPEG format",
357
                          "Spencer Kimball, Peter Mattis & others",
Elliot Lee's avatar
Elliot Lee committed
358
                          "Spencer Kimball & Peter Mattis",
359
                          "1995-1999",
360
                          "<Save>/JPEG",
Elliot Lee's avatar
Elliot Lee committed
361
			  "RGB*, GRAY*",
Sven Neumann's avatar
Sven Neumann committed
362
                          GIMP_PLUGIN,
363
                          G_N_ELEMENTS (save_args), 0,
Elliot Lee's avatar
Elliot Lee committed
364
365
                          save_args, NULL);

366
367
368
  gimp_register_magic_load_handler ("file_jpeg_load",
				    "jpg,jpeg",
				    "",
369
				    "6,string,JFIF,6,string,Exif");
370
371
372
  gimp_register_save_handler       ("file_jpeg_save",
				    "jpg,jpeg",
				    "");
Elliot Lee's avatar
Elliot Lee committed
373
374
375
}

static void
376
377
378
379
380
run (const gchar      *name,
     gint              nparams,
     const GimpParam  *param,
     gint             *nreturn_vals,
     GimpParam       **return_vals)
Elliot Lee's avatar
Elliot Lee committed
381
{
382
  static GimpParam      values[2];
383
  GimpRunMode           run_mode;
384
385
386
387
388
389
390
391
  GimpPDBStatusType     status = GIMP_PDB_SUCCESS;
  gint32                image_ID;
  gint32                drawable_ID;
  gint32                orig_image_ID;
  gint32                display_ID = -1;
  GimpParasite         *parasite;
  gboolean              err;
  GimpExportReturnType  export = GIMP_EXPORT_CANCEL;
Elliot Lee's avatar
Elliot Lee committed
392
393
394

  run_mode = param[0].data.d_int32;

395
396
  INIT_I18N ();

Elliot Lee's avatar
Elliot Lee committed
397
  *nreturn_vals = 1;
398
  *return_vals  = values;
Sven Neumann's avatar
Sven Neumann committed
399
400
  values[0].type          = GIMP_PDB_STATUS;
  values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR;
401

Elliot Lee's avatar
Elliot Lee committed
402
403
  if (strcmp (name, "file_jpeg_load") == 0)
    {
404
      image_ID = load_image (param[1].data.d_string, run_mode, FALSE);
Elliot Lee's avatar
Elliot Lee committed
405
406
407
408

      if (image_ID != -1)
	{
	  *nreturn_vals = 2;
Sven Neumann's avatar
Sven Neumann committed
409
	  values[1].type         = GIMP_PDB_IMAGE;
Elliot Lee's avatar
Elliot Lee committed
410
411
412
413
	  values[1].data.d_image = image_ID;
	}
      else
	{
Sven Neumann's avatar
Sven Neumann committed
414
	  status = GIMP_PDB_EXECUTION_ERROR;
Elliot Lee's avatar
Elliot Lee committed
415
416
417
418
	}
    }
  else if (strcmp (name, "file_jpeg_save") == 0)
    {
Sven Neumann's avatar
Sven Neumann committed
419
420
421
422
423
424
      image_ID = orig_image_ID = param[1].data.d_int32;
      drawable_ID = param[2].data.d_int32;

       /*  eventually export the image */ 
      switch (run_mode)
	{
Sven Neumann's avatar
Sven Neumann committed
425
426
	case GIMP_RUN_INTERACTIVE:
	case GIMP_RUN_WITH_LAST_VALS:
427
	  gimp_ui_init ("jpeg", FALSE);
Sven Neumann's avatar
Sven Neumann committed
428
	  export = gimp_export_image (&image_ID, &drawable_ID, "JPEG", 
429
430
				      (GIMP_EXPORT_CAN_HANDLE_RGB |
				       GIMP_EXPORT_CAN_HANDLE_GRAY));
Sven Neumann's avatar
Sven Neumann committed
431
	  switch (export)
Sven Neumann's avatar
Sven Neumann committed
432
	    {
433
	    case GIMP_EXPORT_EXPORT: 
Sven Neumann's avatar
Sven Neumann committed
434
	      display_ID = gimp_display_new (image_ID);
435
	      gimp_image_set_filename (image_ID, _("Export Preview"));
Sven Neumann's avatar
Sven Neumann committed
436
	      gimp_displays_flush ();
Sven Neumann's avatar
Sven Neumann committed
437
	      break;
438
	    case GIMP_EXPORT_IGNORE:
Sven Neumann's avatar
Sven Neumann committed
439
	      break;
440
	    case GIMP_EXPORT_CANCEL:
Sven Neumann's avatar
Sven Neumann committed
441
	      values[0].data.d_status = GIMP_PDB_CANCEL;
Sven Neumann's avatar
Sven Neumann committed
442
443
	      return;
	      break;
Sven Neumann's avatar
Sven Neumann committed
444
445
446
447
448
	    }
	  break;
	default:
	  break;
	}
Sven Neumann's avatar
Sven Neumann committed
449
      
450
451
452
453
454
#ifdef HAVE_EXIF
      exif_data_unref (exif_data);
      exif_data = NULL;
#endif /* HAVE_EXIF */

Sven Neumann's avatar
Sven Neumann committed
455
456
      g_free (image_comment);
      image_comment = NULL;
457
    
Marc Lehmann's avatar
Marc Lehmann committed
458
      parasite = gimp_image_parasite_find (orig_image_ID, "gimp-comment");
Sven Neumann's avatar
Sven Neumann committed
459
460
461
      if (parasite) 
	{
	  image_comment = g_strdup (parasite->data);
462
	  gimp_parasite_free (parasite);
Sven Neumann's avatar
Sven Neumann committed
463
	}
464

465
466
467
468
469
470
471
472
473
#ifdef HAVE_EXIF
      parasite = gimp_image_parasite_find (orig_image_ID, "jpeg-exif-data");
      if (parasite)
        {
          exif_data = exif_data_new_from_data (parasite->data, parasite->size);
          gimp_parasite_free (parasite);
        }
#endif /* HAVE_EXIF */

474
475
476
      jsvals.quality     = DEFAULT_QUALITY;
      jsvals.smoothing   = DEFAULT_SMOOTHING;
      jsvals.optimize    = DEFAULT_OPTIMIZE;
477
      jsvals.progressive = DEFAULT_PROGRESSIVE;
478
479
480
481
482
      jsvals.baseline    = DEFAULT_BASELINE;
      jsvals.subsmp      = DEFAULT_SUBSMP;
      jsvals.restart     = DEFAULT_RESTART;
      jsvals.dct         = DEFAULT_DCT;
      jsvals.preview     = DEFAULT_PREVIEW;
483
      jsvals.save_exif   = DEFAULT_EXIF;
484

Elliot Lee's avatar
Elliot Lee committed
485
486
      switch (run_mode)
	{
Sven Neumann's avatar
Sven Neumann committed
487
	case GIMP_RUN_INTERACTIVE:
Elliot Lee's avatar
Elliot Lee committed
488
489
490
	  /*  Possibly retrieve data  */
	  gimp_get_data ("file_jpeg_save", &jsvals);

491
	  /* load up the previously used values */
492
493
	  parasite = gimp_image_parasite_find (orig_image_ID,
					       "jpeg-save-options");
494
	  if (parasite)
Sven Neumann's avatar
Sven Neumann committed
495
496
497
498
499
500
501
502
503
504
	    {
	      jsvals.quality     = ((JpegSaveVals *)parasite->data)->quality;
	      jsvals.smoothing   = ((JpegSaveVals *)parasite->data)->smoothing;
	      jsvals.optimize    = ((JpegSaveVals *)parasite->data)->optimize;
	      jsvals.progressive = ((JpegSaveVals *)parasite->data)->progressive;
	      jsvals.baseline    = ((JpegSaveVals *)parasite->data)->baseline;
	      jsvals.subsmp      = ((JpegSaveVals *)parasite->data)->subsmp;
	      jsvals.restart     = ((JpegSaveVals *)parasite->data)->restart;
	      jsvals.dct         = ((JpegSaveVals *)parasite->data)->dct;
	      jsvals.preview     = ((JpegSaveVals *)parasite->data)->preview;
505
	      jsvals.save_exif   = ((JpegSaveVals *)parasite->data)->save_exif;
506
	      gimp_parasite_free (parasite);
Sven Neumann's avatar
Sven Neumann committed
507
	    }
508

509
510
511
512
513
514
515
516
517
518
          if (jsvals.preview)
            {
              /* we start an undo_group and immediately freeze undo saving
                 so that we can avoid sucking up tile cache with our unneeded
                 preview steps. */
              gimp_undo_push_group_start (image_ID);
              gimp_image_undo_freeze (image_ID);

              undo_touched = TRUE;
            }
519

520
521
	  /* prepare for the preview */
	  image_ID_global = image_ID;
Sven Neumann's avatar
Sven Neumann committed
522
523
	  orig_image_ID_global = orig_image_ID;
	  drawable_ID_global = drawable_ID;
524
 
Elliot Lee's avatar
Elliot Lee committed
525
	  /*  First acquire information with a dialog  */
526
	  err = save_dialog ();
Sven Neumann's avatar
Sven Neumann committed
527
 
528
529
530
531
532
533
          if (undo_touched)
            {
              /* thaw undo saving and end the undo_group. */
              gimp_image_undo_thaw (image_ID);
              gimp_undo_push_group_end (image_ID);
            }
534
535

          if (!err)
Sven Neumann's avatar
Sven Neumann committed
536
	    status = GIMP_PDB_CANCEL;
Elliot Lee's avatar
Elliot Lee committed
537
538
	  break;

Sven Neumann's avatar
Sven Neumann committed
539
	case GIMP_RUN_NONINTERACTIVE:
Elliot Lee's avatar
Elliot Lee committed
540
	  /*  Make sure all the arguments are there!  */
541
	  /*  pw - added two more progressive and comment */
542
	  /*  sg - added subsampling, preview, baseline, restarts and DCT */
Sven Neumann's avatar
Sven Neumann committed
543
	  if (nparams != 14)
544
	    {
Sven Neumann's avatar
Sven Neumann committed
545
	      status = GIMP_PDB_CALLING_ERROR;
546
547
	    }
	  else
Elliot Lee's avatar
Elliot Lee committed
548
	    {
549
550
551
552
553
554
	      /* Once the PDB gets default parameters, remove this hack */
	      if (param[5].data.d_float > 0.05)
		{
		  jsvals.quality     = param[5].data.d_float;
		  jsvals.smoothing   = param[6].data.d_float;
		  jsvals.optimize    = param[7].data.d_int32;
555
#ifdef HAVE_PROGRESSIVE_JPEG
556
		  jsvals.progressive = param[8].data.d_int32;
557
#endif /* HAVE_PROGRESSIVE_JPEG */
558
559
560
561
562
563
564
565
566
567
568
		  jsvals.baseline    = param[11].data.d_int32;
		  jsvals.subsmp      = param[10].data.d_int32;
		  jsvals.restart     = param[12].data.d_int32;
		  jsvals.dct         = param[13].data.d_int32;

		  /* free up the default -- wasted some effort earlier */
		  g_free (image_comment);
		  image_comment = g_strdup (param[9].data.d_string);
		}

	      jsvals.preview = FALSE;
569
570

	      if (jsvals.quality < 0.0 || jsvals.quality > 1.0)
Sven Neumann's avatar
Sven Neumann committed
571
		status = GIMP_PDB_CALLING_ERROR;
572
	      else if (jsvals.smoothing < 0.0 || jsvals.smoothing > 1.0)
Sven Neumann's avatar
Sven Neumann committed
573
		status = GIMP_PDB_CALLING_ERROR;
574
	      else if (jsvals.subsmp < 0 || jsvals.subsmp > 2)
Sven Neumann's avatar
Sven Neumann committed
575
		status = GIMP_PDB_CALLING_ERROR;
576
	      else if (jsvals.dct < 0 || jsvals.dct > 2)
Sven Neumann's avatar
Sven Neumann committed
577
		status = GIMP_PDB_CALLING_ERROR;
Elliot Lee's avatar
Elliot Lee committed
578
	    }
Manish Singh's avatar
Manish Singh committed
579
	  break;
Elliot Lee's avatar
Elliot Lee committed
580

Sven Neumann's avatar
Sven Neumann committed
581
	case GIMP_RUN_WITH_LAST_VALS:
Elliot Lee's avatar
Elliot Lee committed
582
583
	  /*  Possibly retrieve data  */
	  gimp_get_data ("file_jpeg_save", &jsvals);
584

585
586
	  parasite = gimp_image_parasite_find (orig_image_ID,
					       "jpeg-save-options");
587
	  if (parasite)
Sven Neumann's avatar
Sven Neumann committed
588
589
590
591
592
593
594
595
596
597
	    {
	      jsvals.quality     = ((JpegSaveVals *)parasite->data)->quality;
	      jsvals.smoothing   = ((JpegSaveVals *)parasite->data)->smoothing;
	      jsvals.optimize    = ((JpegSaveVals *)parasite->data)->optimize;
	      jsvals.progressive = ((JpegSaveVals *)parasite->data)->progressive;
	      jsvals.baseline    = ((JpegSaveVals *)parasite->data)->baseline;
	      jsvals.subsmp      = ((JpegSaveVals *)parasite->data)->subsmp;
	      jsvals.restart     = ((JpegSaveVals *)parasite->data)->restart;
	      jsvals.dct         = ((JpegSaveVals *)parasite->data)->dct;
	      jsvals.preview     = FALSE;
598
	      gimp_parasite_free (parasite);
Sven Neumann's avatar
Sven Neumann committed
599
	    }
Elliot Lee's avatar
Elliot Lee committed
600
601
602
603
604
605
	  break;

	default:
	  break;
	}

Sven Neumann's avatar
Sven Neumann committed
606
      if (status == GIMP_PDB_SUCCESS)
Elliot Lee's avatar
Elliot Lee committed
607
	{
608
609
610
611
612
613
614
615
616
617
618
	  if (save_image (param[3].data.d_string,
			  image_ID,
			  drawable_ID,
			  orig_image_ID,
			  FALSE))
	    {
	      /*  Store mvals data  */
	      gimp_set_data ("file_jpeg_save", &jsvals, sizeof (JpegSaveVals));
	    }
	  else
	    {
Sven Neumann's avatar
Sven Neumann committed
619
	      status = GIMP_PDB_EXECUTION_ERROR;
620
	    }
Elliot Lee's avatar
Elliot Lee committed
621
	}
622

623
      if (export == GIMP_EXPORT_EXPORT)
Sven Neumann's avatar
Sven Neumann committed
624
	{
Sven Neumann's avatar
Sven Neumann committed
625
626
	  /* If the image was exported, delete the new display. */
	  /* This also deletes the image.                       */
627

Sven Neumann's avatar
Sven Neumann committed
628
629
630
631
632
633
	  if (display_ID > -1)
	    gimp_display_delete (display_ID);
	  else
	    gimp_image_delete (image_ID);
	}

634
635
636
637
      /* pw - now we need to change the defaults to be whatever
       * was used to save this image.  Dump the old parasites
       * and add new ones. */
      
Marc Lehmann's avatar
Marc Lehmann committed
638
      gimp_image_parasite_detach (orig_image_ID, "gimp-comment");
Sven Neumann's avatar
Sven Neumann committed
639
      if (image_comment && strlen (image_comment)) 
Sven Neumann's avatar
Sven Neumann committed
640
	{
641
642
643
644
	  parasite = gimp_parasite_new ("gimp-comment",
					GIMP_PARASITE_PERSISTENT,
					strlen (image_comment) + 1,
					image_comment);
Marc Lehmann's avatar
Marc Lehmann committed
645
	  gimp_image_parasite_attach (orig_image_ID, parasite);
646
	  gimp_parasite_free (parasite);
Sven Neumann's avatar
Sven Neumann committed
647
	}
Marc Lehmann's avatar
Marc Lehmann committed
648
      gimp_image_parasite_detach (orig_image_ID, "jpeg-save-options");
649
      
650
651
      parasite = gimp_parasite_new ("jpeg-save-options",
				    0, sizeof (jsvals), &jsvals);
Marc Lehmann's avatar
Marc Lehmann committed
652
      gimp_image_parasite_attach (orig_image_ID, parasite);
653
      gimp_parasite_free (parasite);
Elliot Lee's avatar
Elliot Lee committed
654
    }
655
656
  else
    {
Sven Neumann's avatar
Sven Neumann committed
657
      status = GIMP_PDB_CALLING_ERROR;
658
    }
Elliot Lee's avatar
Elliot Lee committed
659

660
661
  values[0].data.d_status = status;
}
Elliot Lee's avatar
Elliot Lee committed
662

663
/* Read next byte */
664
static guint
665
666
jpeg_getc (j_decompress_ptr cinfo)
{
667
  struct jpeg_source_mgr *datasrc = cinfo->src;
668

Sven Neumann's avatar
Sven Neumann committed
669
670
671
672
673
  if (datasrc->bytes_in_buffer == 0) 
    {
      if (! (*datasrc->fill_input_buffer) (cinfo))
	ERREXIT (cinfo, JERR_CANT_SUSPEND);
    }
674
  datasrc->bytes_in_buffer--;
675

676
677
678
679
680
681
682
683
684
685
686
687
  return *datasrc->next_input_byte++;
}

/* We need our own marker parser, since early versions of libjpeg
 * don't keep a conventient list of the marker's that have been
 * seen. */

/*
 * Marker processor for COM markers.
 * This replaces the library's built-in processor, which just skips the marker.
 * Note this code relies on a non-suspending data source.
 */
Sven Neumann's avatar
Sven Neumann committed
688
static GString *local_image_comments = NULL;
689
690
691
692

static boolean
COM_handler (j_decompress_ptr cinfo)
{
693
694
  gint  length;
  guint ch;
695
696
697
698
699
700
701
702
703
704
705
706
707

  length = jpeg_getc (cinfo) << 8;
  length += jpeg_getc (cinfo);
  if (length < 2)
    return FALSE;
  length -= 2;			/* discount the length word itself */

  if (!local_image_comments)
    local_image_comments = g_string_new (NULL);
  else
    g_string_append_c (local_image_comments, '\n');

  while (length-- > 0)
Sven Neumann's avatar
Sven Neumann committed
708
709
710
711
    {
      ch = jpeg_getc (cinfo);
      g_string_append_c (local_image_comments, ch);
    }
712
713
714
715

  return TRUE;
}

716
717
718
typedef struct my_error_mgr
{
  struct jpeg_error_mgr pub;            /* "public" fields */
Elliot Lee's avatar
Elliot Lee committed
719

720
  jmp_buf               setjmp_buffer;  /* for return to caller */
Elliot Lee's avatar
Elliot Lee committed
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
} *my_error_ptr;

/*
 * Here's the routine that will replace the standard error_exit method:
 */

static void
my_error_exit (j_common_ptr cinfo)
{
  /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
  my_error_ptr myerr = (my_error_ptr) cinfo->err;

  /* Always display the message. */
  /* We could postpone this until after returning, if we chose. */
  (*cinfo->err->output_message) (cinfo);

  /* Return control to the setjmp point */
  longjmp (myerr->setjmp_buffer, 1);
}

static gint32
742
load_image (const gchar *filename, 
743
	    GimpRunMode  runmode, 
744
	    gboolean     preview)
Elliot Lee's avatar
Elliot Lee committed
745
{
746
747
748
749
  GimpPixelRgn     pixel_rgn;
  GimpDrawable    *drawable;
  gint32 volatile  image_ID;
  gint32           layer_ID;
Elliot Lee's avatar
Elliot Lee committed
750
  struct jpeg_decompress_struct cinfo;
751
752
753
754
  struct my_error_mgr           jerr;
  FILE    *infile;
  guchar  *buf;
  guchar  * volatile padded_buf = NULL;
Elliot Lee's avatar
Elliot Lee committed
755
  guchar **rowbuf;
756
757
758
759
760
761
  gchar   *name;
  gint     image_type;
  gint     layer_type;
  gint     tile_height;
  gint     scanlines;
  gint     i, start, end;
Elliot Lee's avatar
Elliot Lee committed
762

763
  GimpParasite * volatile comment_parasite = NULL;
764

765
766
#ifdef HAVE_EXIF
  GimpParasite *exif_parasite = NULL;
767
  ExifData     *exif_data     = NULL;
768
769
#endif

Elliot Lee's avatar
Elliot Lee committed
770
771
772
773
774
775
  /* We set up the normal JPEG error routines. */
  cinfo.err = jpeg_std_error (&jerr.pub);
  jerr.pub.error_exit = my_error_exit;

  if ((infile = fopen (filename, "rb")) == NULL)
    {
776
      g_message (_("Can't open '%s':\n%s"), filename, g_strerror (errno));
Elliot Lee's avatar
Elliot Lee committed
777
778
779
      gimp_quit ();
    }

780
781
782
  name = g_strdup_printf (_("Opening '%s'..."), filename);
  gimp_progress_init (name);
  g_free (name);
Elliot Lee's avatar
Elliot Lee committed
783
784
785
786
787
788
789
790
791
792
793

  image_ID = -1;
  /* Establish the setjmp return context for my_error_exit to use. */
  if (setjmp (jerr.setjmp_buffer))
    {
      /* If we get here, the JPEG code has signaled an error.
       * We need to clean up the JPEG object, close the input file, and return.
       */
      jpeg_destroy_decompress (&cinfo);
      if (infile)
	fclose (infile);
794
      if (image_ID != -1 && !preview)
Elliot Lee's avatar
Elliot Lee committed
795
	gimp_image_delete (image_ID);
796
797
      if (preview)
	destroy_preview();
Elliot Lee's avatar
Elliot Lee committed
798
799
800
801
802
803
804
805
806
      gimp_quit ();
    }
  /* Now we can initialize the JPEG decompression object. */
  jpeg_create_decompress (&cinfo);

  /* Step 2: specify data source (eg, a file) */

  jpeg_stdio_src (&cinfo, infile);

807
  /* pw - step 2.1 let the lib know we want the comments. */
808
809

  jpeg_set_marker_processor (&cinfo, JPEG_COM, COM_handler);
810

Elliot Lee's avatar
Elliot Lee committed
811
812
813
814
815
816
817
818
819
  /* Step 3: read file parameters with jpeg_read_header() */

  (void) jpeg_read_header (&cinfo, TRUE);
  /* We can ignore the return value from jpeg_read_header since
   *   (a) suspension is not possible with the stdio data source, and
   *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
   * See libjpeg.doc for more info.
   */

820
821
822
  if (!preview) 
    {
      /* if we had any comments then make a parasite for them */
823
      if (local_image_comments && local_image_comments->len)
824
	{
825
826
	  gchar *comment = local_image_comments->str;

827
	  g_string_free (local_image_comments, FALSE);
828

829
	  local_image_comments = NULL;
830
831
832
833
834
835
836

          if (g_utf8_validate (comment, -1, NULL))
            comment_parasite = gimp_parasite_new ("gimp-comment",
                                                  GIMP_PARASITE_PERSISTENT,
                                                  strlen (comment) + 1,
                                                  comment);
          g_free (comment);
837
838
	}
      
839
840
841
      /* Do not attach the "jpeg-save-options" parasite to the image
       * because this conflics with the global defaults.  See bug #75398:
       * http://bugzilla.gnome.org/show_bug.cgi?id=75398 */
842
    } 
843
  
Elliot Lee's avatar
Elliot Lee committed
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
  /* Step 4: set parameters for decompression */

  /* In this example, we don't need to change any of the defaults set by
   * jpeg_read_header(), so we do nothing here.
   */

  /* Step 5: Start decompressor */

  jpeg_start_decompress (&cinfo);

  /* We may need to do some setup of our own at this point before reading
   * the data.  After jpeg_start_decompress() we have the correct scaled
   * output image dimensions available, as well as the output colormap
   * if we asked for color quantization.
   * In this example, we need to make an output work buffer of the right size.
   */
  /* temporary buffer */
  tile_height = gimp_tile_height ();
Sven Neumann's avatar
Sven Neumann committed
862
863
  buf = g_new (guchar, 
	       tile_height * cinfo.output_width * cinfo.output_components);
864
  
Elliot Lee's avatar
Elliot Lee committed
865
866
867
868
869
870
  rowbuf = g_new (guchar*, tile_height);

  for (i = 0; i < tile_height; i++)
    rowbuf[i] = buf + cinfo.output_width * cinfo.output_components * i;

  /* Create a new image of the proper size and associate the filename with it.
871
872
873

     Preview layers, not being on the bottom of a layer stack, MUST HAVE
     AN ALPHA CHANNEL!
Elliot Lee's avatar
Elliot Lee committed
874
875
876
877
   */
  switch (cinfo.output_components)
    {
    case 1:
Sven Neumann's avatar
Sven Neumann committed
878
879
      image_type = GIMP_GRAY;
      layer_type = preview ? GIMP_GRAYA_IMAGE : GIMP_GRAY_IMAGE;
Elliot Lee's avatar
Elliot Lee committed
880
      break;
881

Elliot Lee's avatar
Elliot Lee committed
882
    case 3:
Sven Neumann's avatar
Sven Neumann committed
883
884
      image_type = GIMP_RGB;
      layer_type = preview ? GIMP_RGBA_IMAGE : GIMP_RGB_IMAGE;
Elliot Lee's avatar
Elliot Lee committed
885
      break;
886

887
888
889
890
891
892
893
894
895
    case 4:
      if (cinfo.out_color_space == JCS_CMYK)
	{
	  image_type = GIMP_RGB;
	  layer_type = GIMP_RGB_IMAGE;
	  break;
	}
      /*fallthrough*/

Elliot Lee's avatar
Elliot Lee committed
896
    default:
897
898
899
      g_message ("Don't know how to load JPEGs\n"
                 "with %d color channels\n"
                 "using colorspace %d (%d)",
900
901
		 cinfo.output_components, cinfo.out_color_space,
		 cinfo.jpeg_color_space);
Elliot Lee's avatar
Elliot Lee committed
902
      gimp_quit ();
903
      break;
Elliot Lee's avatar
Elliot Lee committed
904
905
    }

906
907
908
909
910
911
912
913
  if (preview)
    padded_buf = g_new (guchar, tile_height * cinfo.output_width *
			(cinfo.output_components + 1));
  else if (cinfo.out_color_space == JCS_CMYK)
    padded_buf = g_new (guchar, tile_height * cinfo.output_width * 3);
  else
    padded_buf = NULL;

Sven Neumann's avatar
Sven Neumann committed
914
915
916
917
918
919
  if (preview) 
    {
      image_ID = image_ID_global;
    } 
  else 
    {
920
921
      image_ID = gimp_image_new (cinfo.output_width, cinfo.output_height,
				 image_type);
Sven Neumann's avatar
Sven Neumann committed
922
923
      gimp_image_set_filename (image_ID, filename);
    }
924

Sven Neumann's avatar
Sven Neumann committed
925
926
  if (preview) 
    {
927
928
929
930
931
      layer_ID_global = layer_ID = 
	gimp_layer_new (image_ID, _("JPEG preview"),
			cinfo.output_width,
			cinfo.output_height,
			layer_type, 100, GIMP_NORMAL_MODE);
932
    }
Sven Neumann's avatar
Sven Neumann committed
933
934
935
936
937
  else 
    {
      layer_ID = gimp_layer_new (image_ID, _("Background"),
				 cinfo.output_width,
				 cinfo.output_height,
Sven Neumann's avatar
Sven Neumann committed
938
				 layer_type, 100, GIMP_NORMAL_MODE);
Sven Neumann's avatar
Sven Neumann committed
939
    }
Elliot Lee's avatar
Elliot Lee committed
940

941
  drawable_global = drawable = gimp_drawable_get (layer_ID);
942
943
  gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0,
		       drawable->width, drawable->height, TRUE, FALSE);
Elliot Lee's avatar
Elliot Lee committed
944

945
  /* Step 5.1: if the file had resolution information, set it on the image */
946
  if (!preview && cinfo.saw_JFIF_marker)
947
948
949
950
    {
      gdouble xresolution;
      gdouble yresolution;
      gdouble asymmetry;
951

952
953
      xresolution = cinfo.X_density;
      yresolution = cinfo.Y_density;
954

955
956
957
958
959
      switch (cinfo.density_unit)
	{
	case 0: /* unknown -> set the aspect ratio but use the default
		*  image resolution
		*/
960
961
962
963
964
	  if (cinfo.Y_density != 0)
	    asymmetry = xresolution / yresolution;
	  else
	    asymmetry = 1.0;

965
966
967
	  gimp_image_get_resolution (image_ID, &xresolution, &yresolution);
	  xresolution *= asymmetry;
	  break;
968

969
970
	case 1: /* dots per inch */
	  break;
971

972
973
974
	case 2: /* dots per cm */
	  xresolution *= 2.54;
	  yresolution *= 2.54;
975
	  gimp_image_set_unit (image_ID, GIMP_UNIT_MM);
976
977
978
	  break;

	default:
979
	  g_message ("Unknown density unit %d\nassuming dots per inch",
980
981
982
983
984
985
		     cinfo.density_unit);
	  break;
	}

      gimp_image_set_resolution (image_ID, xresolution, yresolution);
    }
986

Elliot Lee's avatar
Elliot Lee committed
987
988
989
990
991
992
993
994
995
  /* Step 6: while (scan lines remain to be read) */
  /*           jpeg_read_scanlines(...); */

  /* Here we use the library's state variable cinfo.output_scanline as the
   * loop counter, so that we don't have to keep track ourselves.
   */
  while (cinfo.output_scanline < cinfo.output_height)
    {
      start = cinfo.output_scanline;
996
997
      end   = cinfo.output_scanline + tile_height;
      end   = MIN (end, cinfo.output_height);
Elliot Lee's avatar
Elliot Lee committed
998
999
1000
1001
1002
      scanlines = end - start;

      for (i = 0; i < scanlines; i++)
	jpeg_read_scanlines (&cinfo, (JSAMPARRAY) &rowbuf[i], 1);

1003
1004
1005
1006
      if (preview) /* Add a dummy alpha channel -- convert buf to padded_buf */
	{
	  guchar *dest = padded_buf;
	  guchar *src  = buf;
1007
	  gint    num  = drawable->width * scanlines;
1008
1009
1010
1011

	  switch (cinfo.output_components)
	    {
	    case 1:
1012
	      for (i = 0; i < num; i++)
1013
1014
1015
1016
1017
		{
		  *(dest++) = *(src++);
		  *(dest++) = 255;
		}
	      break;
1018

1019
	    case 3:
1020
	      for (i = 0; i < num; i++)
1021
1022
1023
1024
1025
1026
1027
		{
		  *(dest++) = *(src++);
		  *(dest++) = *(src++);
		  *(dest++) = *(src++);
		  *(dest++) = 255;
		}
	      break;
1028

1029
	    default:
1030
	      g_warning ("JPEG - shouldn't have gotten here.\nReport to http://bugzilla.gnome.org/");
1031
	      break;
1032
1033
	    }
	}
1034
1035
1036
1037
1038
      else if (cinfo.out_color_space == JCS_CMYK) /* buf-> RGB in padded_buf */
	{
	  guchar *dest = padded_buf;
	  guchar *src  = buf;
	  gint    num  = drawable->width * scanlines;
1039

1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
	  for (i = 0; i < num; i++)
	    {
	      guint r_c, g_m, b_y, a_k;

	      r_c = *(src++);
	      g_m = *(src++);
	      b_y = *(src++);
	      a_k = *(src++);
	      *(dest++) = (r_c * a_k) / 255;
	      *(dest++) = (g_m * a_k) / 255;
	      *(dest++) = (b_y * a_k) / 255;
	    }
	}

      gimp_pixel_rgn_set_rect (&pixel_rgn, padded_buf ? padded_buf : buf,
1055
			       0, start, drawable->width, scanlines);
Elliot Lee's avatar
Elliot Lee committed
1056

1057
1058
      gimp_progress_update ((gdouble) cinfo.output_scanline / 
                            (gdouble) cinfo.output_height);
Elliot Lee's avatar
Elliot Lee committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
    }

  /* Step 7: Finish decompression */

  jpeg_finish_decompress (&cinfo);
  /* We can ignore the return value since suspension is not possible
   * with the stdio data source.
   */

  /* Step 8: Release JPEG decompression object */

  /* This is an important step since it will release a good deal of memory. */
  jpeg_destroy_decompress (&cinfo);

  /* free up the temporary buffers */
  g_free (rowbuf);
  g_free (buf);
1076
  g_free (padded_buf);
Elliot Lee's avatar
Elliot Lee committed
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090

  /* After finish_decompress, we can close the input file.
   * Here we postpone it until after no more JPEG errors are possible,
   * so as to simplify the setjmp error logic above.  (Actually, I don't
   * think that jpeg_destroy can do an error exit, but why assume anything...)
   */
  fclose (infile);

  /* At this point you may want to check to see whether any corrupt-data
   * warnings occurred (test whether jerr.num_warnings is nonzero).
   */

  /* Tell the GIMP to display the image.
   */
BST 1999 Andy Thomas's avatar
BST 1999 Andy Thomas committed
1091
  gimp_image_add_layer (image_ID, layer_ID, 0);
Elliot Lee's avatar
Elliot Lee committed
1092
1093
  gimp_drawable_flush (drawable);

1094
1095
  /* pw - Last of all, attach the parasites (couldn't do it earlier -
     there was no image. */
Sven Neumann's avatar
Sven Neumann committed
1096

1097
  if (!preview)
Sven Neumann's avatar
Sven Neumann committed
1098
1099
1100
    {
      if (comment_parasite)
	{
Marc Lehmann's avatar
Marc Lehmann committed
1101
	  gimp_image_parasite_attach (image_ID, comment_parasite);
1102
	  gimp_parasite_free (comment_parasite);
1103
1104

          comment_parasite = NULL;
Sven Neumann's avatar
Sven Neumann committed
1105
	}
1106
1107
1108
1109
1110

#ifdef HAVE_EXIF
      exif_data = exif_data_new_from_file (filename);
      if (exif_data)
        {
1111
1112
1113
          guchar *exif_buf;
          guint   exif_buf_len;

1114
1115
1116
1117
1118
1119
1120
          exif_data_save_data (exif_data, &exif_buf, &exif_buf_len);
          exif_data_unref (exif_data);
          exif_parasite = gimp_parasite_new ("jpeg-exif-data", 
                                             GIMP_PARASITE_PERSISTENT,
                                             exif_buf_len, exif_buf);
          gimp_image_parasite_attach (image_ID, exif_parasite);
          gimp_parasite_free (exif_parasite);
1121
          free (exif_buf);
1122
1123
1124
        }
#endif

1125
    }
1126

Elliot Lee's avatar
Elliot Lee committed
1127
1128
1129
  return image_ID;
}

1130
1131
1132
1133
1134
1135
1136
1137
/*
 * sg - This is the best I can do, I'm afraid... I think it will fail
 * if something bad really happens (but it might not). If you have a
 * better solution, send it ;-)
 */ 
static void
background_error_exit (j_common_ptr cinfo)
{
Sven Neumann's avatar
Sven Neumann committed
1138
1139
  if (abort_me) 
    *abort_me = TRUE;
1140
1141
1142
  (*cinfo->err->output_message) (cinfo);
}

1143
static gboolean
Sven Neumann's avatar
Sven Neumann committed
1144
background_jpeg_save (PreviewPersistent *pp)
1145
1146
1147
{
  guchar *t;
  guchar *s;
1148
1149
  gint    i, j;
  gint    yend;
1150

1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
  if (pp->abort_me || (pp->cinfo.next_scanline >= pp->cinfo.image_height))
    {
      /* clean up... */
      if (pp->abort_me)
	{
	  jpeg_abort_compress (&(pp->cinfo));
	}
      else
	{
	  jpeg_finish_compress (&(pp->cinfo));
	}
1162

1163
1164
      fclose (pp->outfile);
      jpeg_destroy_compress (&(pp->cinfo));
1165