Add year 2009 to copyright info everywhere.
[geeqie.git] / src / exif-common.c
1 /*
2  * Geeqie
3  * (C) 2006 John Ellis
4  * Copyright (C) 2008 - 2009 The Geeqie Team
5  *
6 */
7
8 #ifdef HAVE_CONFIG_H
9 #  include "config.h"
10 #endif
11
12 #include <stdio.h>
13 #include <string.h>
14 #include <fcntl.h>
15 #include <unistd.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/mman.h>
19 #include <math.h>
20
21 #ifdef HAVE_LCMS
22 /*** color support enabled ***/
23
24 #ifdef HAVE_LCMS_LCMS_H
25   #include <lcms/lcms.h>
26 #else
27   #include <lcms.h>
28 #endif
29 #endif
30
31 #include <glib.h>
32
33 #include "intl.h"
34
35 #include "main.h"
36 #include "exif.h"
37
38 #include "filedata.h"
39 #include "filefilter.h"
40 #include "filecache.h"
41 #include "format_raw.h"
42 #include "ui_fileops.h"
43 #include "cache.h"
44
45
46 static gdouble exif_rational_to_double(ExifRational *r, gint sign)
47 {
48         if (!r || r->den == 0.0) return 0.0;
49
50         if (sign) return (gdouble)((gint)r->num) / (gdouble)((gint)r->den);
51         return (gdouble)r->num / r->den;
52 }
53
54 static gdouble exif_get_rational_as_double(ExifData *exif, const gchar *key)
55 {
56         ExifRational *r;
57         gint sign;
58
59         r = exif_get_rational(exif, key, &sign);
60         return exif_rational_to_double(r, sign);
61 }
62
63 static GString *append_comma_text(GString *string, const gchar *text)
64 {
65         string = g_string_append(string, ", ");
66         string = g_string_append(string, text);
67
68         return string;
69 }
70
71 static gchar *remove_common_prefix(gchar *s, gchar *t)
72 {
73         gint i;
74
75         if (!s || !t) return t;
76
77         for (i = 0; s[i] && t[i] && s[i] == t[i]; i++)
78                 ;
79         if (!i)
80                 return t;
81         if (s[i-1] == ' ' || !s[i])
82                 {
83                 while (t[i] == ' ')
84                         i++;
85                 return t + i;
86                 }
87         return s;
88 }
89
90 static gdouble get_crop_factor(ExifData *exif)
91 {
92         gdouble res_unit_tbl[] = {0.0, 25.4, 25.4, 10.0, 1.0, 0.001 };
93         gdouble xres = exif_get_rational_as_double(exif, "Exif.Photo.FocalPlaneXResolution");
94         gdouble yres = exif_get_rational_as_double(exif, "Exif.Photo.FocalPlaneYResolution");
95         gint res_unit;
96         gint w, h;
97         gdouble xsize, ysize, size, ratio;
98
99         if (xres == 0.0 || yres == 0.0) return 0.0;
100
101         if (!exif_get_integer(exif, "Exif.Photo.FocalPlaneResolutionUnit", &res_unit)) return 0.0;
102         if (res_unit < 1 || res_unit > 5) return 0.0;
103
104         if (!exif_get_integer(exif, "Exif.Photo.PixelXDimension", &w)) return 0.0;
105         if (!exif_get_integer(exif, "Exif.Photo.PixelYDimension", &h)) return 0.0;
106
107         xsize = w * res_unit_tbl[res_unit] / xres;
108         ysize = h * res_unit_tbl[res_unit] / yres;
109
110         ratio = xsize / ysize;
111
112         if (ratio < 0.5 || ratio > 2.0) return 0.0; /* reasonable ratio */
113
114         size = sqrt(xsize * xsize + ysize * ysize);
115
116         if (size < 1.0 || size > 100.0) return 0.0; /* reasonable sensor size in mm */
117
118         return sqrt(36*36+24*24) / size;
119
120 }
121
122 static gint remove_suffix(gchar *str, const gchar *suffix, gint suffix_len)
123 {
124         gint str_len = strlen(str);
125         
126         if (suffix_len < 0) suffix_len = strlen(suffix);
127         if (str_len < suffix_len) return FALSE;
128         
129         if (strcmp(str + str_len - suffix_len, suffix) != 0) return FALSE;
130         str[str_len - suffix_len] = '\0';
131         
132         return TRUE;
133 }
134
135 static gchar *exif_build_formatted_Camera(ExifData *exif)
136 {
137         gchar *text;
138         gchar *make = exif_get_data_as_text(exif, "Exif.Image.Make");
139         gchar *model = exif_get_data_as_text(exif, "Exif.Image.Model");
140         gchar *software = exif_get_data_as_text(exif, "Exif.Image.Software");
141         gchar *model2;
142         gchar *software2;
143
144         if (make)
145                 {
146                 g_strstrip(make);
147
148                 if (remove_suffix(make, " CORPORATION", 12)) { /* Nikon */ }
149                 else if (remove_suffix(make, " Corporation", 12)) { /* Pentax */ }
150                 else if (remove_suffix(make, " OPTICAL CO.,LTD", 16)) { /* OLYMPUS */ };
151                 }
152
153         if (model)
154                 g_strstrip(model);
155
156         if (software)
157                 {
158                 gint i, j;
159
160                 g_strstrip(software);
161                 
162                 /* remove superfluous spaces (pentax K100D) */
163                 for (i = 0, j = 0; software[i]; i++, j++)
164                         {
165                         if (software[i] == ' ' && software[i + 1] == ' ')
166                                 i++;
167                         if (i != j) software[j] = software[i];
168                         }
169                 software[j] = '\0';
170                 }
171
172         model2 = remove_common_prefix(make, model);
173         software2 = remove_common_prefix(model2, software);
174
175         text = g_strdup_printf("%s%s%s%s%s%s", (make) ? make : "", (make && model2) ? " " : "",
176                                                (model2) ? model2 : "",
177                                                (software2 && (make || model2)) ? " (" : "",
178                                                (software2) ? software2 : "",
179                                                (software2 && (make || model2)) ? ")" : "");
180
181         g_free(make);
182         g_free(model);
183         g_free(software);
184         return text;
185 }
186
187 static gchar *exif_build_formatted_DateTime(ExifData *exif)
188 {
189         gchar *text = exif_get_data_as_text(exif, "Exif.Photo.DateTimeOriginal");
190         gchar *subsec = NULL;
191
192         if (text) subsec = exif_get_data_as_text(exif, "Exif.Photo.SubSecTimeOriginal");
193         if (!text)
194                 {
195                 text = exif_get_data_as_text(exif, "Exif.Image.DateTime");
196                 if (text) subsec = exif_get_data_as_text(exif, "Exif.Photo.SubSecTime");
197                 }
198         if (subsec)
199                 {
200                 gchar *tmp = text;
201                 text = g_strconcat(tmp, ".", subsec, NULL);
202                 g_free(tmp);
203                 g_free(subsec);
204                 }
205         return text;
206 }
207
208 static gchar *exif_build_formatted_ShutterSpeed(ExifData *exif)
209 {
210         ExifRational *r;
211
212         r = exif_get_rational(exif, "Exif.Photo.ExposureTime", NULL);
213         if (r && r->num && r->den)
214                 {
215                 gdouble n = (gdouble)r->den / (gdouble)r->num;
216                 return g_strdup_printf("%s%.0fs", n > 1.0 ? "1/" : "",
217                                                   n > 1.0 ? n : 1.0 / n);
218                 }
219         r = exif_get_rational(exif, "Exif.Photo.ShutterSpeedValue", NULL);
220         if (r && r->num  && r->den)
221                 {
222                 gdouble n = pow(2.0, exif_rational_to_double(r, TRUE));
223
224                 /* Correct exposure time to avoid values like 1/91s (seen on Minolta DImage 7) */
225                 if (n > 1.0 && (gint)n - ((gint)(n/10))*10 == 1) n--;
226
227                 return g_strdup_printf("%s%.0fs", n > 1.0 ? "1/" : "",
228                                                   n > 1.0 ? floor(n) : 1.0 / n);
229                 }
230         return NULL;
231 }
232
233 static gchar *exif_build_formatted_Aperture(ExifData *exif)
234 {
235         gdouble n;
236
237         n = exif_get_rational_as_double(exif, "Exif.Photo.FNumber");
238         if (n == 0.0) n = exif_get_rational_as_double(exif, "Exif.Photo.ApertureValue");
239         if (n == 0.0) return NULL;
240
241         return g_strdup_printf("f/%.1f", n);
242 }
243
244 static gchar *exif_build_formatted_ExposureBias(ExifData *exif)
245 {
246         ExifRational *r;
247         gint sign;
248         gdouble n;
249
250         r = exif_get_rational(exif, "Exif.Photo.ExposureBiasValue", &sign);
251         if (!r) return NULL;
252
253         n = exif_rational_to_double(r, sign);
254         return g_strdup_printf("%+.1f", n);
255 }
256
257 static gchar *exif_build_formatted_FocalLength(ExifData *exif)
258 {
259         gdouble n;
260
261         n = exif_get_rational_as_double(exif, "Exif.Photo.FocalLength");
262         if (n == 0.0) return NULL;
263         return g_strdup_printf("%.0f mm", n);
264 }
265
266 static gchar *exif_build_formatted_FocalLength35mmFilm(ExifData *exif)
267 {
268         gint n;
269         gdouble f, c;
270
271         if (exif_get_integer(exif, "Exif.Photo.FocalLengthIn35mmFilm", &n) && n != 0)
272                 {
273                 return g_strdup_printf("%d mm", n);
274                 }
275
276         f = exif_get_rational_as_double(exif, "Exif.Photo.FocalLength");
277         if (f == 0.0) return NULL;
278
279         c = get_crop_factor(exif);
280         if (c == 0.0) return NULL;
281
282         return g_strdup_printf("%.0f mm", f * c);
283 }
284
285 static gchar *exif_build_formatted_ISOSpeedRating(ExifData *exif)
286 {
287         gchar *text;
288
289         text = exif_get_data_as_text(exif, "Exif.Photo.ISOSpeedRatings");
290         /* kodak may set this instead */
291         if (!text) text = exif_get_data_as_text(exif, "Exif.Photo.ExposureIndex");
292         return text;
293 }
294
295 static gchar *exif_build_formatted_SubjectDistance(ExifData *exif)
296 {
297         ExifRational *r;
298         gint sign;
299         gdouble n;
300
301         r = exif_get_rational(exif, "Exif.Photo.SubjectDistance", &sign);
302         if (!r) return NULL;
303
304         if ((glong)r->num == (glong)0xffffffff) return g_strdup(_("infinity"));
305         if ((glong)r->num == 0) return g_strdup(_("unknown"));
306
307         n = exif_rational_to_double(r, sign);
308         if (n == 0.0) return _("unknown");
309         return g_strdup_printf("%.3f m", n);
310 }
311
312 static gchar *exif_build_formatted_Flash(ExifData *exif)
313 {
314         /* grr, flash is a bitmask... */
315         GString *string;
316         gchar *text;
317         gint n;
318         gint v;
319
320         if (!exif_get_integer(exif, "Exif.Photo.Flash", &n)) return NULL;
321
322         /* Exif 2.1 only defines first 3 bits */
323         if (n <= 0x07) return exif_get_data_as_text(exif, "Exif.Photo.Flash");
324
325         /* must be Exif 2.2 */
326         string = g_string_new("");
327
328         /* flash fired (bit 0) */
329         string = g_string_append(string, (n & 0x01) ? _("yes") : _("no"));
330
331         /* flash mode (bits 3, 4) */
332         v = (n >> 3) & 0x03;
333         if (v) string = append_comma_text(string, _("mode:"));
334         switch (v)
335                 {
336                 case 1:
337                         string = g_string_append(string, _("on"));
338                         break;
339                 case 2:
340                         string = g_string_append(string, _("off"));
341                         break;
342                 case 3:
343                         string = g_string_append(string, _("auto"));
344                         break;
345                 }
346
347         /* return light (bits 1, 2) */
348         v = (n >> 1) & 0x03;
349         if (v == 2) string = append_comma_text(string, _("not detected by strobe"));
350         if (v == 3) string = append_comma_text(string, _("detected by strobe"));
351
352         /* we ignore flash function (bit 5) */
353
354         /* red-eye (bit 6) */
355         if ((n >> 5) & 0x01) string = append_comma_text(string, _("red-eye reduction"));
356
357         text = string->str;
358         g_string_free(string, FALSE);
359         return text;
360 }
361
362 static gchar *exif_build_formatted_Resolution(ExifData *exif)
363 {
364         ExifRational *rx, *ry;
365         gchar *units;
366         gchar *text;
367
368         rx = exif_get_rational(exif, "Exif.Image.XResolution", NULL);
369         ry = exif_get_rational(exif, "Exif.Image.YResolution", NULL);
370         if (!rx || !ry) return NULL;
371
372         units = exif_get_data_as_text(exif, "Exif.Image.ResolutionUnit");
373         text = g_strdup_printf("%0.f x %0.f (%s/%s)", rx->den ? (gdouble)rx->num / rx->den : 1.0,
374                                                       ry->den ? (gdouble)ry->num / ry->den : 1.0,
375                                                       _("dot"), (units) ? units : _("unknown"));
376
377         g_free(units);
378         return text;
379 }
380
381 static gchar *exif_build_formatted_ColorProfile(ExifData *exif)
382 {
383         const gchar *name = "";
384         const gchar *source = "";
385         guchar *profile_data;
386         guint profile_len;
387
388         profile_data = exif_get_color_profile(exif, &profile_len);
389         if (!profile_data)
390                 {
391                 gint cs;
392                 gchar *interop_index;
393
394                 /* ColorSpace == 1 specifies sRGB per EXIF 2.2 */
395                 if (!exif_get_integer(exif, "Exif.Photo.ColorSpace", &cs)) cs = 0;
396                 interop_index = exif_get_data_as_text(exif, "Exif.Iop.InteroperabilityIndex");
397
398                 if (cs == 1)
399                         {
400                         name = _("sRGB");
401                         source = "ColorSpace";
402                         }
403                 else if (cs == 2 || (interop_index && !strcmp(interop_index, "R03")))
404                         {
405                         name = _("AdobeRGB");
406                         source = (cs == 2) ? "ColorSpace" : "Iop";
407                         }
408
409                 g_free(interop_index);
410                 }
411         else
412                 {
413                 source = _("embedded");
414 #ifdef HAVE_LCMS
415
416                         {
417                         cmsHPROFILE profile;
418
419                         profile = cmsOpenProfileFromMem(profile_data, profile_len);
420                         if (profile)
421                                 {
422                                 name = cmsTakeProductName(profile);
423                                 cmsCloseProfile(profile);
424                                 }
425                         g_free(profile_data);
426                         }
427 #endif
428                 }
429         if (name[0] == 0 && source[0] == 0) return NULL;
430         return g_strdup_printf("%s (%s)", name, source);
431 }
432
433 static gchar *exif_build_formatted_GPSPosition(ExifData *exif)
434 {
435         GString *string;
436         gchar *text, *ref;
437         ExifRational *value;
438         ExifItem *item;
439         guint i;
440         gdouble p, p3;
441         gulong p1, p2;
442
443         string = g_string_new("");
444
445         item = exif_get_item(exif, "Exif.GPSInfo.GPSLatitude");
446         ref = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLatitudeRef");
447         if (item && ref)
448                 {
449                 p = 0;
450                 for (i = 0; i < exif_item_get_elements(item); i++)
451                         {
452                         value = exif_item_get_rational(item, NULL, i);
453                         if (value && value->num && value->den)
454                                 p += (gdouble)value->num / (gdouble)value->den / pow(60.0, (gdouble)i);
455                         }
456                 p1 = (gint)p;
457                 p2 = (gint)((p - p1)*60);
458                 p3 = ((p - p1)*60 - p2)*60;
459
460                 g_string_append_printf(string, "%0lu° %0lu' %0.2f\" %.1s", p1, p2, p3, ref);
461                 } // if (item && ref)
462
463         item = exif_get_item(exif, "Exif.GPSInfo.GPSLongitude");
464         ref = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLongitudeRef");
465         if (item && ref)
466                 {
467                 p = 0;
468                 for (i = 0; i < exif_item_get_elements(item); i++)
469                         {
470                         value = exif_item_get_rational(item, NULL, i);
471                         if (value && value->num && value->den)
472                         p += (gdouble)value->num / (gdouble)value->den / pow(60.0, (gdouble)i);
473                         }
474                 p1 = (gint)p;
475                 p2 = (gint)((p - p1)*60);
476                 p3 = ((p - p1)*60 - p2)*60;
477
478                 g_string_append_printf(string, ", %0lu° %0lu' %0.2f\" %.1s", p1, p2, p3, ref);
479                 } // if (item && ref)
480
481         text = string->str;
482         g_string_free(string, FALSE);
483
484         return text;
485 } // static gchar *exif_build_forma...
486
487 static gchar *exif_build_formatted_GPSAltitude(ExifData *exif)
488 {
489         ExifRational *r;
490         ExifItem *item;
491         gdouble alt;
492         gint ref;
493
494         item = exif_get_item(exif, "Exif.GPSInfo.GPSAltitudeRef");
495         r = exif_get_rational(exif, "Exif.GPSInfo.GPSAltitude", NULL);
496
497         if (!r || !item) return NULL;
498
499         alt = exif_rational_to_double(r, 0);
500         exif_item_get_integer(item, &ref);
501
502         return g_strdup_printf("%0.f m %s", alt, (ref==0)?_("Above Sea Level"):_("Below Sea Level"));
503 }
504
505
506 /* List of custom formatted pseudo-exif tags */
507 #define EXIF_FORMATTED_TAG(name, label) { EXIF_FORMATTED()#name, label, exif_build_formatted##_##name }
508
509 ExifFormattedText ExifFormattedList[] = {
510         EXIF_FORMATTED_TAG(Camera,              N_("Camera")),
511         EXIF_FORMATTED_TAG(DateTime,            N_("Date")),
512         EXIF_FORMATTED_TAG(ShutterSpeed,        N_("Shutter speed")),
513         EXIF_FORMATTED_TAG(Aperture,            N_("Aperture")),
514         EXIF_FORMATTED_TAG(ExposureBias,        N_("Exposure bias")),
515         EXIF_FORMATTED_TAG(ISOSpeedRating,      N_("ISO sensitivity")),
516         EXIF_FORMATTED_TAG(FocalLength,         N_("Focal length")),
517         EXIF_FORMATTED_TAG(FocalLength35mmFilm, N_("Focal length 35mm")),
518         EXIF_FORMATTED_TAG(SubjectDistance,     N_("Subject distance")),
519         EXIF_FORMATTED_TAG(Flash,               N_("Flash")),
520         EXIF_FORMATTED_TAG(Resolution,          N_("Resolution")),
521         EXIF_FORMATTED_TAG(ColorProfile,        N_("Color profile")),
522         EXIF_FORMATTED_TAG(GPSPosition,         N_("GPS position")),
523         EXIF_FORMATTED_TAG(GPSAltitude,         N_("GPS altitude")),
524         { NULL, NULL, NULL }
525 };
526
527 gchar *exif_get_formatted_by_key(ExifData *exif, const gchar *key, gint *key_valid)
528 {
529         if (strncmp(key, EXIF_FORMATTED(), EXIF_FORMATTED_LEN) == 0)
530                 {
531                 gint i;
532
533                 if (key_valid) *key_valid = TRUE;
534
535                 key += EXIF_FORMATTED_LEN;
536                 for (i = 0; ExifFormattedList[i].key; i++)
537                         if (strcmp(key, ExifFormattedList[i].key + EXIF_FORMATTED_LEN) == 0)
538                                 return ExifFormattedList[i].build_func(exif);
539                 }
540
541         if (key_valid) *key_valid = FALSE;
542         return NULL;
543 }
544
545 gchar *exif_get_description_by_key(const gchar *key)
546 {
547         if (!key) return NULL;
548
549         if (strncmp(key, EXIF_FORMATTED(), EXIF_FORMATTED_LEN) == 0)
550                 {
551                 gint i;
552
553                 key += EXIF_FORMATTED_LEN;
554                 for (i = 0; ExifFormattedList[i].key; i++)
555                         if (strcmp(key, ExifFormattedList[i].key + EXIF_FORMATTED_LEN) == 0)
556                                 return g_strdup(_(ExifFormattedList[i].description));
557                 }
558
559         return exif_get_tag_description_by_key(key);
560 }
561
562 gint exif_get_integer(ExifData *exif, const gchar *key, gint *value)
563 {
564         ExifItem *item;
565
566         item = exif_get_item(exif, key);
567         return exif_item_get_integer(item, value);
568 }
569
570 ExifRational *exif_get_rational(ExifData *exif, const gchar *key, gint *sign)
571 {
572         ExifItem *item;
573
574         item = exif_get_item(exif, key);
575         return exif_item_get_rational(item, sign, 0);
576 }
577
578 gchar *exif_get_data_as_text(ExifData *exif, const gchar *key)
579 {
580         ExifItem *item;
581         gchar *text;
582         gint key_valid;
583
584         if (!key) return NULL;
585
586         text = exif_get_formatted_by_key(exif, key, &key_valid);
587         if (key_valid) return text;
588
589         item = exif_get_item(exif, key);
590         if (item) return exif_item_get_data_as_text(item);
591
592         return NULL;
593 }
594
595
596 static FileCacheData *exif_cache;
597
598 void exif_release_cb(FileData *fd)
599 {
600         exif_free(fd->exif);
601         fd->exif = NULL;
602 }
603
604 ExifData *exif_read_fd(FileData *fd)
605 {
606         gchar *sidecar_path;
607
608         if (!fd) return NULL;
609         
610         if (!exif_cache) exif_cache = file_cache_new(exif_release_cb, 4);
611         
612         if (file_cache_get(exif_cache, fd)) return fd->exif;
613         
614         /* CACHE_TYPE_XMP_METADATA file should exist only if the metadata are
615          * not writable directly, thus it should contain the most up-to-date version */
616         sidecar_path = cache_find_location(CACHE_TYPE_XMP_METADATA, fd->path);
617
618         if (!sidecar_path) sidecar_path = file_data_get_sidecar_path(fd, TRUE);
619
620         fd->exif = exif_read(fd->path, sidecar_path, fd->modified_xmp);
621
622         g_free(sidecar_path);
623         return fd->exif;
624 }
625
626
627 void exif_free_fd(FileData *fd, ExifData *exif)
628 {
629         if (!fd) return;
630         g_assert(fd->exif == exif);
631         
632         file_cache_put(exif_cache, fd, 1);
633 }
634
635 /* embedded icc in jpeg */
636
637
638 #define JPEG_MARKER             0xFF
639 #define JPEG_MARKER_SOI         0xD8
640 #define JPEG_MARKER_EOI         0xD9
641 #define JPEG_MARKER_APP1        0xE1
642 #define JPEG_MARKER_APP2        0xE2
643
644 /* jpeg container format:
645      all data markers start with 0XFF
646      2 byte long file start and end markers: 0xFFD8(SOI) and 0XFFD9(EOI)
647      4 byte long data segment markers in format: 0xFFTTSSSSNNN...
648        FF:   1 byte standard marker identifier
649        TT:   1 byte data type
650        SSSS: 2 bytes in Motorola byte alignment for length of the data.
651              This value includes these 2 bytes in the count, making actual
652              length of NN... == SSSS - 2.
653        NNN.: the data in this segment
654  */
655
656 gint exif_jpeg_segment_find(guchar *data, guint size,
657                             guchar app_marker, const gchar *magic, guint magic_len,
658                             guint *seg_offset, guint *seg_length)
659 {
660         guchar marker = 0;
661         guint offset = 0;
662         guint length = 0;
663
664         while (marker != app_marker &&
665                marker != JPEG_MARKER_EOI)
666                 {
667                 offset += length;
668                 length = 2;
669
670                 if (offset + 2 >= size ||
671                     data[offset] != JPEG_MARKER) return FALSE;
672
673                 marker = data[offset + 1];
674                 if (marker != JPEG_MARKER_SOI &&
675                     marker != JPEG_MARKER_EOI)
676                         {
677                         if (offset + 4 >= size) return FALSE;
678                         length += ((guint)data[offset + 2] << 8) + data[offset + 3];
679                         }
680                 }
681
682         if (marker == app_marker &&
683             offset + length < size &&
684             length >= 4 + magic_len &&
685             memcmp(data + offset + 4, magic, magic_len) == 0)
686                 {
687                 *seg_offset = offset + 4;
688                 *seg_length = length - 4;
689                 return TRUE;
690                 }
691
692         return FALSE;
693 }
694
695 gint exif_jpeg_parse_color(ExifData *exif, guchar *data, guint size)
696 {
697         guint seg_offset = 0;
698         guint seg_length = 0;
699         guint chunk_offset[255];
700         guint chunk_length[255];
701         guint chunk_count = 0;
702
703         /* For jpeg/jfif, ICC color profile data can be in more than one segment.
704            the data is in APP2 data segments that start with "ICC_PROFILE\x00\xNN\xTT"
705            NN = segment number for data
706            TT = total number of ICC segments (TT in each ICC segment should match)
707          */
708
709         while (exif_jpeg_segment_find(data + seg_offset + seg_length,
710                                       size - seg_offset - seg_length,
711                                       JPEG_MARKER_APP2,
712                                       "ICC_PROFILE\x00", 12,
713                                       &seg_offset, &seg_length))
714                 {
715                 guchar chunk_num;
716                 guchar chunk_tot;
717
718                 if (seg_length < 14) return FALSE;
719
720                 chunk_num = data[seg_offset + 12];
721                 chunk_tot = data[seg_offset + 13];
722
723                 if (chunk_num == 0 || chunk_tot == 0) return FALSE;
724
725                 if (chunk_count == 0)
726                         {
727                         guint i;
728
729                         chunk_count = (guint)chunk_tot;
730                         for (i = 0; i < chunk_count; i++) chunk_offset[i] = 0;
731                         for (i = 0; i < chunk_count; i++) chunk_length[i] = 0;
732                         }
733
734                 if (chunk_tot != chunk_count ||
735                     chunk_num > chunk_count) return FALSE;
736
737                 chunk_num--;
738                 chunk_offset[chunk_num] = seg_offset + 14;
739                 chunk_length[chunk_num] = seg_length - 14;
740                 }
741
742         if (chunk_count > 0)
743                 {
744                 guchar *cp_data;
745                 guint cp_length = 0;
746                 guint i;
747
748                 for (i = 0; i < chunk_count; i++) cp_length += chunk_length[i];
749                 cp_data = g_malloc(cp_length);
750
751                 for (i = 0; i < chunk_count; i++)
752                         {
753                         if (chunk_offset[i] == 0)
754                                 {
755                                 /* error, we never saw this chunk */
756                                 g_free(cp_data);
757                                 return FALSE;
758                                 }
759                         memcpy(cp_data, data + chunk_offset[i], chunk_length[i]);
760                         }
761                 DEBUG_1("Found embedded icc profile in jpeg");
762                 exif_add_jpeg_color_profile(exif, cp_data, cp_length);
763
764                 return TRUE;
765                 }
766
767         return FALSE;
768 }
769 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */