tizen 2.0 init
[framework/multimedia/gst-plugins-base0.10.git] / gst-libs / gst / tag / gstexiftag.c
1 /* GStreamer
2  * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
3  *
4  * gstexiftag.c: library for reading / modifying exif tags
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:gsttagexif
24  * @short_description: tag mappings and support functions for plugins
25  *                     dealing with exif tags
26  * @see_also: #GstTagList
27  *
28  * Contains utility function to parse #GstTagList<!-- -->s from exif
29  * buffers and to create exif buffers from #GstTagList<!-- -->s
30  *
31  * Note that next IFD fields on the created exif buffers are set to 0.
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif
37 #include <gst/gsttagsetter.h>
38 #include <gst/base/gstbytewriter.h>
39 #include "gsttageditingprivate.h"
40
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <gst/math-compat.h>
45
46 /* Some useful constants */
47 #define TIFF_LITTLE_ENDIAN  0x4949
48 #define TIFF_BIG_ENDIAN     0x4D4D
49 #define TIFF_HEADER_SIZE    8
50 #define EXIF_TAG_ENTRY_SIZE (2 + 2 + 4 + 4)
51
52 /* Exif tag types */
53 #define EXIF_TYPE_BYTE       1
54 #define EXIF_TYPE_ASCII      2
55 #define EXIF_TYPE_SHORT      3
56 #define EXIF_TYPE_LONG       4
57 #define EXIF_TYPE_RATIONAL   5
58 #define EXIF_TYPE_UNDEFINED  7
59 #define EXIF_TYPE_SLONG      9
60 #define EXIF_TYPE_SRATIONAL 10
61
62 typedef struct _GstExifTagMatch GstExifTagMatch;
63 typedef struct _GstExifWriter GstExifWriter;
64 typedef struct _GstExifReader GstExifReader;
65 typedef struct _GstExifTagData GstExifTagData;
66
67 typedef void (*GstExifSerializationFunc) (GstExifWriter * writer,
68     const GstTagList * taglist, const GstExifTagMatch * exiftag);
69
70 /*
71  * Function used to deserialize tags that don't follow the usual
72  * deserialization conversions. Usually those that have 'Ref' complementary
73  * tags.
74  *
75  * Those functions receive a exif tag data in the parameters, plus the taglist
76  * and the reader and buffer if they need to get more information to build
77  * its tags. There are lots of parameters, but this is needed to make it
78  * versatile. Explanation of them follows:
79  *
80  * exif_reader: The #GstExifReader with the reading parameter and taglist for
81  * results.
82  * reader: The #GstByteReader pointing to the start of the next tag entry in
83  * the ifd, useful for tags that use other complementary tags.
84  * the buffer start
85  * exiftag: The #GstExifTagMatch that contains this tag info
86  * tagdata: values from the already parsed tag
87  */
88 typedef gint (*GstExifDeserializationFunc) (GstExifReader * exif_reader,
89     GstByteReader * reader, const GstExifTagMatch * exiftag,
90     GstExifTagData * tagdata);
91
92 #define EXIF_SERIALIZATION_FUNC(name) \
93 static void serialize_ ## name (GstExifWriter * writer, \
94     const GstTagList * taglist, const GstExifTagMatch * exiftag)
95
96 #define EXIF_DESERIALIZATION_FUNC(name) \
97 static gint deserialize_ ## name (GstExifReader * exif_reader, \
98     GstByteReader * reader, const GstExifTagMatch * exiftag, \
99     GstExifTagData * tagdata)
100
101 #define EXIF_SERIALIZATION_DESERIALIZATION_FUNC(name) \
102   EXIF_SERIALIZATION_FUNC (name); \
103   EXIF_DESERIALIZATION_FUNC (name)
104
105 /*
106  * A common case among serialization/deserialization routines is that
107  * the gstreamer tag is a string (with a predefined set of allowed values)
108  * and exif is an int. These macros cover these cases
109  */
110 #define EXIF_SERIALIZATION_MAP_STRING_TO_INT_FUNC(name,funcname) \
111 static void \
112 serialize_ ## name (GstExifWriter * writer, const GstTagList * taglist, \
113     const GstExifTagMatch * exiftag) \
114 { \
115   gchar *str = NULL; \
116   gint exif_value; \
117 \
118   if (!gst_tag_list_get_string_index (taglist, exiftag->gst_tag, 0, &str)) { \
119     GST_WARNING ("No %s tag present in taglist", exiftag->gst_tag); \
120     return; \
121   } \
122 \
123   exif_value = __exif_tag_ ## funcname ## _to_exif_value (str); \
124   if (exif_value == -1) { \
125     g_free (str); \
126     return; \
127   } \
128   g_free (str); \
129 \
130   switch (exiftag->exif_type) { \
131     case EXIF_TYPE_SHORT: \
132       gst_exif_writer_write_short_tag (writer, exiftag->exif_tag, exif_value); \
133       break; \
134     case EXIF_TYPE_LONG: \
135       gst_exif_writer_write_long_tag (writer, exiftag->exif_tag, exif_value); \
136       break; \
137     case EXIF_TYPE_UNDEFINED: \
138     { \
139         guint8 data = (guint8) exif_value; \
140         write_exif_undefined_tag (writer, exiftag->exif_tag, &data, 1); \
141     } \
142       break; \
143     default: \
144       g_assert_not_reached (); \
145       GST_WARNING ("Unmapped serialization for type %d", exiftag->exif_type); \
146       break; \
147    } \
148 }
149
150 #define EXIF_DESERIALIZATION_MAP_STRING_TO_INT_FUNC(name,funcname) \
151 static gint \
152 deserialize_ ## name (GstExifReader * exif_reader, \
153     GstByteReader * reader, const GstExifTagMatch * exiftag, \
154     GstExifTagData * tagdata) \
155 { \
156   const gchar *str = NULL; \
157   gint value; \
158 \
159   GST_LOG ("Starting to parse %s tag in exif 0x%x", exiftag->gst_tag, \
160       exiftag->exif_tag); \
161 \
162   /* validate tag */ \
163   if (tagdata->count != 1) { \
164     GST_WARNING ("0x%X has unexpected count", tagdata->count); \
165     return 0; \
166   } \
167 \
168   if (tagdata->tag_type == EXIF_TYPE_SHORT) { \
169     if (exif_reader->byte_order == G_LITTLE_ENDIAN) { \
170       value = GST_READ_UINT16_LE (tagdata->offset_as_data); \
171     } else { \
172       value = GST_READ_UINT16_BE (tagdata->offset_as_data); \
173     } \
174   } else if (tagdata->tag_type == EXIF_TYPE_UNDEFINED) { \
175     value = GST_READ_UINT8 (tagdata->offset_as_data); \
176   } else { \
177     GST_WARNING ("0x%X has unexpected type %d", exiftag->exif_tag, \
178         tagdata->tag_type); \
179     return 0; \
180   } \
181 \
182   str = __exif_tag_## funcname ## _from_exif_value (value); \
183   if (str == NULL) { \
184     GST_WARNING ("Invalid value for tag 0x%X: %d", tagdata->tag, value); \
185     return 0; \
186   } \
187   gst_tag_list_add (exif_reader->taglist, GST_TAG_MERGE_REPLACE, \
188       exiftag->gst_tag, str, NULL); \
189 \
190   return 0; \
191 }
192
193 #define EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC(name,funcname) \
194   EXIF_SERIALIZATION_MAP_STRING_TO_INT_FUNC(name,funcname); \
195   EXIF_DESERIALIZATION_MAP_STRING_TO_INT_FUNC(name,funcname);
196
197 struct _GstExifTagMatch
198 {
199   const gchar *gst_tag;
200   guint16 exif_tag;
201   guint16 exif_type;
202
203   /* for tags that need special handling */
204   guint16 complementary_tag;
205   GstExifSerializationFunc serialize;
206   GstExifDeserializationFunc deserialize;
207 };
208
209 struct _GstExifTagData
210 {
211   guint16 tag;
212   guint16 tag_type;
213   guint32 count;
214   guint32 offset;
215   const guint8 *offset_as_data;
216 };
217
218 /*
219  * Holds the info and variables necessary to write
220  * the exif tags properly
221  */
222 struct _GstExifWriter
223 {
224   GstByteWriter tagwriter;
225   GstByteWriter datawriter;
226
227   gint byte_order;
228   guint tags_total;
229 };
230
231 struct _GstExifReader
232 {
233   GstTagList *taglist;
234   const GstBuffer *buffer;
235   guint32 base_offset;
236   gint byte_order;
237
238   /* tags waiting for their complementary tags */
239   GSList *pending_tags;
240 };
241
242 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (aperture_value);
243 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (contrast);
244 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (exposure_program);
245 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (exposure_mode);
246 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (flash);
247 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (gain_control);
248 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (geo_coordinate);
249 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (geo_direction);
250 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (geo_elevation);
251 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (metering_mode);
252 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (orientation);
253 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (saturation);
254 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (scene_capture_type);
255 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (scene_type);
256 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (sensitivity_type);
257 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (sharpness);
258 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (shutter_speed);
259 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (source);
260 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (speed);
261 EXIF_SERIALIZATION_DESERIALIZATION_FUNC (white_balance);
262
263 EXIF_DESERIALIZATION_FUNC (resolution);
264 EXIF_DESERIALIZATION_FUNC (add_to_pending_tags);
265
266 /* FIXME copyright tag has a weird "artist\0editor\0" format that is
267  * not yet handled */
268
269 /* exif tag numbers */
270 #define EXIF_TAG_GPS_LATITUDE_REF 0x1
271 #define EXIF_TAG_GPS_LATITUDE 0x2
272 #define EXIF_TAG_GPS_LONGITUDE_REF 0x3
273 #define EXIF_TAG_GPS_LONGITUDE 0x4
274 #define EXIF_TAG_GPS_ALTITUDE_REF 0x5
275 #define EXIF_TAG_GPS_ALTITUDE 0x6
276 #define EXIF_TAG_GPS_SPEED_REF 0xC
277 #define EXIF_TAG_GPS_SPEED 0xD
278 #define EXIF_TAG_GPS_TRACK_REF 0xE
279 #define EXIF_TAG_GPS_TRACK 0xF
280 #define EXIF_TAG_GPS_IMAGE_DIRECTION_REF 0x10
281 #define EXIF_TAG_GPS_IMAGE_DIRECTION 0x11
282 #define EXIF_TAG_GPS_HORIZONTAL_POSITIONING_ERROR 0x1F
283 #define EXIF_TAG_IMAGE_DESCRIPTION 0x10E
284 #define EXIF_TAG_MAKE 0x10F
285 #define EXIF_TAG_MODEL 0x110
286 #define EXIF_TAG_ORIENTATION 0x112
287 #define EXIF_TAG_XRESOLUTION 0x11A
288 #define EXIF_TAG_YRESOLUTION 0x11B
289 #define EXIF_TAG_RESOLUTION_UNIT 0x128
290 #define EXIF_TAG_SOFTWARE 0x131
291 #define EXIF_TAG_DATE_TIME 0x132
292 #define EXIF_TAG_ARTIST 0x13B
293 #define EXIF_TAG_COPYRIGHT 0x8298
294 #define EXIF_TAG_EXPOSURE_TIME 0x829A
295 #define EXIF_TAG_F_NUMBER 0x829D
296 #define EXIF_TAG_EXPOSURE_PROGRAM 0x8822
297 #define EXIF_TAG_PHOTOGRAPHIC_SENSITIVITY 0x8827
298 #define EXIF_TAG_SENSITIVITY_TYPE 0x8830
299 #define EXIF_TAG_ISO_SPEED 0x8833
300 #define EXIF_TAG_DATE_TIME_ORIGINAL 0x9003
301 #define EXIF_TAG_DATE_TIME_DIGITIZED 0x9004
302 #define EXIF_TAG_SHUTTER_SPEED_VALUE 0x9201
303 #define EXIF_TAG_APERTURE_VALUE 0x9202
304 #define EXIF_TAG_EXPOSURE_BIAS 0x9204
305 #define EXIF_TAG_METERING_MODE 0x9207
306 #define EXIF_TAG_FLASH 0x9209
307 #define EXIF_TAG_FOCAL_LENGTH 0x920A
308 #define EXIF_TAG_MAKER_NOTE 0x927C
309 #define EXIF_TAG_FILE_SOURCE 0xA300
310 #define EXIF_TAG_SCENE_TYPE 0xA301
311 #define EXIF_TAG_EXPOSURE_MODE 0xA402
312 #define EXIF_TAG_WHITE_BALANCE 0xA403
313 #define EXIF_TAG_DIGITAL_ZOOM_RATIO 0xA404
314 #define EXIF_TAG_SCENE_CAPTURE_TYPE 0xA406
315 #define EXIF_TAG_GAIN_CONTROL 0xA407
316 #define EXIF_TAG_CONTRAST 0xA408
317 #define EXIF_TAG_SATURATION 0xA409
318 #define EXIF_TAG_SHARPNESS 0xA40A
319
320 /* IFD pointer tags */
321 #define EXIF_IFD_TAG 0x8769
322 #define EXIF_GPS_IFD_TAG 0x8825
323
324 /* version tags */
325 #define EXIF_VERSION_TAG 0x9000
326 #define EXIF_FLASHPIX_VERSION_TAG 0xA000
327
328 /* useful macros for speed tag */
329 #define METERS_PER_SECOND_TO_KILOMETERS_PER_HOUR (3.6)
330 #define KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND (1/3.6)
331 #define MILES_PER_HOUR_TO_METERS_PER_SECOND (0.44704)
332 #define KNOTS_TO_METERS_PER_SECOND (0.514444)
333
334 /*
335  * Should be kept in ascending id order
336  *
337  * {gst-tag, exif-tag, exig-type, complementary-exif-tag, serialization-func,
338  *     deserialization-func}
339  */
340 static const GstExifTagMatch tag_map_ifd0[] = {
341   {GST_TAG_IMAGE_HORIZONTAL_PPI, EXIF_TAG_XRESOLUTION, EXIF_TYPE_RATIONAL,
342       0, NULL, deserialize_add_to_pending_tags},
343   {GST_TAG_IMAGE_VERTICAL_PPI, EXIF_TAG_YRESOLUTION, EXIF_TYPE_RATIONAL,
344       0, NULL, deserialize_add_to_pending_tags},
345   {NULL, EXIF_TAG_RESOLUTION_UNIT, EXIF_TYPE_SHORT, 0, NULL,
346       deserialize_resolution},
347   {GST_TAG_DESCRIPTION, EXIF_TAG_IMAGE_DESCRIPTION, EXIF_TYPE_ASCII, 0, NULL,
348       NULL},
349   {GST_TAG_DEVICE_MANUFACTURER, EXIF_TAG_MAKE, EXIF_TYPE_ASCII, 0, NULL, NULL},
350   {GST_TAG_DEVICE_MODEL, EXIF_TAG_MODEL, EXIF_TYPE_ASCII, 0, NULL, NULL},
351   {GST_TAG_IMAGE_ORIENTATION, EXIF_TAG_ORIENTATION, EXIF_TYPE_SHORT, 0,
352         serialize_orientation,
353       deserialize_orientation},
354   {GST_TAG_APPLICATION_NAME, EXIF_TAG_SOFTWARE, EXIF_TYPE_ASCII, 0, NULL, NULL},
355   {GST_TAG_DATE_TIME, EXIF_TAG_DATE_TIME, EXIF_TYPE_ASCII, 0, NULL, NULL},
356   {GST_TAG_ARTIST, EXIF_TAG_ARTIST, EXIF_TYPE_ASCII, 0, NULL, NULL},
357   {GST_TAG_COPYRIGHT, EXIF_TAG_COPYRIGHT, EXIF_TYPE_ASCII, 0, NULL, NULL},
358   {NULL, EXIF_IFD_TAG, EXIF_TYPE_LONG, 0, NULL, NULL},
359   {NULL, EXIF_GPS_IFD_TAG, EXIF_TYPE_LONG, 0, NULL, NULL},
360   {NULL, 0, 0, 0, NULL, NULL}
361 };
362
363 static const GstExifTagMatch tag_map_exif[] = {
364   {GST_TAG_CAPTURING_SHUTTER_SPEED, EXIF_TAG_EXPOSURE_TIME, EXIF_TYPE_RATIONAL,
365         0,
366       NULL, NULL},
367   {GST_TAG_CAPTURING_FOCAL_RATIO, EXIF_TAG_F_NUMBER, EXIF_TYPE_RATIONAL, 0,
368         NULL,
369       NULL},
370   {GST_TAG_CAPTURING_EXPOSURE_PROGRAM, EXIF_TAG_EXPOSURE_PROGRAM,
371         EXIF_TYPE_SHORT, 0, serialize_exposure_program,
372       deserialize_exposure_program},
373
374   /* don't need the serializer as we always write the iso speed alone */
375   {GST_TAG_CAPTURING_ISO_SPEED, EXIF_TAG_PHOTOGRAPHIC_SENSITIVITY,
376         EXIF_TYPE_SHORT, 0, NULL,
377       deserialize_add_to_pending_tags},
378
379   {GST_TAG_CAPTURING_ISO_SPEED, EXIF_TAG_SENSITIVITY_TYPE, EXIF_TYPE_SHORT, 0,
380       serialize_sensitivity_type, deserialize_sensitivity_type},
381   {GST_TAG_CAPTURING_ISO_SPEED, EXIF_TAG_ISO_SPEED, EXIF_TYPE_LONG, 0, NULL,
382       NULL},
383   {NULL, EXIF_VERSION_TAG, EXIF_TYPE_UNDEFINED, 0, NULL, NULL},
384   {GST_TAG_DATE_TIME, EXIF_TAG_DATE_TIME_ORIGINAL, EXIF_TYPE_ASCII, 0, NULL,
385       NULL},
386   {GST_TAG_CAPTURING_SHUTTER_SPEED, EXIF_TAG_SHUTTER_SPEED_VALUE,
387         EXIF_TYPE_SRATIONAL, 0,
388       serialize_shutter_speed, deserialize_shutter_speed},
389   {GST_TAG_CAPTURING_FOCAL_RATIO, EXIF_TAG_APERTURE_VALUE, EXIF_TYPE_RATIONAL,
390         0,
391       serialize_aperture_value, deserialize_aperture_value},
392   {GST_TAG_CAPTURING_EXPOSURE_COMPENSATION, EXIF_TAG_EXPOSURE_BIAS,
393       EXIF_TYPE_SRATIONAL, 0, NULL, NULL},
394   {GST_TAG_CAPTURING_METERING_MODE, EXIF_TAG_METERING_MODE, EXIF_TYPE_SHORT, 0,
395       serialize_metering_mode, deserialize_metering_mode},
396   {GST_TAG_CAPTURING_FLASH_FIRED, EXIF_TAG_FLASH, EXIF_TYPE_SHORT, 0,
397       serialize_flash, deserialize_flash},
398   {GST_TAG_CAPTURING_FOCAL_LENGTH, EXIF_TAG_FOCAL_LENGTH, EXIF_TYPE_RATIONAL, 0,
399       NULL, NULL},
400   {GST_TAG_APPLICATION_DATA, EXIF_TAG_MAKER_NOTE, EXIF_TYPE_UNDEFINED, 0, NULL,
401       NULL},
402   {NULL, EXIF_FLASHPIX_VERSION_TAG, EXIF_TYPE_UNDEFINED, 0, NULL, NULL},
403   {GST_TAG_CAPTURING_SOURCE, EXIF_TAG_FILE_SOURCE, EXIF_TYPE_UNDEFINED,
404       0, serialize_source, deserialize_source},
405   {GST_TAG_CAPTURING_SOURCE, EXIF_TAG_SCENE_TYPE, EXIF_TYPE_UNDEFINED,
406       0, serialize_scene_type, deserialize_scene_type},
407   {GST_TAG_CAPTURING_EXPOSURE_MODE, EXIF_TAG_EXPOSURE_MODE, EXIF_TYPE_SHORT,
408       0, serialize_exposure_mode, deserialize_exposure_mode},
409   {GST_TAG_CAPTURING_WHITE_BALANCE, EXIF_TAG_WHITE_BALANCE, EXIF_TYPE_SHORT,
410       0, serialize_white_balance, deserialize_white_balance},
411   {GST_TAG_CAPTURING_DIGITAL_ZOOM_RATIO, EXIF_TAG_DIGITAL_ZOOM_RATIO,
412         EXIF_TYPE_RATIONAL, 0, NULL,
413       NULL},
414   {GST_TAG_CAPTURING_SCENE_CAPTURE_TYPE, EXIF_TAG_SCENE_CAPTURE_TYPE,
415         EXIF_TYPE_SHORT, 0, serialize_scene_capture_type,
416       deserialize_scene_capture_type},
417   {GST_TAG_CAPTURING_GAIN_ADJUSTMENT, EXIF_TAG_GAIN_CONTROL,
418         EXIF_TYPE_SHORT, 0, serialize_gain_control,
419       deserialize_gain_control},
420   {GST_TAG_CAPTURING_CONTRAST, EXIF_TAG_CONTRAST, EXIF_TYPE_SHORT, 0,
421       serialize_contrast, deserialize_contrast},
422   {GST_TAG_CAPTURING_SATURATION, EXIF_TAG_SATURATION, EXIF_TYPE_SHORT, 0,
423       serialize_saturation, deserialize_saturation},
424   {GST_TAG_CAPTURING_SHARPNESS, EXIF_TAG_SHARPNESS, EXIF_TYPE_SHORT, 0,
425       serialize_sharpness, deserialize_sharpness},
426   {NULL, 0, 0, 0, NULL, NULL}
427 };
428
429 static const GstExifTagMatch tag_map_gps[] = {
430   {GST_TAG_GEO_LOCATION_LATITUDE, EXIF_TAG_GPS_LATITUDE, EXIF_TYPE_RATIONAL,
431         EXIF_TAG_GPS_LATITUDE_REF,
432       serialize_geo_coordinate, deserialize_geo_coordinate},
433   {GST_TAG_GEO_LOCATION_LONGITUDE, EXIF_TAG_GPS_LONGITUDE, EXIF_TYPE_RATIONAL,
434         EXIF_TAG_GPS_LONGITUDE_REF,
435       serialize_geo_coordinate, deserialize_geo_coordinate},
436   {GST_TAG_GEO_LOCATION_ELEVATION, EXIF_TAG_GPS_ALTITUDE, EXIF_TYPE_RATIONAL,
437         EXIF_TAG_GPS_ALTITUDE_REF,
438       serialize_geo_elevation, deserialize_geo_elevation},
439   {GST_TAG_GEO_LOCATION_MOVEMENT_SPEED, EXIF_TAG_GPS_SPEED, EXIF_TYPE_RATIONAL,
440         EXIF_TAG_GPS_SPEED_REF,
441       serialize_speed, deserialize_speed},
442   {GST_TAG_GEO_LOCATION_MOVEMENT_DIRECTION, EXIF_TAG_GPS_TRACK,
443         EXIF_TYPE_RATIONAL, EXIF_TAG_GPS_TRACK_REF,
444       serialize_geo_direction, deserialize_geo_direction},
445   {GST_TAG_GEO_LOCATION_CAPTURE_DIRECTION, EXIF_TAG_GPS_IMAGE_DIRECTION,
446         EXIF_TYPE_RATIONAL, EXIF_TAG_GPS_IMAGE_DIRECTION_REF,
447       serialize_geo_direction, deserialize_geo_direction},
448   {GST_TAG_GEO_LOCATION_HORIZONTAL_ERROR,
449         EXIF_TAG_GPS_HORIZONTAL_POSITIONING_ERROR,
450       EXIF_TYPE_RATIONAL, 0, NULL, NULL},
451   {NULL, 0, 0, 0, NULL, NULL}
452 };
453
454 /* GstExifReader functions */
455 static void
456 gst_exif_reader_init (GstExifReader * reader, gint byte_order,
457     const GstBuffer * buf, guint32 base_offset)
458 {
459   ensure_exif_tags ();
460
461   reader->taglist = gst_tag_list_new ();
462   reader->buffer = buf;
463   reader->base_offset = base_offset;
464   reader->byte_order = byte_order;
465   reader->pending_tags = NULL;
466   if (reader->byte_order != G_LITTLE_ENDIAN &&
467       reader->byte_order != G_BIG_ENDIAN) {
468     GST_WARNING ("Unexpected byte order %d, using system default: %d",
469         reader->byte_order, G_BYTE_ORDER);
470     reader->byte_order = G_BYTE_ORDER;
471   }
472 }
473
474 static void
475 gst_exif_reader_add_pending_tag (GstExifReader * reader, GstExifTagData * data)
476 {
477   GstExifTagData *copy;
478
479   copy = g_slice_new (GstExifTagData);
480   memcpy (copy, data, sizeof (GstExifTagData));
481
482   reader->pending_tags = g_slist_prepend (reader->pending_tags, copy);
483 }
484
485 static GstExifTagData *
486 gst_exif_reader_get_pending_tag (GstExifReader * reader, gint tagid)
487 {
488   GSList *walker;
489
490   for (walker = reader->pending_tags; walker; walker = g_slist_next (walker)) {
491     GstExifTagData *data = (GstExifTagData *) walker->data;
492     if (data->tag == tagid)
493       return data;
494   }
495
496   return NULL;
497 }
498
499 static GstTagList *
500 gst_exif_reader_reset (GstExifReader * reader, gboolean return_taglist)
501 {
502   GstTagList *ret = NULL;
503   GSList *walker;
504
505   for (walker = reader->pending_tags; walker; walker = g_slist_next (walker)) {
506     GstExifTagData *data = (GstExifTagData *) walker->data;
507
508     g_slice_free (GstExifTagData, data);
509   }
510   g_slist_free (reader->pending_tags);
511
512   if (return_taglist) {
513     ret = reader->taglist;
514     reader->taglist = NULL;
515   }
516
517   if (reader->taglist) {
518     gst_tag_list_free (reader->taglist);
519   }
520
521   return ret;
522 }
523
524 /* GstExifWriter functions */
525
526 static void
527 gst_exif_writer_init (GstExifWriter * writer, gint byte_order)
528 {
529   ensure_exif_tags ();
530
531   gst_byte_writer_init (&writer->tagwriter);
532   gst_byte_writer_init (&writer->datawriter);
533
534   writer->byte_order = byte_order;
535   writer->tags_total = 0;
536   if (writer->byte_order != G_LITTLE_ENDIAN &&
537       writer->byte_order != G_BIG_ENDIAN) {
538     GST_WARNING ("Unexpected byte order %d, using system default: %d",
539         writer->byte_order, G_BYTE_ORDER);
540     writer->byte_order = G_BYTE_ORDER;
541   }
542 }
543
544 static GstBuffer *
545 gst_exif_writer_reset_and_get_buffer (GstExifWriter * writer)
546 {
547   GstBuffer *header;
548   GstBuffer *data;
549
550   header = gst_byte_writer_reset_and_get_buffer (&writer->tagwriter);
551   data = gst_byte_writer_reset_and_get_buffer (&writer->datawriter);
552
553   return gst_buffer_join (header, data);
554 }
555
556 /*
557  * Given the exif tag with the passed id, returns the map index of the tag
558  * corresponding to it. If use_complementary is true, then the complementary
559  * are also used in the search.
560  *
561  * Returns -1 if not found
562  */
563 static gint
564 exif_tag_map_find_reverse (guint16 exif_tag, const GstExifTagMatch * tag_map,
565     gboolean use_complementary)
566 {
567   gint i;
568
569   for (i = 0; tag_map[i].exif_tag != 0; i++) {
570     if (exif_tag == tag_map[i].exif_tag || (use_complementary &&
571             exif_tag == tag_map[i].complementary_tag)) {
572       return i;
573     }
574   }
575   return -1;
576 }
577
578 static gboolean
579 gst_tag_list_has_ifd_tags (const GstTagList * taglist,
580     const GstExifTagMatch * tag_map)
581 {
582   gint i;
583
584   for (i = 0; tag_map[i].exif_tag != 0; i++) {
585     if (tag_map[i].gst_tag == NULL) {
586       if (tag_map[i].exif_tag == EXIF_GPS_IFD_TAG &&
587           gst_tag_list_has_ifd_tags (taglist, tag_map_gps))
588         return TRUE;
589       if (tag_map[i].exif_tag == EXIF_IFD_TAG &&
590           gst_tag_list_has_ifd_tags (taglist, tag_map_exif))
591         return TRUE;
592       continue;
593     }
594
595     if (gst_tag_list_get_value_index (taglist, tag_map[i].gst_tag, 0)) {
596       return TRUE;
597     }
598   }
599   return FALSE;
600 }
601
602 /*
603  * Writes the tag entry.
604  *
605  * The tag entry is the tag id, the tag type,
606  * the count and the offset.
607  *
608  * The offset is the on the amount of data writen so far, as one
609  * can't predict the total bytes that the tag entries will take.
610  * This means those fields requires being updated later.
611  */
612 static void
613 gst_exif_writer_write_tag_header (GstExifWriter * writer,
614     guint16 exif_tag, guint16 exif_type, guint32 count, guint32 offset,
615     const guint32 * offset_data)
616 {
617   GST_DEBUG ("Writing tag entry: id %x, type %u, count %u, offset %u",
618       exif_tag, exif_type, count, offset);
619
620   if (writer->byte_order == G_LITTLE_ENDIAN) {
621     gst_byte_writer_put_uint16_le (&writer->tagwriter, exif_tag);
622     gst_byte_writer_put_uint16_le (&writer->tagwriter, exif_type);
623     gst_byte_writer_put_uint32_le (&writer->tagwriter, count);
624     if (offset_data != NULL) {
625       gst_byte_writer_put_data (&writer->tagwriter, (guint8 *) offset_data, 4);
626     } else {
627       gst_byte_writer_put_uint32_le (&writer->tagwriter, offset);
628     }
629   } else if (writer->byte_order == G_BIG_ENDIAN) {
630     gst_byte_writer_put_uint16_be (&writer->tagwriter, exif_tag);
631     gst_byte_writer_put_uint16_be (&writer->tagwriter, exif_type);
632     gst_byte_writer_put_uint32_be (&writer->tagwriter, count);
633     if (offset_data != NULL) {
634       gst_byte_writer_put_data (&writer->tagwriter, (guint8 *) offset_data, 4);
635     } else {
636       gst_byte_writer_put_uint32_be (&writer->tagwriter, offset);
637     }
638   } else {
639     g_assert_not_reached ();
640   }
641
642   writer->tags_total++;
643 }
644
645 static void
646 gst_exif_writer_write_rational_data (GstExifWriter * writer, guint32 frac_n,
647     guint32 frac_d)
648 {
649   if (writer->byte_order == G_LITTLE_ENDIAN) {
650     gst_byte_writer_put_uint32_le (&writer->datawriter, frac_n);
651     gst_byte_writer_put_uint32_le (&writer->datawriter, frac_d);
652   } else {
653     gst_byte_writer_put_uint32_be (&writer->datawriter, frac_n);
654     gst_byte_writer_put_uint32_be (&writer->datawriter, frac_d);
655   }
656 }
657
658 static void
659 gst_exif_writer_write_signed_rational_data (GstExifWriter * writer,
660     gint32 frac_n, gint32 frac_d)
661 {
662   if (writer->byte_order == G_LITTLE_ENDIAN) {
663     gst_byte_writer_put_int32_le (&writer->datawriter, frac_n);
664     gst_byte_writer_put_int32_le (&writer->datawriter, frac_d);
665   } else {
666     gst_byte_writer_put_int32_be (&writer->datawriter, frac_n);
667     gst_byte_writer_put_int32_be (&writer->datawriter, frac_d);
668   }
669 }
670
671 static void
672 gst_exif_writer_write_rational_tag (GstExifWriter * writer,
673     guint16 tag, guint32 frac_n, guint32 frac_d)
674 {
675   guint32 offset = gst_byte_writer_get_size (&writer->datawriter);
676
677   gst_exif_writer_write_tag_header (writer, tag, EXIF_TYPE_RATIONAL,
678       1, offset, NULL);
679
680   gst_exif_writer_write_rational_data (writer, frac_n, frac_d);
681 }
682
683 static void
684 gst_exif_writer_write_signed_rational_tag (GstExifWriter * writer,
685     guint16 tag, gint32 frac_n, gint32 frac_d)
686 {
687   guint32 offset = gst_byte_writer_get_size (&writer->datawriter);
688
689   gst_exif_writer_write_tag_header (writer, tag, EXIF_TYPE_SRATIONAL,
690       1, offset, NULL);
691
692   gst_exif_writer_write_signed_rational_data (writer, frac_n, frac_d);
693 }
694
695 static void
696 gst_exif_writer_write_rational_tag_from_double (GstExifWriter * writer,
697     guint16 tag, gdouble value)
698 {
699   gint frac_n;
700   gint frac_d;
701
702   gst_util_double_to_fraction (value, &frac_n, &frac_d);
703
704   gst_exif_writer_write_rational_tag (writer, tag, frac_n, frac_d);
705 }
706
707 static void
708 gst_exif_writer_write_signed_rational_tag_from_double (GstExifWriter * writer,
709     guint16 tag, gdouble value)
710 {
711   gint frac_n;
712   gint frac_d;
713
714   gst_util_double_to_fraction (value, &frac_n, &frac_d);
715
716   gst_exif_writer_write_signed_rational_tag (writer, tag, frac_n, frac_d);
717 }
718
719 static void
720 gst_exif_writer_write_byte_tag (GstExifWriter * writer, guint16 tag,
721     guint8 value)
722 {
723   guint32 offset = 0;
724
725   GST_WRITE_UINT8 ((guint8 *) & offset, value);
726   gst_exif_writer_write_tag_header (writer, tag, EXIF_TYPE_BYTE,
727       1, offset, &offset);
728 }
729
730 static void
731 gst_exif_writer_write_short_tag (GstExifWriter * writer, guint16 tag,
732     guint16 value)
733 {
734   guint32 offset = 0;
735
736   if (writer->byte_order == G_LITTLE_ENDIAN) {
737     GST_WRITE_UINT16_LE ((guint8 *) & offset, value);
738   } else {
739     GST_WRITE_UINT16_BE ((guint8 *) & offset, value);
740   }
741
742   gst_exif_writer_write_tag_header (writer, tag, EXIF_TYPE_SHORT,
743       1, offset, &offset);
744 }
745
746 static void
747 gst_exif_writer_write_long_tag (GstExifWriter * writer, guint16 tag,
748     guint32 value)
749 {
750   guint32 offset = 0;
751   if (writer->byte_order == G_LITTLE_ENDIAN) {
752     GST_WRITE_UINT32_LE ((guint8 *) & offset, value);
753   } else {
754     GST_WRITE_UINT32_BE ((guint8 *) & offset, value);
755   }
756
757   gst_exif_writer_write_tag_header (writer, tag, EXIF_TYPE_LONG,
758       1, offset, &offset);
759 }
760
761
762 static void
763 write_exif_undefined_tag (GstExifWriter * writer, guint16 tag,
764     const guint8 * data, gint size)
765 {
766   guint32 offset = 0;
767
768   if (size > 4) {
769     /* we only use the data offset here, later we add up the
770      * resulting tag headers offset and the base offset */
771     offset = gst_byte_writer_get_size (&writer->datawriter);
772     gst_exif_writer_write_tag_header (writer, tag, EXIF_TYPE_UNDEFINED,
773         size, offset, NULL);
774     gst_byte_writer_put_data (&writer->datawriter, data, size);
775   } else {
776     /* small enough to go in the offset */
777     memcpy ((guint8 *) & offset, data, size);
778     gst_exif_writer_write_tag_header (writer, tag, EXIF_TYPE_UNDEFINED,
779         size, offset, &offset);
780   }
781 }
782
783 static void
784 write_exif_ascii_tag (GstExifWriter * writer, guint16 tag, const gchar * str)
785 {
786   guint32 offset = 0;
787   gchar *ascii_str;
788   gsize ascii_size;
789   GError *error = NULL;
790
791   ascii_str = g_convert (str, -1, "latin1", "utf8", NULL, &ascii_size, &error);
792
793   if (error) {
794     GST_WARNING ("Failed to convert exif tag to ascii: 0x%x - %s. Error: %s",
795         tag, str, error->message);
796     g_error_free (error);
797     g_free (ascii_str);
798     return;
799   }
800
801   /* add the \0 at the end */
802   ascii_size++;
803
804   if (ascii_size > 4) {
805     /* we only use the data offset here, later we add up the
806      * resulting tag headers offset and the base offset */
807     offset = gst_byte_writer_get_size (&writer->datawriter);
808     gst_exif_writer_write_tag_header (writer, tag, EXIF_TYPE_ASCII,
809         ascii_size, offset, NULL);
810     gst_byte_writer_put_string (&writer->datawriter, ascii_str);
811   } else {
812     /* small enough to go in the offset */
813     memcpy ((guint8 *) & offset, ascii_str, ascii_size);
814     gst_exif_writer_write_tag_header (writer, tag, EXIF_TYPE_ASCII,
815         ascii_size, offset, &offset);
816   }
817
818   g_free (ascii_str);
819 }
820
821 static void
822 write_exif_ascii_tag_from_taglist (GstExifWriter * writer,
823     const GstTagList * taglist, const GstExifTagMatch * exiftag)
824 {
825   gchar *str = NULL;
826   gboolean cleanup = FALSE;
827   const GValue *value;
828   gint tag_size = gst_tag_list_get_tag_size (taglist, exiftag->gst_tag);
829
830   if (tag_size != 1) {
831     /* FIXME support this by serializing them with a ','? */
832     GST_WARNING ("Multiple string tags not supported yet");
833     return;
834   }
835
836   value = gst_tag_list_get_value_index (taglist, exiftag->gst_tag, 0);
837
838   /* do some conversion if needed */
839   switch (G_VALUE_TYPE (value)) {
840     case G_TYPE_STRING:
841       str = (gchar *) g_value_get_string (value);
842       break;
843     default:
844       if (G_VALUE_TYPE (value) == GST_TYPE_DATE_TIME) {
845         GstDateTime *dt = (GstDateTime *) g_value_get_boxed (value);
846
847         if (dt == NULL) {
848           GST_WARNING ("NULL datetime received");
849           break;
850         }
851
852         str = g_strdup_printf ("%04d:%02d:%02d %02d:%02d:%02d",
853             gst_date_time_get_year (dt), gst_date_time_get_month (dt),
854             gst_date_time_get_day (dt), gst_date_time_get_hour (dt),
855             gst_date_time_get_minute (dt), gst_date_time_get_second (dt));
856
857         cleanup = TRUE;
858       } else {
859         GST_WARNING ("Conversion from %s to ascii string not supported",
860             G_VALUE_TYPE_NAME (value));
861       }
862       break;
863   }
864
865   if (str == NULL)
866     return;
867
868   write_exif_ascii_tag (writer, exiftag->exif_tag, str);
869   if (cleanup)
870     g_free (str);
871 }
872
873 static void
874 write_exif_undefined_tag_from_taglist (GstExifWriter * writer,
875     const GstTagList * taglist, const GstExifTagMatch * exiftag)
876 {
877   const GValue *value;
878   const guint8 *data = NULL;
879   gint size = 0;
880   gint tag_size = gst_tag_list_get_tag_size (taglist, exiftag->gst_tag);
881
882   if (tag_size != 1) {
883     GST_WARNING ("Only the first item in the taglist will be serialized");
884     return;
885   }
886
887   value = gst_tag_list_get_value_index (taglist, exiftag->gst_tag, 0);
888
889   /* do some conversion if needed */
890   switch (G_VALUE_TYPE (value)) {
891     case G_TYPE_STRING:
892       data = (guint8 *) g_value_get_string (value);
893       size = strlen ((gchar *) data);   /* no need to +1, undefined doesn't require it */
894       break;
895     default:
896       if (G_VALUE_TYPE (value) == GST_TYPE_BUFFER) {
897         GstBuffer *buf = gst_value_get_buffer (value);
898
899         data = GST_BUFFER_DATA (buf);
900         size = GST_BUFFER_SIZE (buf);
901       } else {
902         GST_WARNING ("Conversion from %s to raw data not supported",
903             G_VALUE_TYPE_NAME (value));
904       }
905       break;
906   }
907
908   if (size == 0)
909     return;
910
911   write_exif_undefined_tag (writer, exiftag->exif_tag, data, size);
912 }
913
914 static void
915 write_exif_rational_tag_from_taglist (GstExifWriter * writer,
916     const GstTagList * taglist, const GstExifTagMatch * exiftag)
917 {
918   const GValue *value;
919   gdouble num = 0;
920   gint tag_size = gst_tag_list_get_tag_size (taglist, exiftag->gst_tag);
921
922   if (tag_size != 1) {
923     GST_WARNING ("Only the first item in the taglist will be serialized");
924     return;
925   }
926
927   value = gst_tag_list_get_value_index (taglist, exiftag->gst_tag, 0);
928
929   /* do some conversion if needed */
930   switch (G_VALUE_TYPE (value)) {
931     case G_TYPE_DOUBLE:
932       num = g_value_get_double (value);
933       gst_exif_writer_write_rational_tag_from_double (writer, exiftag->exif_tag,
934           num);
935       break;
936     default:
937       if (G_VALUE_TYPE (value) == GST_TYPE_FRACTION) {
938         gst_exif_writer_write_rational_tag (writer, exiftag->exif_tag,
939             gst_value_get_fraction_numerator (value),
940             gst_value_get_fraction_denominator (value));
941       } else {
942         GST_WARNING ("Conversion from %s to rational not supported",
943             G_VALUE_TYPE_NAME (value));
944       }
945       break;
946   }
947 }
948
949 static void
950 write_exif_signed_rational_tag_from_taglist (GstExifWriter * writer,
951     const GstTagList * taglist, const GstExifTagMatch * exiftag)
952 {
953   const GValue *value;
954   gdouble num = 0;
955   gint tag_size = gst_tag_list_get_tag_size (taglist, exiftag->gst_tag);
956
957   if (tag_size != 1) {
958     GST_WARNING ("Only the first item in the taglist will be serialized");
959     return;
960   }
961
962   value = gst_tag_list_get_value_index (taglist, exiftag->gst_tag, 0);
963
964   /* do some conversion if needed */
965   switch (G_VALUE_TYPE (value)) {
966     case G_TYPE_DOUBLE:
967       num = g_value_get_double (value);
968       gst_exif_writer_write_signed_rational_tag_from_double (writer,
969           exiftag->exif_tag, num);
970       break;
971     default:
972       if (G_VALUE_TYPE (value) == GST_TYPE_FRACTION) {
973         gst_exif_writer_write_signed_rational_tag (writer, exiftag->exif_tag,
974             gst_value_get_fraction_numerator (value),
975             gst_value_get_fraction_denominator (value));
976       } else {
977         GST_WARNING ("Conversion from %s to signed rational not supported",
978             G_VALUE_TYPE_NAME (value));
979       }
980       break;
981   }
982 }
983
984 static void
985 write_exif_integer_tag_from_taglist (GstExifWriter * writer,
986     const GstTagList * taglist, const GstExifTagMatch * exiftag)
987 {
988   const GValue *value;
989   guint32 num = 0;
990   gint tag_size = gst_tag_list_get_tag_size (taglist, exiftag->gst_tag);
991
992   if (tag_size != 1) {
993     GST_WARNING ("Only the first item in the taglist will be serialized");
994     return;
995   }
996
997   value = gst_tag_list_get_value_index (taglist, exiftag->gst_tag, 0);
998
999   /* do some conversion if needed */
1000   switch (G_VALUE_TYPE (value)) {
1001     case G_TYPE_INT:
1002       num = g_value_get_int (value);
1003       break;
1004     default:
1005       GST_WARNING ("Conversion from %s to int not supported",
1006           G_VALUE_TYPE_NAME (value));
1007       break;
1008   }
1009
1010   switch (exiftag->exif_type) {
1011     case EXIF_TYPE_LONG:
1012       gst_exif_writer_write_long_tag (writer, exiftag->exif_tag, num);
1013       break;
1014     case EXIF_TYPE_SHORT:
1015       gst_exif_writer_write_short_tag (writer, exiftag->exif_tag, num);
1016       break;
1017     default:
1018       break;
1019   }
1020 }
1021
1022 static void
1023 write_exif_tag_from_taglist (GstExifWriter * writer, const GstTagList * taglist,
1024     const GstExifTagMatch * exiftag)
1025 {
1026   GST_DEBUG ("Writing tag %s", exiftag->gst_tag);
1027
1028   /* check for special handling */
1029   if (exiftag->serialize) {
1030     exiftag->serialize (writer, taglist, exiftag);
1031     return;
1032   }
1033
1034   switch (exiftag->exif_type) {
1035     case EXIF_TYPE_ASCII:
1036       write_exif_ascii_tag_from_taglist (writer, taglist, exiftag);
1037       break;
1038     case EXIF_TYPE_UNDEFINED:
1039       write_exif_undefined_tag_from_taglist (writer, taglist, exiftag);
1040       break;
1041     case EXIF_TYPE_RATIONAL:
1042       write_exif_rational_tag_from_taglist (writer, taglist, exiftag);
1043       break;
1044     case EXIF_TYPE_SRATIONAL:
1045       write_exif_signed_rational_tag_from_taglist (writer, taglist, exiftag);
1046       break;
1047     case EXIF_TYPE_LONG:
1048     case EXIF_TYPE_SHORT:
1049       write_exif_integer_tag_from_taglist (writer, taglist, exiftag);
1050       break;
1051     default:
1052       GST_WARNING ("Unhandled tag type %d", exiftag->exif_type);
1053   }
1054 }
1055
1056 static void
1057 tagdata_copy (GstExifTagData * to, const GstExifTagData * from)
1058 {
1059   to->tag = from->tag;
1060   to->tag_type = from->tag_type;
1061   to->count = from->count;
1062   to->offset = from->offset;
1063   to->offset_as_data = from->offset_as_data;
1064 }
1065
1066 static void
1067 gst_exif_tag_rewrite_offsets (GstByteWriter * writer, gint byte_order,
1068     guint32 offset, gint num_tags, GstByteWriter * inner_ifds_data)
1069 {
1070   GstByteReader *reader;
1071   gint i;
1072   guint16 aux = G_MAXUINT16;
1073
1074   GST_LOG ("Rewriting tag entries offsets");
1075
1076   reader = (GstByteReader *) writer;
1077
1078   if (num_tags == -1) {
1079     if (byte_order == G_LITTLE_ENDIAN) {
1080       gst_byte_reader_get_uint16_le (reader, &aux);
1081     } else {
1082       gst_byte_reader_get_uint16_be (reader, &aux);
1083     }
1084     if (aux == G_MAXUINT16) {
1085       GST_WARNING ("Failed to read number of tags, won't rewrite offsets");
1086       return;
1087     }
1088     num_tags = (gint) aux;
1089   }
1090
1091   g_return_if_fail (num_tags != -1);
1092
1093   GST_DEBUG ("number of tags %d", num_tags);
1094
1095   for (i = 0; i < num_tags; i++) {
1096     guint16 type = 0;
1097     guint32 cur_offset = 0;
1098     gint byte_size = 0;
1099     guint32 count = 0;
1100     guint16 tag_id = 0;
1101
1102     g_assert (gst_byte_writer_get_pos (writer) <
1103         gst_byte_writer_get_size (writer));
1104
1105     /* read the type */
1106     if (byte_order == G_LITTLE_ENDIAN) {
1107       if (!gst_byte_reader_get_uint16_le (reader, &tag_id))
1108         break;
1109       if (!gst_byte_reader_get_uint16_le (reader, &type))
1110         break;
1111       if (!gst_byte_reader_get_uint32_le (reader, &count))
1112         break;
1113     } else {
1114       if (!gst_byte_reader_get_uint16_be (reader, &tag_id))
1115         break;
1116       if (!gst_byte_reader_get_uint16_be (reader, &type))
1117         break;
1118       if (!gst_byte_reader_get_uint32_be (reader, &count))
1119         break;
1120     }
1121
1122     GST_LOG ("Parsed tag %x of type %u and count %u", tag_id, type, count);
1123
1124     switch (type) {
1125       case EXIF_TYPE_BYTE:
1126       case EXIF_TYPE_ASCII:
1127       case EXIF_TYPE_UNDEFINED:
1128         byte_size = count;
1129         break;
1130       case EXIF_TYPE_SHORT:
1131         byte_size = count * 2;  /* 2 bytes */
1132         break;
1133       case EXIF_TYPE_LONG:
1134       case EXIF_TYPE_SLONG:
1135         byte_size = count * 4;  /* 4 bytes */
1136         break;
1137       case EXIF_TYPE_RATIONAL:
1138       case EXIF_TYPE_SRATIONAL:
1139         byte_size = count * 8;  /* 8 bytes */
1140         break;
1141       default:
1142         g_assert_not_reached ();
1143         break;
1144     }
1145
1146     /* adjust the offset if needed */
1147     if (byte_size > 4 || tag_id == EXIF_GPS_IFD_TAG || tag_id == EXIF_IFD_TAG) {
1148       if (byte_order == G_LITTLE_ENDIAN) {
1149         if (gst_byte_reader_peek_uint32_le (reader, &cur_offset)) {
1150           gst_byte_writer_put_uint32_le (writer, cur_offset + offset);
1151         }
1152       } else {
1153         if (gst_byte_reader_peek_uint32_be (reader, &cur_offset)) {
1154           gst_byte_writer_put_uint32_be (writer, cur_offset + offset);
1155         }
1156       }
1157       GST_DEBUG ("Rewriting tag offset from %u to (%u + %u) %u",
1158           cur_offset, cur_offset, offset, cur_offset + offset);
1159
1160       if ((tag_id == EXIF_GPS_IFD_TAG || tag_id == EXIF_IFD_TAG) &&
1161           inner_ifds_data != NULL) {
1162         /* needs special handling */
1163         if (!gst_byte_writer_set_pos (inner_ifds_data, cur_offset)) {
1164           GST_WARNING ("Failed to position writer to rewrite inner ifd "
1165               "offsets");
1166           continue;
1167         }
1168
1169         gst_exif_tag_rewrite_offsets (inner_ifds_data, byte_order, offset, -1,
1170             NULL);
1171       }
1172     } else {
1173       gst_byte_reader_skip (reader, 4);
1174       GST_DEBUG ("No need to rewrite tag offset");
1175     }
1176   }
1177   GST_LOG ("Done rewriting offsets");
1178 }
1179
1180 static void
1181 parse_exif_ascii_tag (GstExifReader * reader, const GstExifTagMatch * tag,
1182     guint32 count, guint32 offset, const guint8 * offset_as_data)
1183 {
1184   GType tagtype;
1185   gchar *str;
1186   gchar *utfstr;
1187   guint32 real_offset;
1188   GError *error = NULL;
1189
1190   if (count > 4) {
1191     if (offset < reader->base_offset) {
1192       GST_WARNING ("Offset is smaller (%u) than base offset (%u)", offset,
1193           reader->base_offset);
1194       return;
1195     }
1196
1197     real_offset = offset - reader->base_offset;
1198     if (real_offset >= GST_BUFFER_SIZE (reader->buffer)) {
1199       GST_WARNING ("Invalid offset %u for buffer of size %u, not adding tag %s",
1200           real_offset, GST_BUFFER_SIZE (reader->buffer), tag->gst_tag);
1201       return;
1202     }
1203
1204     str =
1205         g_strndup ((gchar *) (GST_BUFFER_DATA (reader->buffer) + real_offset),
1206         count);
1207   } else {
1208     str = g_strndup ((gchar *) offset_as_data, count);
1209   }
1210
1211   /* convert from ascii to utf8 */
1212   if (g_utf8_validate (str, -1, NULL)) {
1213     GST_DEBUG ("Exif string is already on utf8: %s", str);
1214     utfstr = str;
1215   } else {
1216     GST_DEBUG ("Exif string isn't utf8, trying to convert from latin1: %s",
1217         str);
1218     utfstr = g_convert (str, count, "utf8", "latin1", NULL, NULL, &error);
1219     g_free (str);
1220     if (error) {
1221       GST_WARNING ("Skipping tag %d:%s. Failed to convert ascii string "
1222           "to utf8 : %s - %s", tag->exif_tag, tag->gst_tag, str,
1223           error->message);
1224       g_error_free (error);
1225       g_free (utfstr);
1226       return;
1227     }
1228   }
1229
1230   tagtype = gst_tag_get_type (tag->gst_tag);
1231   if (tagtype == GST_TYPE_DATE_TIME) {
1232     gint year = 0, month = 1, day = 1, hour = 0, minute = 0, second = 0;
1233
1234     if (sscanf (utfstr, "%04d:%02d:%02d %02d:%02d:%02d", &year, &month, &day,
1235             &hour, &minute, &second) > 0) {
1236       GstDateTime *d;
1237
1238       d = gst_date_time_new_local_time (year, month, day, hour, minute, second);
1239       gst_tag_list_add (reader->taglist, GST_TAG_MERGE_REPLACE,
1240           tag->gst_tag, d, NULL);
1241       gst_date_time_unref (d);
1242     } else {
1243       GST_WARNING ("Failed to parse %s into a datetime tag", str);
1244     }
1245   } else if (tagtype == G_TYPE_STRING) {
1246     gst_tag_list_add (reader->taglist, GST_TAG_MERGE_REPLACE, tag->gst_tag,
1247         utfstr, NULL);
1248   } else {
1249     GST_WARNING ("No parsing function associated to %x(%s)", tag->exif_tag,
1250         tag->gst_tag);
1251   }
1252   g_free (utfstr);
1253 }
1254
1255 static void
1256 parse_exif_long_tag (GstExifReader * reader, const GstExifTagMatch * tag,
1257     guint32 count, guint32 offset, const guint8 * offset_as_data)
1258 {
1259   GType tagtype;
1260
1261   if (count > 1) {
1262     GST_WARNING ("Long tags with more than one value are not supported");
1263     return;
1264   }
1265
1266   tagtype = gst_tag_get_type (tag->gst_tag);
1267   if (tagtype == G_TYPE_INT) {
1268     gst_tag_list_add (reader->taglist, GST_TAG_MERGE_REPLACE, tag->gst_tag,
1269         offset, NULL);
1270   } else {
1271     GST_WARNING ("No parsing function associated to %x(%s)", tag->exif_tag,
1272         tag->gst_tag);
1273   }
1274 }
1275
1276
1277 static void
1278 parse_exif_undefined_tag (GstExifReader * reader, const GstExifTagMatch * tag,
1279     guint32 count, guint32 offset, const guint8 * offset_as_data)
1280 {
1281   GType tagtype;
1282   guint8 *data;
1283   guint32 real_offset;
1284
1285   if (count > 4) {
1286     if (offset < reader->base_offset) {
1287       GST_WARNING ("Offset is smaller (%u) than base offset (%u)", offset,
1288           reader->base_offset);
1289       return;
1290     }
1291
1292     real_offset = offset - reader->base_offset;
1293     if (real_offset >= GST_BUFFER_SIZE (reader->buffer)) {
1294       GST_WARNING ("Invalid offset %u for buffer of size %u, not adding tag %s",
1295           real_offset, GST_BUFFER_SIZE (reader->buffer), tag->gst_tag);
1296       return;
1297     }
1298
1299     /* +1 because it could be a string without the \0 */
1300     data = malloc (sizeof (guint8) * count + 1);
1301     memcpy (data, GST_BUFFER_DATA (reader->buffer) + real_offset, count);
1302     data[count] = 0;
1303   } else {
1304     data = malloc (sizeof (guint8) * count + 1);
1305     memcpy (data, (guint8 *) offset_as_data, count);
1306     data[count] = 0;
1307   }
1308
1309   tagtype = gst_tag_get_type (tag->gst_tag);
1310   if (tagtype == GST_TYPE_BUFFER) {
1311     GstBuffer *buf;
1312
1313     buf = gst_buffer_new ();
1314     GST_BUFFER_DATA (buf) = data;
1315     GST_BUFFER_MALLOCDATA (buf) = data;
1316     GST_BUFFER_SIZE (buf) = count;
1317     data = NULL;
1318
1319     gst_tag_list_add (reader->taglist, GST_TAG_MERGE_APPEND, tag->gst_tag,
1320         buf, NULL);
1321
1322     gst_buffer_unref (buf);
1323   } else if (tagtype == G_TYPE_STRING) {
1324     gst_tag_list_add (reader->taglist, GST_TAG_MERGE_REPLACE, tag->gst_tag,
1325         data, NULL);
1326   } else {
1327     GST_WARNING ("No parsing function associated to %x(%s)", tag->exif_tag,
1328         tag->gst_tag);
1329   }
1330   g_free (data);
1331 }
1332
1333 static gboolean
1334 exif_reader_read_rational_tag (GstExifReader * exif_reader,
1335     guint32 count, guint32 offset, gboolean is_signed,
1336     gint32 * _frac_n, gint32 * _frac_d)
1337 {
1338   GstByteReader data_reader;
1339   guint32 real_offset;
1340   gint32 frac_n = 0;
1341   gint32 frac_d = 0;
1342
1343   if (count > 1) {
1344     GST_WARNING ("Rationals with multiple entries are not supported");
1345   }
1346   if (offset < exif_reader->base_offset) {
1347     GST_WARNING ("Offset is smaller (%u) than base offset (%u)", offset,
1348         exif_reader->base_offset);
1349     return FALSE;
1350   }
1351
1352   real_offset = offset - exif_reader->base_offset;
1353   if (real_offset >= GST_BUFFER_SIZE (exif_reader->buffer)) {
1354     GST_WARNING ("Invalid offset %u for buffer of size %u",
1355         real_offset, GST_BUFFER_SIZE (exif_reader->buffer));
1356     return FALSE;
1357   }
1358
1359   gst_byte_reader_init_from_buffer (&data_reader, exif_reader->buffer);
1360   if (!gst_byte_reader_set_pos (&data_reader, real_offset))
1361     goto reader_fail;
1362
1363   if (!is_signed) {
1364     guint32 aux_n = 0, aux_d = 0;
1365     if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
1366       if (!gst_byte_reader_get_uint32_le (&data_reader, &aux_n) ||
1367           !gst_byte_reader_get_uint32_le (&data_reader, &aux_d))
1368         goto reader_fail;
1369     } else {
1370       if (!gst_byte_reader_get_uint32_be (&data_reader, &aux_n) ||
1371           !gst_byte_reader_get_uint32_be (&data_reader, &aux_d))
1372         goto reader_fail;
1373     }
1374     frac_n = (gint32) aux_n;
1375     frac_d = (gint32) aux_d;
1376   } else {
1377     if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
1378       if (!gst_byte_reader_get_int32_le (&data_reader, &frac_n) ||
1379           !gst_byte_reader_get_int32_le (&data_reader, &frac_d))
1380         goto reader_fail;
1381     } else {
1382       if (!gst_byte_reader_get_int32_be (&data_reader, &frac_n) ||
1383           !gst_byte_reader_get_int32_be (&data_reader, &frac_d))
1384         goto reader_fail;
1385     }
1386   }
1387
1388   if (_frac_n)
1389     *_frac_n = frac_n;
1390   if (_frac_d)
1391     *_frac_d = frac_d;
1392
1393   return TRUE;
1394
1395 reader_fail:
1396   GST_WARNING ("Failed to read from byte reader. (Buffer too short?)");
1397   return FALSE;
1398 }
1399
1400 static void
1401 parse_exif_rational_tag (GstExifReader * exif_reader,
1402     const gchar * gst_tag, guint32 count, guint32 offset, gdouble multiplier,
1403     gboolean is_signed)
1404 {
1405   GType type;
1406   gint32 frac_n = 0;
1407   gint32 frac_d = 1;
1408   gdouble value;
1409
1410   GST_DEBUG ("Reading fraction for tag %s...", gst_tag);
1411   if (!exif_reader_read_rational_tag (exif_reader, count, offset, is_signed,
1412           &frac_n, &frac_d))
1413     return;
1414   GST_DEBUG ("Read fraction for tag %s: %d/%d", gst_tag, frac_n, frac_d);
1415
1416   type = gst_tag_get_type (gst_tag);
1417   switch (type) {
1418     case G_TYPE_DOUBLE:
1419       gst_util_fraction_to_double (frac_n, frac_d, &value);
1420       value *= multiplier;
1421       GST_DEBUG ("Adding %s tag: %lf", gst_tag, value);
1422       gst_tag_list_add (exif_reader->taglist, GST_TAG_MERGE_REPLACE, gst_tag,
1423           value, NULL);
1424       break;
1425     default:
1426       if (type == GST_TYPE_FRACTION) {
1427         GValue fraction = { 0 };
1428
1429         g_value_init (&fraction, GST_TYPE_FRACTION);
1430         gst_value_set_fraction (&fraction, frac_n * multiplier, frac_d);
1431         gst_tag_list_add_value (exif_reader->taglist, GST_TAG_MERGE_REPLACE,
1432             gst_tag, &fraction);
1433         g_value_unset (&fraction);
1434       } else {
1435         GST_WARNING ("Can't convert from fraction into %s", g_type_name (type));
1436       }
1437   }
1438
1439 }
1440
1441 static GstBuffer *
1442 write_exif_ifd (const GstTagList * taglist, guint byte_order,
1443     guint32 base_offset, const GstExifTagMatch * tag_map)
1444 {
1445   GstExifWriter writer;
1446   gint i;
1447
1448   GST_DEBUG ("Formatting taglist %p as exif buffer. Byte order: %d, "
1449       "base_offset: %u", taglist, byte_order, base_offset);
1450
1451   g_assert (byte_order == G_LITTLE_ENDIAN || byte_order == G_BIG_ENDIAN);
1452
1453   if (!gst_tag_list_has_ifd_tags (taglist, tag_map)) {
1454     GST_DEBUG ("No tags for this ifd");
1455     return NULL;
1456   }
1457
1458   gst_exif_writer_init (&writer, byte_order);
1459
1460   /* write tag number as 0 */
1461   gst_byte_writer_put_uint16_le (&writer.tagwriter, 0);
1462
1463   /* write both tag headers and data
1464    * in ascending id order */
1465
1466   for (i = 0; tag_map[i].exif_tag != 0; i++) {
1467
1468     /* special cases have NULL gst tag */
1469     if (tag_map[i].gst_tag == NULL) {
1470       GstBuffer *inner_ifd = NULL;
1471       const GstExifTagMatch *inner_tag_map = NULL;
1472
1473       GST_LOG ("Inner ifd tag: %x", tag_map[i].exif_tag);
1474
1475       if (tag_map[i].exif_tag == EXIF_GPS_IFD_TAG) {
1476         inner_tag_map = tag_map_gps;
1477       } else if (tag_map[i].exif_tag == EXIF_IFD_TAG) {
1478         inner_tag_map = tag_map_exif;
1479       } else if (tag_map[i].exif_tag == EXIF_VERSION_TAG) {
1480         /* special case where we write the exif version */
1481         write_exif_undefined_tag (&writer, EXIF_VERSION_TAG, (guint8 *) "0230",
1482             4);
1483       } else if (tag_map[i].exif_tag == EXIF_FLASHPIX_VERSION_TAG) {
1484         /* special case where we write the flashpix version */
1485         write_exif_undefined_tag (&writer, EXIF_FLASHPIX_VERSION_TAG,
1486             (guint8 *) "0100", 4);
1487       }
1488
1489       if (inner_tag_map) {
1490         /* base offset and tagheader size are added when rewriting offset */
1491         inner_ifd = write_exif_ifd (taglist, byte_order,
1492             gst_byte_writer_get_size (&writer.datawriter), inner_tag_map);
1493       }
1494
1495       if (inner_ifd) {
1496         GST_DEBUG ("Adding inner ifd: %x", tag_map[i].exif_tag);
1497         gst_exif_writer_write_tag_header (&writer, tag_map[i].exif_tag,
1498             EXIF_TYPE_LONG, 1,
1499             gst_byte_writer_get_size (&writer.datawriter), NULL);
1500         gst_byte_writer_put_data (&writer.datawriter,
1501             GST_BUFFER_DATA (inner_ifd), GST_BUFFER_SIZE (inner_ifd));
1502         gst_buffer_unref (inner_ifd);
1503       }
1504       continue;
1505     }
1506
1507     GST_LOG ("Checking tag %s", tag_map[i].gst_tag);
1508     if (gst_tag_list_get_value_index (taglist, tag_map[i].gst_tag, 0) == NULL)
1509       continue;
1510
1511     write_exif_tag_from_taglist (&writer, taglist, &tag_map[i]);
1512   }
1513
1514   /* Add the next IFD offset, we just set it to 0 because
1515    * there is no easy way to predict what it is going to be.
1516    * The user might rewrite the value if needed */
1517   gst_byte_writer_put_uint32_le (&writer.tagwriter, 0);
1518
1519   /* write the number of tags */
1520   gst_byte_writer_set_pos (&writer.tagwriter, 0);
1521   if (writer.byte_order == G_LITTLE_ENDIAN)
1522     gst_byte_writer_put_uint16_le (&writer.tagwriter, writer.tags_total);
1523   else
1524     gst_byte_writer_put_uint16_be (&writer.tagwriter, writer.tags_total);
1525
1526   GST_DEBUG ("Number of tags rewritten to %d", writer.tags_total);
1527
1528   /* now that we know the tag headers size, we can add the offsets */
1529   gst_exif_tag_rewrite_offsets (&writer.tagwriter, writer.byte_order,
1530       base_offset + gst_byte_writer_get_size (&writer.tagwriter),
1531       writer.tags_total, &writer.datawriter);
1532
1533   return gst_exif_writer_reset_and_get_buffer (&writer);
1534 }
1535
1536 static gboolean
1537 parse_exif_tag_header (GstByteReader * reader, gint byte_order,
1538     GstExifTagData * _tagdata)
1539 {
1540   g_assert (_tagdata);
1541
1542   /* read the fields */
1543   if (byte_order == G_LITTLE_ENDIAN) {
1544     if (!gst_byte_reader_get_uint16_le (reader, &_tagdata->tag) ||
1545         !gst_byte_reader_get_uint16_le (reader, &_tagdata->tag_type) ||
1546         !gst_byte_reader_get_uint32_le (reader, &_tagdata->count) ||
1547         !gst_byte_reader_get_data (reader, 4, &_tagdata->offset_as_data)) {
1548       return FALSE;
1549     }
1550     _tagdata->offset = GST_READ_UINT32_LE (_tagdata->offset_as_data);
1551   } else {
1552     if (!gst_byte_reader_get_uint16_be (reader, &_tagdata->tag) ||
1553         !gst_byte_reader_get_uint16_be (reader, &_tagdata->tag_type) ||
1554         !gst_byte_reader_get_uint32_be (reader, &_tagdata->count) ||
1555         !gst_byte_reader_get_data (reader, 4, &_tagdata->offset_as_data)) {
1556       return FALSE;
1557     }
1558     _tagdata->offset = GST_READ_UINT32_BE (_tagdata->offset_as_data);
1559   }
1560
1561   return TRUE;
1562 }
1563
1564 static gboolean
1565 parse_exif_ifd (GstExifReader * exif_reader, gint buf_offset,
1566     const GstExifTagMatch * tag_map)
1567 {
1568   GstByteReader reader;
1569   guint16 entries = 0;
1570   guint16 i;
1571
1572   g_return_val_if_fail (exif_reader->byte_order == G_LITTLE_ENDIAN
1573       || exif_reader->byte_order == G_BIG_ENDIAN, FALSE);
1574
1575   gst_byte_reader_init_from_buffer (&reader, exif_reader->buffer);
1576   if (!gst_byte_reader_set_pos (&reader, buf_offset)) {
1577     GST_WARNING ("Buffer offset invalid when parsing exif ifd");
1578     return FALSE;
1579   }
1580
1581   /* read the IFD entries number */
1582   if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
1583     if (!gst_byte_reader_get_uint16_le (&reader, &entries))
1584       goto read_error;
1585   } else {
1586     if (!gst_byte_reader_get_uint16_be (&reader, &entries))
1587       goto read_error;
1588   }
1589   GST_DEBUG ("Read number of entries: %u", entries);
1590
1591   /* iterate over the buffer and find the tags and stuff */
1592   for (i = 0; i < entries; i++) {
1593     GstExifTagData tagdata;
1594     gint map_index;
1595
1596     GST_LOG ("Reading entry: %u", i);
1597
1598     if (!parse_exif_tag_header (&reader, exif_reader->byte_order, &tagdata))
1599       goto read_error;
1600
1601     GST_DEBUG ("Parsed tag: id 0x%x, type %u, count %u, offset %u (0x%x)"
1602         ", buf size: %u", tagdata.tag, tagdata.tag_type, tagdata.count,
1603         tagdata.offset, tagdata.offset, gst_byte_reader_get_size (&reader));
1604
1605     map_index = exif_tag_map_find_reverse (tagdata.tag, tag_map, TRUE);
1606     if (map_index == -1) {
1607       GST_WARNING ("Unmapped exif tag: 0x%x", tagdata.tag);
1608       continue;
1609     }
1610
1611     /*
1612      * inner ifd tags handling, errors processing those are being ignored
1613      * and we try to continue the parsing
1614      */
1615     if (tagdata.tag == EXIF_GPS_IFD_TAG) {
1616       parse_exif_ifd (exif_reader,
1617           tagdata.offset - exif_reader->base_offset, tag_map_gps);
1618
1619       continue;
1620     }
1621     if (tagdata.tag == EXIF_IFD_TAG) {
1622       parse_exif_ifd (exif_reader,
1623           tagdata.offset - exif_reader->base_offset, tag_map_exif);
1624
1625       continue;
1626     }
1627     if (tagdata.tag == EXIF_VERSION_TAG ||
1628         tagdata.tag == EXIF_FLASHPIX_VERSION_TAG) {
1629       /* skip */
1630       continue;
1631     }
1632
1633     /* tags that need specialized deserialization */
1634     if (tag_map[map_index].deserialize) {
1635       i += tag_map[map_index].deserialize (exif_reader, &reader,
1636           &tag_map[map_index], &tagdata);
1637       continue;
1638     }
1639
1640     switch (tagdata.tag_type) {
1641       case EXIF_TYPE_ASCII:
1642         parse_exif_ascii_tag (exif_reader, &tag_map[map_index],
1643             tagdata.count, tagdata.offset, tagdata.offset_as_data);
1644         break;
1645       case EXIF_TYPE_RATIONAL:
1646         parse_exif_rational_tag (exif_reader, tag_map[map_index].gst_tag,
1647             tagdata.count, tagdata.offset, 1, FALSE);
1648         break;
1649       case EXIF_TYPE_SRATIONAL:
1650         parse_exif_rational_tag (exif_reader, tag_map[map_index].gst_tag,
1651             tagdata.count, tagdata.offset, 1, TRUE);
1652         break;
1653       case EXIF_TYPE_UNDEFINED:
1654         parse_exif_undefined_tag (exif_reader, &tag_map[map_index],
1655             tagdata.count, tagdata.offset, tagdata.offset_as_data);
1656         break;
1657       case EXIF_TYPE_LONG:
1658         parse_exif_long_tag (exif_reader, &tag_map[map_index],
1659             tagdata.count, tagdata.offset, tagdata.offset_as_data);
1660         break;
1661       default:
1662         GST_WARNING ("Unhandled tag type: %u", tagdata.tag_type);
1663         break;
1664     }
1665   }
1666
1667   /* check if the pending tags have something that can still be added */
1668   {
1669     GSList *walker;
1670     GstExifTagData *data;
1671
1672     for (walker = exif_reader->pending_tags; walker;
1673         walker = g_slist_next (walker)) {
1674       data = (GstExifTagData *) walker->data;
1675       switch (data->tag) {
1676         case EXIF_TAG_XRESOLUTION:
1677           parse_exif_rational_tag (exif_reader, GST_TAG_IMAGE_HORIZONTAL_PPI,
1678               data->count, data->offset, 1, FALSE);
1679           break;
1680         case EXIF_TAG_YRESOLUTION:
1681           parse_exif_rational_tag (exif_reader, GST_TAG_IMAGE_VERTICAL_PPI,
1682               data->count, data->offset, 1, FALSE);
1683           break;
1684         default:
1685           /* NOP */
1686           break;
1687       }
1688     }
1689   }
1690
1691   return TRUE;
1692
1693 read_error:
1694   {
1695     GST_WARNING ("Failed to parse the exif ifd");
1696     return FALSE;
1697   }
1698 }
1699
1700 /**
1701  * gst_tag_list_to_exif_buffer:
1702  * @taglist: The taglist
1703  * @byte_order: byte order used in writing (G_LITTLE_ENDIAN or G_BIG_ENDIAN)
1704  * @base_offset: Offset from the tiff header first byte
1705  *
1706  * Formats the tags in taglist on exif format. The resulting buffer contains
1707  * the tags IFD and is followed by the data pointed by the tag entries.
1708  *
1709  * Returns: A GstBuffer containing the tag entries followed by the tag data
1710  *
1711  * Since: 0.10.30
1712  */
1713 GstBuffer *
1714 gst_tag_list_to_exif_buffer (const GstTagList * taglist, gint byte_order,
1715     guint32 base_offset)
1716 {
1717   return write_exif_ifd (taglist, byte_order, base_offset, tag_map_ifd0);
1718 }
1719
1720 /**
1721  * gst_tag_list_to_exif_buffer_with_tiff_header:
1722  * @taglist: The taglist
1723  *
1724  * Formats the tags in taglist into exif structure, a tiff header
1725  * is put in the beginning of the buffer.
1726  *
1727  * Returns: A GstBuffer containing the data
1728  *
1729  * Since: 0.10.30
1730  */
1731 GstBuffer *
1732 gst_tag_list_to_exif_buffer_with_tiff_header (const GstTagList * taglist)
1733 {
1734   GstBuffer *ifd;
1735   GstByteWriter writer;
1736   guint size;
1737
1738   ifd = gst_tag_list_to_exif_buffer (taglist, G_BYTE_ORDER, 8);
1739   if (ifd == NULL) {
1740     GST_WARNING ("Failed to create exif buffer");
1741     return NULL;
1742   }
1743   size = TIFF_HEADER_SIZE + GST_BUFFER_SIZE (ifd);
1744
1745   /* TODO what is the correct endianness here? */
1746   gst_byte_writer_init_with_size (&writer, size, FALSE);
1747   /* TIFF header */
1748   if (G_BYTE_ORDER == G_LITTLE_ENDIAN) {
1749     gst_byte_writer_put_uint16_le (&writer, TIFF_LITTLE_ENDIAN);
1750     gst_byte_writer_put_uint16_le (&writer, 42);
1751     gst_byte_writer_put_uint32_le (&writer, 8);
1752   } else {
1753     gst_byte_writer_put_uint16_be (&writer, TIFF_BIG_ENDIAN);
1754     gst_byte_writer_put_uint16_be (&writer, 42);
1755     gst_byte_writer_put_uint32_be (&writer, 8);
1756   }
1757   if (!gst_byte_writer_put_data (&writer, GST_BUFFER_DATA (ifd),
1758           GST_BUFFER_SIZE (ifd))) {
1759     GST_WARNING ("Byte writer size mismatch");
1760     /* reaching here is a programming error because we should have a buffer
1761      * large enough */
1762     g_assert_not_reached ();
1763     gst_buffer_unref (ifd);
1764     gst_byte_writer_reset (&writer);
1765     return NULL;
1766   }
1767   gst_buffer_unref (ifd);
1768   return gst_byte_writer_reset_and_get_buffer (&writer);
1769 }
1770
1771 /**
1772  * gst_tag_list_from_exif_buffer:
1773  * @buffer: The exif buffer
1774  * @byte_order: byte order of the data
1775  * @base_offset: Offset from the tiff header to this buffer
1776  *
1777  * Parses the IFD and IFD tags data contained in the buffer and puts it
1778  * on a taglist. The base_offset is used to subtract from the offset in
1779  * the tag entries and be able to get the offset relative to the buffer
1780  * start
1781  *
1782  * Returns: The parsed taglist
1783  *
1784  * Since: 0.10.30
1785  */
1786 GstTagList *
1787 gst_tag_list_from_exif_buffer (const GstBuffer * buffer, gint byte_order,
1788     guint32 base_offset)
1789 {
1790   GstExifReader reader;
1791   g_return_val_if_fail (byte_order == G_LITTLE_ENDIAN
1792       || byte_order == G_BIG_ENDIAN, NULL);
1793
1794   gst_exif_reader_init (&reader, byte_order, buffer, base_offset);
1795
1796   if (!parse_exif_ifd (&reader, 0, tag_map_ifd0))
1797     goto read_error;
1798
1799   return gst_exif_reader_reset (&reader, TRUE);
1800
1801 read_error:
1802   {
1803     gst_exif_reader_reset (&reader, FALSE);
1804     GST_WARNING ("Failed to parse the exif buffer");
1805     return NULL;
1806   }
1807 }
1808
1809 /**
1810  * gst_tag_list_from_exif_buffer_with_tiff_header:
1811  * @buffer: The exif buffer
1812  *
1813  * Parses the exif tags starting with a tiff header structure.
1814  *
1815  * Returns: The taglist
1816  *
1817  * Since: 0.10.30
1818  */
1819 GstTagList *
1820 gst_tag_list_from_exif_buffer_with_tiff_header (const GstBuffer * buffer)
1821 {
1822   GstByteReader reader;
1823   guint16 fortytwo = 42;
1824   guint16 endianness = 0;
1825   guint32 offset;
1826   GstTagList *taglist = NULL;
1827   GstBuffer *subbuffer;
1828
1829   GST_LOG ("Parsing exif tags with tiff header of size %u",
1830       GST_BUFFER_SIZE (buffer));
1831
1832   gst_byte_reader_init_from_buffer (&reader, buffer);
1833
1834   GST_LOG ("Parsing the tiff header");
1835   if (!gst_byte_reader_get_uint16_be (&reader, &endianness)) {
1836     goto byte_reader_fail;
1837   }
1838
1839   if (endianness == TIFF_LITTLE_ENDIAN) {
1840     if (!gst_byte_reader_get_uint16_le (&reader, &fortytwo) ||
1841         !gst_byte_reader_get_uint32_le (&reader, &offset))
1842       goto byte_reader_fail;
1843   } else if (endianness == TIFF_BIG_ENDIAN) {
1844     if (!gst_byte_reader_get_uint16_be (&reader, &fortytwo) ||
1845         !gst_byte_reader_get_uint32_be (&reader, &offset))
1846       goto byte_reader_fail;
1847   } else {
1848     GST_WARNING ("Invalid endianness number %u", endianness);
1849     return NULL;
1850   }
1851
1852   if (fortytwo != 42) {
1853     GST_WARNING ("Invalid magic number %u, should be 42", fortytwo);
1854     return NULL;
1855   }
1856
1857   subbuffer = gst_buffer_new_and_alloc (GST_BUFFER_SIZE (buffer) -
1858       (TIFF_HEADER_SIZE - 2));
1859   memcpy (GST_BUFFER_DATA (subbuffer),
1860       GST_BUFFER_DATA (buffer) + TIFF_HEADER_SIZE,
1861       GST_BUFFER_SIZE (buffer) - TIFF_HEADER_SIZE);
1862
1863   taglist = gst_tag_list_from_exif_buffer (subbuffer,
1864       endianness == TIFF_LITTLE_ENDIAN ? G_LITTLE_ENDIAN : G_BIG_ENDIAN, 8);
1865
1866   gst_buffer_unref (subbuffer);
1867   return taglist;
1868
1869 byte_reader_fail:
1870   {
1871     GST_WARNING ("Failed to read values from buffer");
1872     return NULL;
1873   }
1874 }
1875
1876 /* special serialization functions */
1877 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (contrast,
1878     capturing_contrast);
1879 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (exposure_mode,
1880     capturing_exposure_mode);
1881 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (exposure_program,
1882     capturing_exposure_program);
1883 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (gain_control,
1884     capturing_gain_adjustment);
1885 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (metering_mode,
1886     capturing_metering_mode);
1887 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (orientation,
1888     image_orientation);
1889 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (saturation,
1890     capturing_saturation);
1891 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (scene_capture_type,
1892     capturing_scene_capture_type);
1893 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (sharpness,
1894     capturing_sharpness);
1895 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (source,
1896     capturing_source);
1897 EXIF_SERIALIZATION_DESERIALIZATION_MAP_STRING_TO_INT_FUNC (white_balance,
1898     capturing_white_balance);
1899
1900 static void
1901 serialize_geo_coordinate (GstExifWriter * writer, const GstTagList * taglist,
1902     const GstExifTagMatch * exiftag)
1903 {
1904   gboolean latitude;
1905   gdouble value;
1906   gint degrees;
1907   gint minutes;
1908   gint seconds;
1909   guint32 offset;
1910
1911   latitude = exiftag->exif_tag == EXIF_TAG_GPS_LATITUDE;        /* exif tag for latitude */
1912   if (!gst_tag_list_get_double (taglist, exiftag->gst_tag, &value)) {
1913     GST_WARNING ("Failed to get double from tag list for tag: %s",
1914         exiftag->gst_tag);
1915     return;
1916   }
1917
1918   /* first write the Latitude or Longitude Ref */
1919   if (latitude) {
1920     if (value >= 0) {
1921       write_exif_ascii_tag (writer, exiftag->complementary_tag, "N");
1922     } else {
1923       value *= -1;
1924       write_exif_ascii_tag (writer, exiftag->complementary_tag, "S");
1925     }
1926   } else {
1927     if (value >= 0) {
1928       write_exif_ascii_tag (writer, exiftag->complementary_tag, "E");
1929     } else {
1930       value *= -1;
1931       write_exif_ascii_tag (writer, exiftag->complementary_tag, "W");
1932     }
1933   }
1934
1935   /* now write the degrees stuff */
1936   GST_LOG ("Converting geo location %lf to degrees", value);
1937   degrees = (gint) value;
1938   value -= degrees;
1939   minutes = (gint) (value * 60);
1940   value = (value * 60) - minutes;
1941   seconds = (gint) (value * 60);
1942   GST_LOG ("Converted geo location to %d.%d'%d'' degrees", degrees,
1943       minutes, seconds);
1944
1945   offset = gst_byte_writer_get_size (&writer->datawriter);
1946   gst_exif_writer_write_tag_header (writer, exiftag->exif_tag,
1947       EXIF_TYPE_RATIONAL, 3, offset, NULL);
1948   gst_exif_writer_write_rational_data (writer, degrees, 1);
1949   gst_exif_writer_write_rational_data (writer, minutes, 1);
1950   gst_exif_writer_write_rational_data (writer, seconds, 1);
1951 }
1952
1953 static gint
1954 deserialize_geo_coordinate (GstExifReader * exif_reader,
1955     GstByteReader * reader, const GstExifTagMatch * exiftag,
1956     GstExifTagData * tagdata)
1957 {
1958   GstByteReader fractions_reader;
1959   gint multiplier;
1960   GstExifTagData next_tagdata;
1961   gint ret = 0;
1962   /* for the conversion */
1963   guint32 degrees_n = 0;
1964   guint32 degrees_d = 1;
1965   guint32 minutes_n = 0;
1966   guint32 minutes_d = 1;
1967   guint32 seconds_n = 0;
1968   guint32 seconds_d = 1;
1969   gdouble degrees;
1970   gdouble minutes;
1971   gdouble seconds;
1972
1973   GST_LOG ("Starting to parse %s tag in exif 0x%x", exiftag->gst_tag,
1974       exiftag->exif_tag);
1975
1976   if (exiftag->complementary_tag != tagdata->tag) {
1977     /* First should come the 'Ref' tags */
1978     GST_WARNING ("Tag %d is not the 'Ref' tag for latitude nor longitude",
1979         tagdata->tag);
1980     return ret;
1981   }
1982
1983   if (tagdata->offset_as_data[0] == 'N' || tagdata->offset_as_data[0] == 'E') {
1984     multiplier = 1;
1985   } else if (tagdata->offset_as_data[0] == 'S'
1986       || tagdata->offset_as_data[0] == 'W') {
1987     multiplier = -1;
1988   } else {
1989     GST_WARNING ("Invalid LatitudeRef or LongitudeRef %c",
1990         tagdata->offset_as_data[0]);
1991     return ret;
1992   }
1993
1994   /* now read the following tag that must be the latitude or longitude */
1995   if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
1996     if (!gst_byte_reader_peek_uint16_le (reader, &next_tagdata.tag))
1997       goto reader_fail;
1998   } else {
1999     if (!gst_byte_reader_peek_uint16_be (reader, &next_tagdata.tag))
2000       goto reader_fail;
2001   }
2002
2003   if (exiftag->exif_tag != next_tagdata.tag) {
2004     GST_WARNING ("This is not a geo coordinate tag");
2005     return ret;
2006   }
2007
2008   /* read the remaining tag entry data */
2009   if (!parse_exif_tag_header (reader, exif_reader->byte_order, &next_tagdata)) {
2010     ret = -1;
2011     goto reader_fail;
2012   }
2013
2014   ret = 1;
2015
2016   /* some checking */
2017   if (next_tagdata.tag_type != EXIF_TYPE_RATIONAL) {
2018     GST_WARNING ("Invalid type %d for geo coordinate (latitude/longitude)",
2019         next_tagdata.tag_type);
2020     return ret;
2021   }
2022   if (next_tagdata.count != 3) {
2023     GST_WARNING ("Geo coordinate should use 3 fractions, we have %u",
2024         next_tagdata.count);
2025     return ret;
2026   }
2027
2028   /* now parse the fractions */
2029   gst_byte_reader_init_from_buffer (&fractions_reader, exif_reader->buffer);
2030   if (!gst_byte_reader_set_pos (&fractions_reader,
2031           next_tagdata.offset - exif_reader->base_offset))
2032     goto reader_fail;
2033
2034   if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
2035     if (!gst_byte_reader_get_uint32_le (&fractions_reader, &degrees_n) ||
2036         !gst_byte_reader_get_uint32_le (&fractions_reader, &degrees_d) ||
2037         !gst_byte_reader_get_uint32_le (&fractions_reader, &minutes_n) ||
2038         !gst_byte_reader_get_uint32_le (&fractions_reader, &minutes_d) ||
2039         !gst_byte_reader_get_uint32_le (&fractions_reader, &seconds_n) ||
2040         !gst_byte_reader_get_uint32_le (&fractions_reader, &seconds_d))
2041       goto reader_fail;
2042   } else {
2043     if (!gst_byte_reader_get_uint32_be (&fractions_reader, &degrees_n) ||
2044         !gst_byte_reader_get_uint32_be (&fractions_reader, &degrees_d) ||
2045         !gst_byte_reader_get_uint32_be (&fractions_reader, &minutes_n) ||
2046         !gst_byte_reader_get_uint32_be (&fractions_reader, &minutes_d) ||
2047         !gst_byte_reader_get_uint32_be (&fractions_reader, &seconds_n) ||
2048         !gst_byte_reader_get_uint32_be (&fractions_reader, &seconds_d))
2049       goto reader_fail;
2050   }
2051
2052   GST_DEBUG ("Read degrees fraction for tag %s: %u/%u %u/%u %u/%u",
2053       exiftag->gst_tag, degrees_n, degrees_d, minutes_n, minutes_d,
2054       seconds_n, seconds_d);
2055
2056   gst_util_fraction_to_double (degrees_n, degrees_d, &degrees);
2057   gst_util_fraction_to_double (minutes_n, minutes_d, &minutes);
2058   gst_util_fraction_to_double (seconds_n, seconds_d, &seconds);
2059
2060   minutes += seconds / 60;
2061   degrees += minutes / 60;
2062   degrees *= multiplier;
2063
2064   GST_DEBUG ("Adding %s tag: %lf", exiftag->gst_tag, degrees);
2065   gst_tag_list_add (exif_reader->taglist, GST_TAG_MERGE_REPLACE,
2066       exiftag->gst_tag, degrees, NULL);
2067
2068   return ret;
2069
2070 reader_fail:
2071   GST_WARNING ("Failed to read fields from buffer (too short?)");
2072   return ret;
2073 }
2074
2075
2076 static void
2077 serialize_geo_direction (GstExifWriter * writer, const GstTagList * taglist,
2078     const GstExifTagMatch * exiftag)
2079 {
2080   gdouble value;
2081
2082   if (!gst_tag_list_get_double (taglist, exiftag->gst_tag, &value)) {
2083     GST_WARNING ("Failed to get double from tag list for tag: %s",
2084         exiftag->gst_tag);
2085     return;
2086   }
2087
2088   /* first write the direction ref */
2089   write_exif_ascii_tag (writer, exiftag->complementary_tag, "T");
2090   gst_exif_writer_write_rational_tag_from_double (writer,
2091       exiftag->exif_tag, value);
2092 }
2093
2094 static gint
2095 deserialize_geo_direction (GstExifReader * exif_reader,
2096     GstByteReader * reader, const GstExifTagMatch * exiftag,
2097     GstExifTagData * tagdata)
2098 {
2099   GstExifTagData next_tagdata = { 0, };
2100   gint ret = 0;
2101
2102   GST_LOG ("Starting to parse %s tag in exif 0x%x", exiftag->gst_tag,
2103       exiftag->exif_tag);
2104
2105   if (exiftag->complementary_tag == tagdata->tag) {
2106     /* First should come the 'Ref' tags */
2107     if (tagdata->offset_as_data[0] == 'M') {
2108       GST_WARNING ("Magnetic direction is not supported");
2109       return ret;
2110     } else if (tagdata->offset_as_data[0] == 'T') {
2111       /* nop */
2112     } else {
2113       GST_WARNING ("Invalid Ref for direction or track %c",
2114           tagdata->offset_as_data[0]);
2115       return ret;
2116     }
2117   } else {
2118     GST_DEBUG ("No Direction Ref, using default=T");
2119     if (tagdata->tag == exiftag->exif_tag) {
2120       /* this is the main tag */
2121       tagdata_copy (&next_tagdata, tagdata);
2122     }
2123   }
2124
2125   if (next_tagdata.tag == 0) {
2126     /* now read the following tag that must be the exif_tag */
2127     if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
2128       if (!gst_byte_reader_peek_uint16_le (reader, &next_tagdata.tag))
2129         goto reader_fail;
2130     } else {
2131       if (!gst_byte_reader_peek_uint16_be (reader, &next_tagdata.tag))
2132         goto reader_fail;
2133     }
2134
2135     if (exiftag->exif_tag != next_tagdata.tag) {
2136       GST_WARNING ("Unexpected tag");
2137       return ret;
2138     }
2139
2140     /* read the remaining tag entry data */
2141     if (!parse_exif_tag_header (reader, exif_reader->byte_order, &next_tagdata)) {
2142       ret = -1;
2143       goto reader_fail;
2144     }
2145     ret = 1;
2146   }
2147
2148   /* some checking */
2149   if (next_tagdata.tag_type != EXIF_TYPE_RATIONAL) {
2150     GST_WARNING ("Invalid type %d for 0x%x", next_tagdata.tag_type,
2151         next_tagdata.tag);
2152     return ret;
2153   }
2154   if (next_tagdata.count != 1) {
2155     GST_WARNING ("0x%x tag must have a single fraction, we have %u",
2156         next_tagdata.tag_type, next_tagdata.count);
2157     return ret;
2158   }
2159
2160   parse_exif_rational_tag (exif_reader,
2161       exiftag->gst_tag, next_tagdata.count, next_tagdata.offset, 1, FALSE);
2162
2163   return ret;
2164
2165 reader_fail:
2166   GST_WARNING ("Failed to read fields from buffer (too short?)");
2167   return ret;
2168 }
2169
2170
2171 static void
2172 serialize_geo_elevation (GstExifWriter * writer, const GstTagList * taglist,
2173     const GstExifTagMatch * exiftag)
2174 {
2175   gdouble value;
2176
2177   if (!gst_tag_list_get_double (taglist, exiftag->gst_tag, &value)) {
2178     GST_WARNING ("Failed to get double from tag list for tag: %s",
2179         exiftag->gst_tag);
2180     return;
2181   }
2182
2183   /* first write the Ref */
2184   gst_exif_writer_write_byte_tag (writer,
2185       exiftag->complementary_tag, value >= 0 ? 0 : 1);
2186
2187   if (value < 0)
2188     value *= -1;
2189
2190   /* now the value */
2191   gst_exif_writer_write_rational_tag_from_double (writer,
2192       exiftag->exif_tag, value);
2193 }
2194
2195 static gint
2196 deserialize_geo_elevation (GstExifReader * exif_reader,
2197     GstByteReader * reader, const GstExifTagMatch * exiftag,
2198     GstExifTagData * tagdata)
2199 {
2200   GstExifTagData next_tagdata = { 0, };
2201   gint multiplier = 1;
2202   gint ret = 0;
2203
2204   GST_LOG ("Starting to parse %s tag in exif 0x%x", exiftag->gst_tag,
2205       exiftag->exif_tag);
2206
2207   if (exiftag->complementary_tag == tagdata->tag) {
2208     if (tagdata->offset_as_data[0] == 0) {
2209       /* NOP */
2210     } else if (tagdata->offset_as_data[0] == 1) {
2211       multiplier = -1;
2212     } else {
2213       GST_WARNING ("Invalid GPSAltitudeRef %u", tagdata->offset_as_data[0]);
2214       return ret;
2215     }
2216   } else {
2217     GST_DEBUG ("No GPSAltitudeRef, using default=0");
2218     if (tagdata->tag == exiftag->exif_tag) {
2219       tagdata_copy (&next_tagdata, tagdata);
2220     }
2221   }
2222
2223   /* now read the following tag that must be the exif_tag */
2224   if (next_tagdata.tag == 0) {
2225     if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
2226       if (!gst_byte_reader_peek_uint16_le (reader, &next_tagdata.tag))
2227         goto reader_fail;
2228     } else {
2229       if (!gst_byte_reader_peek_uint16_be (reader, &next_tagdata.tag))
2230         goto reader_fail;
2231     }
2232
2233     if (exiftag->exif_tag != next_tagdata.tag) {
2234       GST_WARNING ("Unexpected tag");
2235       return ret;
2236     }
2237
2238     /* read the remaining tag entry data */
2239     if (!parse_exif_tag_header (reader, exif_reader->byte_order, &next_tagdata)) {
2240       ret = -1;
2241       goto reader_fail;
2242     }
2243     ret = 1;
2244   }
2245
2246   /* some checking */
2247   if (next_tagdata.tag_type != EXIF_TYPE_RATIONAL) {
2248     GST_WARNING ("Invalid type %d for 0x%x", next_tagdata.tag_type,
2249         next_tagdata.tag);
2250     return ret;
2251   }
2252   if (next_tagdata.count != 1) {
2253     GST_WARNING ("0x%x tag must have a single fraction, we have %u",
2254         next_tagdata.tag_type, next_tagdata.count);
2255     return ret;
2256   }
2257
2258   parse_exif_rational_tag (exif_reader,
2259       exiftag->gst_tag, next_tagdata.count, next_tagdata.offset, multiplier,
2260       FALSE);
2261
2262   return ret;
2263
2264 reader_fail:
2265   GST_WARNING ("Failed to read fields from buffer (too short?)");
2266   return ret;
2267 }
2268
2269
2270 static void
2271 serialize_speed (GstExifWriter * writer, const GstTagList * taglist,
2272     const GstExifTagMatch * exiftag)
2273 {
2274   gdouble value;
2275
2276   if (!gst_tag_list_get_double (taglist, exiftag->gst_tag, &value)) {
2277     GST_WARNING ("Failed to get double from tag list for tag: %s",
2278         exiftag->gst_tag);
2279     return;
2280   }
2281
2282   /* first write the Ref */
2283   write_exif_ascii_tag (writer, exiftag->complementary_tag, "K");
2284
2285   /* now the value */
2286   gst_exif_writer_write_rational_tag_from_double (writer,
2287       exiftag->exif_tag, value * METERS_PER_SECOND_TO_KILOMETERS_PER_HOUR);
2288 }
2289
2290 static gint
2291 deserialize_speed (GstExifReader * exif_reader,
2292     GstByteReader * reader, const GstExifTagMatch * exiftag,
2293     GstExifTagData * tagdata)
2294 {
2295   GstExifTagData next_tagdata = { 0, };
2296   gdouble multiplier = 1;
2297   gint ret = 0;
2298
2299   GST_LOG ("Starting to parse %s tag in exif 0x%x", exiftag->gst_tag,
2300       exiftag->exif_tag);
2301
2302   if (exiftag->complementary_tag == tagdata->tag) {
2303     if (tagdata->offset_as_data[0] == 'K') {
2304       multiplier = KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND;
2305     } else if (tagdata->offset_as_data[0] == 'M') {
2306       multiplier = MILES_PER_HOUR_TO_METERS_PER_SECOND;
2307     } else if (tagdata->offset_as_data[0] == 'N') {
2308       multiplier = KNOTS_TO_METERS_PER_SECOND;
2309     } else {
2310       GST_WARNING ("Invalid GPSSpeedRed %c", tagdata->offset_as_data[0]);
2311       return ret;
2312     }
2313   } else {
2314     GST_DEBUG ("No GPSSpeedRef, using default=K");
2315     multiplier = KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND;
2316
2317     if (tagdata->tag == exiftag->exif_tag) {
2318       tagdata_copy (&next_tagdata, tagdata);
2319     }
2320   }
2321
2322   /* now read the following tag that must be the exif_tag */
2323   if (next_tagdata.tag == 0) {
2324     if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
2325       if (!gst_byte_reader_peek_uint16_le (reader, &next_tagdata.tag))
2326         goto reader_fail;
2327     } else {
2328       if (!gst_byte_reader_peek_uint16_be (reader, &next_tagdata.tag))
2329         goto reader_fail;
2330     }
2331
2332     if (exiftag->exif_tag != next_tagdata.tag) {
2333       GST_WARNING ("Unexpected tag");
2334       return ret;
2335     }
2336
2337     /* read the remaining tag entry data */
2338     if (!parse_exif_tag_header (reader, exif_reader->byte_order, &next_tagdata)) {
2339       ret = -1;
2340       goto reader_fail;
2341     }
2342     ret = 1;
2343   }
2344
2345
2346   /* some checking */
2347   if (next_tagdata.tag_type != EXIF_TYPE_RATIONAL) {
2348     GST_WARNING ("Invalid type %d for 0x%x", next_tagdata.tag_type,
2349         next_tagdata.tag);
2350     return ret;
2351   }
2352   if (next_tagdata.count != 1) {
2353     GST_WARNING ("0x%x tag must have a single fraction, we have %u",
2354         next_tagdata.tag_type, next_tagdata.count);
2355     return ret;
2356   }
2357
2358   parse_exif_rational_tag (exif_reader,
2359       exiftag->gst_tag, next_tagdata.count, next_tagdata.offset, multiplier,
2360       FALSE);
2361
2362   return ret;
2363
2364 reader_fail:
2365   GST_WARNING ("Failed to read fields from buffer (too short?)");
2366   return ret;
2367 }
2368
2369 static void
2370 serialize_shutter_speed (GstExifWriter * writer, const GstTagList * taglist,
2371     const GstExifTagMatch * exiftag)
2372 {
2373   const GValue *value = NULL;
2374   gdouble num;
2375
2376   value = gst_tag_list_get_value_index (taglist, exiftag->gst_tag, 0);
2377   if (!value) {
2378     GST_WARNING ("Failed to get shutter speed from from tag list");
2379     return;
2380   }
2381   gst_util_fraction_to_double (gst_value_get_fraction_numerator (value),
2382       gst_value_get_fraction_denominator (value), &num);
2383
2384 #ifdef HAVE_LOG2
2385   num = -log2 (num);
2386 #else
2387   num = -log (num) / M_LN2;
2388 #endif
2389
2390   /* now the value */
2391   gst_exif_writer_write_signed_rational_tag_from_double (writer,
2392       exiftag->exif_tag, num);
2393 }
2394
2395 static gint
2396 deserialize_shutter_speed (GstExifReader * exif_reader,
2397     GstByteReader * reader, const GstExifTagMatch * exiftag,
2398     GstExifTagData * tagdata)
2399 {
2400   gint32 frac_n, frac_d;
2401   gdouble d;
2402   GValue value = { 0 };
2403
2404   GST_LOG ("Starting to parse %s tag in exif 0x%x", exiftag->gst_tag,
2405       exiftag->exif_tag);
2406
2407   if (!exif_reader_read_rational_tag (exif_reader, tagdata->count,
2408           tagdata->offset, TRUE, &frac_n, &frac_d))
2409     return 0;
2410
2411   gst_util_fraction_to_double (frac_n, frac_d, &d);
2412   d = pow (2, -d);
2413   gst_util_double_to_fraction (d, &frac_n, &frac_d);
2414
2415   g_value_init (&value, GST_TYPE_FRACTION);
2416   gst_value_set_fraction (&value, frac_n, frac_d);
2417   gst_tag_list_add_value (exif_reader->taglist, GST_TAG_MERGE_KEEP,
2418       exiftag->gst_tag, &value);
2419   g_value_unset (&value);
2420
2421   return 0;
2422 }
2423
2424 static void
2425 serialize_aperture_value (GstExifWriter * writer, const GstTagList * taglist,
2426     const GstExifTagMatch * exiftag)
2427 {
2428   gdouble num;
2429
2430   if (!gst_tag_list_get_double_index (taglist, exiftag->gst_tag, 0, &num)) {
2431     GST_WARNING ("Failed to get focal ratio from from tag list");
2432     return;
2433   }
2434 #ifdef HAVE_LOG2
2435   num = 2 * log2 (num);
2436 #else
2437   num = 2 * (log (num) / M_LN2);
2438 #endif
2439
2440   /* now the value */
2441   gst_exif_writer_write_rational_tag_from_double (writer,
2442       exiftag->exif_tag, num);
2443 }
2444
2445 static gint
2446 deserialize_aperture_value (GstExifReader * exif_reader,
2447     GstByteReader * reader, const GstExifTagMatch * exiftag,
2448     GstExifTagData * tagdata)
2449 {
2450   gint32 frac_n, frac_d;
2451   gdouble d;
2452
2453   GST_LOG ("Starting to parse %s tag in exif 0x%x", exiftag->gst_tag,
2454       exiftag->exif_tag);
2455
2456   if (!exif_reader_read_rational_tag (exif_reader, tagdata->count,
2457           tagdata->offset, FALSE, &frac_n, &frac_d))
2458     return 0;
2459
2460   gst_util_fraction_to_double (frac_n, frac_d, &d);
2461   d = pow (2, d / 2);
2462
2463   gst_tag_list_add (exif_reader->taglist, GST_TAG_MERGE_KEEP,
2464       exiftag->gst_tag, d, NULL);
2465
2466   return 0;
2467 }
2468
2469 static void
2470 serialize_sensitivity_type (GstExifWriter * writer, const GstTagList * taglist,
2471     const GstExifTagMatch * exiftag)
2472 {
2473   /* we only support ISOSpeed as the sensitivity type (3) */
2474   gst_exif_writer_write_short_tag (writer, exiftag->exif_tag, 3);
2475 }
2476
2477 static gint
2478 deserialize_sensitivity_type (GstExifReader * exif_reader,
2479     GstByteReader * reader, const GstExifTagMatch * exiftag,
2480     GstExifTagData * tagdata)
2481 {
2482   GstExifTagData *sensitivity = NULL;
2483   guint16 type_data;
2484
2485   if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
2486     type_data = GST_READ_UINT16_LE (tagdata->offset_as_data);
2487   } else {
2488     type_data = GST_READ_UINT16_BE (tagdata->offset_as_data);
2489   }
2490
2491   if (type_data != 3) {
2492     GST_WARNING ("We only support SensitivityType=3");
2493     return 0;
2494   }
2495
2496   /* check the pending tags for the PhotographicSensitivity tag */
2497   sensitivity =
2498       gst_exif_reader_get_pending_tag (exif_reader,
2499       EXIF_TAG_PHOTOGRAPHIC_SENSITIVITY);
2500   if (sensitivity == NULL) {
2501     GST_WARNING ("PhotographicSensitivity tag not found");
2502     return 0;
2503   }
2504
2505   GST_LOG ("Starting to parse %s tag in exif 0x%x", exiftag->gst_tag,
2506       exiftag->exif_tag);
2507
2508   gst_tag_list_add (exif_reader->taglist, GST_TAG_MERGE_KEEP,
2509       GST_TAG_CAPTURING_ISO_SPEED, sensitivity->offset_as_data, NULL);
2510
2511   return 0;
2512 }
2513
2514 static void
2515 serialize_flash (GstExifWriter * writer, const GstTagList * taglist,
2516     const GstExifTagMatch * exiftag)
2517 {
2518   gboolean flash_fired;
2519   const gchar *flash_mode;
2520   guint16 tagvalue = 0;
2521
2522   if (!gst_tag_list_get_boolean_index (taglist, exiftag->gst_tag, 0,
2523           &flash_fired)) {
2524     GST_WARNING ("Failed to get flash fired from from tag list");
2525     return;
2526   }
2527
2528   if (flash_fired)
2529     tagvalue = 1;
2530
2531   if (gst_tag_list_peek_string_index (taglist, GST_TAG_CAPTURING_FLASH_MODE, 0,
2532           &flash_mode)) {
2533     guint16 mode = 0;
2534     if (strcmp (flash_mode, "auto") == 0) {
2535       mode = 3;
2536     } else if (strcmp (flash_mode, "always") == 0) {
2537       mode = 1;
2538     } else if (strcmp (flash_mode, "never") == 0) {
2539       mode = 2;
2540     }
2541
2542     tagvalue = tagvalue | (mode << 3);
2543   } else {
2544     GST_DEBUG ("flash-mode not available");
2545   }
2546
2547   gst_exif_writer_write_short_tag (writer, exiftag->exif_tag, tagvalue);
2548 }
2549
2550 static gint
2551 deserialize_flash (GstExifReader * exif_reader,
2552     GstByteReader * reader, const GstExifTagMatch * exiftag,
2553     GstExifTagData * tagdata)
2554 {
2555   guint16 value = 0;
2556   guint mode = 0;
2557   const gchar *mode_str = NULL;
2558
2559   GST_LOG ("Starting to parse %s tag in exif 0x%x", exiftag->gst_tag,
2560       exiftag->exif_tag);
2561
2562   if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
2563     value = GST_READ_UINT16_LE (tagdata->offset_as_data);
2564   } else {
2565     value = GST_READ_UINT16_BE (tagdata->offset_as_data);
2566   }
2567
2568   /* check flash fired */
2569   if (value & 0x1) {
2570     gst_tag_list_add (exif_reader->taglist, GST_TAG_MERGE_REPLACE,
2571         GST_TAG_CAPTURING_FLASH_FIRED, TRUE, NULL);
2572   } else {
2573     gst_tag_list_add (exif_reader->taglist, GST_TAG_MERGE_REPLACE,
2574         GST_TAG_CAPTURING_FLASH_FIRED, FALSE, NULL);
2575   }
2576
2577   mode = (value >> 3) & 0x3;
2578   if (mode == 1) {
2579     mode_str = "always";
2580   } else if (mode == 2) {
2581     mode_str = "never";
2582   } else if (mode == 3) {
2583     mode_str = "auto";
2584   }
2585
2586   if (mode_str)
2587     gst_tag_list_add (exif_reader->taglist, GST_TAG_MERGE_REPLACE,
2588         GST_TAG_CAPTURING_FLASH_MODE, mode_str, NULL);
2589
2590   return 0;
2591 }
2592
2593 static gint
2594 deserialize_resolution (GstExifReader * exif_reader,
2595     GstByteReader * reader, const GstExifTagMatch * exiftag,
2596     GstExifTagData * tagdata)
2597 {
2598   GstExifTagData *xres = NULL;
2599   GstExifTagData *yres = NULL;
2600   guint16 unit;
2601   gdouble multiplier;
2602
2603   if (exif_reader->byte_order == G_LITTLE_ENDIAN) {
2604     unit = GST_READ_UINT16_LE (tagdata->offset_as_data);
2605   } else {
2606     unit = GST_READ_UINT16_BE (tagdata->offset_as_data);
2607   }
2608
2609   switch (unit) {
2610     case 2:                    /* inch */
2611       multiplier = 1;
2612       break;
2613     case 3:                    /* cm */
2614       multiplier = 1 / 2.54;
2615       break;
2616     default:
2617       GST_WARNING ("Invalid resolution unit, ignoring PPI tags");
2618       return 0;
2619   }
2620
2621   xres = gst_exif_reader_get_pending_tag (exif_reader, EXIF_TAG_XRESOLUTION);
2622   if (xres) {
2623     parse_exif_rational_tag (exif_reader, GST_TAG_IMAGE_HORIZONTAL_PPI,
2624         xres->count, xres->offset, multiplier, FALSE);
2625   }
2626   yres = gst_exif_reader_get_pending_tag (exif_reader, EXIF_TAG_YRESOLUTION);
2627   if (yres) {
2628     parse_exif_rational_tag (exif_reader, GST_TAG_IMAGE_VERTICAL_PPI,
2629         yres->count, yres->offset, multiplier, FALSE);
2630   }
2631
2632   return 0;
2633 }
2634
2635 static void
2636 serialize_scene_type (GstExifWriter * writer, const GstTagList * taglist,
2637     const GstExifTagMatch * exiftag)
2638 {
2639   const gchar *str;
2640   guint8 value = 0;
2641
2642   if (gst_tag_list_peek_string_index (taglist, GST_TAG_CAPTURING_SOURCE, 0,
2643           &str)) {
2644     if (strcmp (str, "dsc") == 0) {
2645       value = 1;
2646     }
2647   }
2648
2649   if (value != 0)
2650     write_exif_undefined_tag (writer, exiftag->exif_tag, &value, 1);
2651 }
2652
2653 static gint
2654 deserialize_scene_type (GstExifReader * exif_reader,
2655     GstByteReader * reader, const GstExifTagMatch * exiftag,
2656     GstExifTagData * tagdata)
2657 {
2658   guint8 value = 0;
2659
2660   GST_LOG ("Starting to parse %s tag in exif 0x%x", exiftag->gst_tag,
2661       exiftag->exif_tag);
2662
2663   value = GST_READ_UINT8 (tagdata->offset_as_data);
2664
2665   if (value == 1) {
2666     gst_tag_list_add (exif_reader->taglist, GST_TAG_MERGE_KEEP,
2667         GST_TAG_CAPTURING_SOURCE, "dsc", NULL);
2668   }
2669
2670   return 0;
2671 }
2672
2673 static gint
2674 deserialize_add_to_pending_tags (GstExifReader * exif_reader,
2675     GstByteReader * reader, const GstExifTagMatch * exiftag,
2676     GstExifTagData * tagdata)
2677 {
2678   GST_LOG ("Adding %s tag in exif 0x%x to pending tags", exiftag->gst_tag,
2679       exiftag->exif_tag);
2680
2681   /* add it to the pending tags, as we can only parse it when we find the
2682    * SensitivityType tag */
2683   gst_exif_reader_add_pending_tag (exif_reader, tagdata);
2684   return 0;
2685 }
2686
2687 #undef EXIF_SERIALIZATION_FUNC
2688 #undef EXIF_DESERIALIZATION_FUNC
2689 #undef EXIF_SERIALIZATION_DESERIALIZATION_FUNC