1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "CameraExifUtils"
18 #define ATRACE_TAG ATRACE_TAG_CAMERA
19 //#define LOG_NDEBUG 0
20 
21 #include "ExifUtils.h"
22 
23 #include <inttypes.h>
24 #include <log/log.h>
25 #include <math.h>
26 #include <stdint.h>
27 
28 #include <string>
29 #include <vector>
30 
31 #include "../EmulatedSensor.h"
32 
33 extern "C" {
34 #include <libexif/exif-data.h>
35 }
36 
37 namespace std {
38 
39 template <>
40 struct default_delete<ExifEntry> {
operator ()std::default_delete41   inline void operator()(ExifEntry* entry) const {
42     exif_entry_unref(entry);
43   }
44 };
45 
46 }  // namespace std
47 
48 namespace android {
49 
50 class ExifUtilsImpl : public ExifUtils {
51  public:
52   ExifUtilsImpl(SensorCharacteristics sensor_chars);
53 
54   virtual ~ExifUtilsImpl();
55 
56   // Initialize() can be called multiple times. The setting of Exif tags will be
57   // cleared.
58   virtual bool Initialize();
59 
60   // set all known fields from a metadata structure
61   virtual bool SetFromMetadata(const HalCameraMetadata& metadata,
62                                size_t image_width, size_t image_height);
63 
64   // sets the len aperture.
65   // Returns false if memory allocation fails.
66   virtual bool SetAperture(float aperture);
67 
68   // sets the color space.
69   // Returns false if memory allocation fails.
70   virtual bool SetColorSpace(uint16_t color_space);
71 
72   // sets the date and time of image last modified. It takes local time. The
73   // name of the tag is DateTime in IFD0.
74   // Returns false if memory allocation fails.
75   virtual bool SetDateTime(const struct tm& t);
76 
77   // sets the digital zoom ratio. If the numerator is 0, it means digital zoom
78   // was not used.
79   // Returns false if memory allocation fails.
80   virtual bool SetDigitalZoomRatio(uint32_t crop_width, uint32_t crop_height,
81                                    uint32_t sensor_width,
82                                    uint32_t sensor_height);
83 
84   // Sets the exposure bias.
85   // Returns false if memory allocation fails.
86   virtual bool SetExposureBias(int32_t ev, uint32_t ev_step_numerator,
87                                uint32_t ev_step_denominator);
88 
89   // sets the exposure mode set when the image was shot.
90   // Returns false if memory allocation fails.
91   virtual bool SetExposureMode(uint8_t exposure_mode);
92 
93   // sets the exposure time, given in seconds.
94   // Returns false if memory allocation fails.
95   virtual bool SetExposureTime(float exposure_time);
96 
97   // sets the status of flash.
98   // Returns false if memory allocation fails.
99   virtual bool SetFlash(uint8_t flash_available, uint8_t flash_state,
100                         uint8_t ae_mode);
101 
102   // sets the F number.
103   // Returns false if memory allocation fails.
104   virtual bool SetFNumber(float f_number);
105 
106   // sets the focal length of lens used to take the image in millimeters.
107   // Returns false if memory allocation fails.
108   virtual bool SetFocalLength(float focal_length);
109 
110   // sets the focal length of lens for 35mm film used to take the image in
111   // millimeters. Returns false if memory allocation fails.
112   virtual bool SetFocalLengthIn35mmFilm(float focal_length, float sensor_size_x,
113                                         float sensor_size_y);
114 
115   // sets make & model
116   virtual bool SetMake(const std::string& make);
117   virtual bool SetModel(const std::string& model);
118 
119   // sets the altitude in meters.
120   // Returns false if memory allocation fails.
121   virtual bool SetGpsAltitude(double altitude);
122 
123   // sets the latitude with degrees minutes seconds format.
124   // Returns false if memory allocation fails.
125   virtual bool SetGpsLatitude(double latitude);
126 
127   // sets the longitude with degrees minutes seconds format.
128   // Returns false if memory allocation fails.
129   virtual bool SetGpsLongitude(double longitude);
130 
131   // sets GPS processing method.
132   // Returns false if memory allocation fails.
133   virtual bool SetGpsProcessingMethod(const std::string& method);
134 
135   // sets GPS date stamp and time stamp (atomic clock). It takes UTC time.
136   // Returns false if memory allocation fails.
137   virtual bool SetGpsTimestamp(const struct tm& t);
138 
139   // sets the length (number of rows) of main image.
140   // Returns false if memory allocation fails.
141   virtual bool SetImageHeight(uint32_t length);
142 
143   // sets the width (number of columes) of main image.
144   // Returns false if memory allocation fails.
145   virtual bool SetImageWidth(uint32_t width);
146 
147   // sets the ISO speed.
148   // Returns false if memory allocation fails.
149   virtual bool SetIsoSpeedRating(uint16_t iso_speed_ratings);
150 
151   // sets the smallest F number of the lens.
152   // Returns false if memory allocation fails.
153   virtual bool SetMaxAperture(float aperture);
154 
155   // sets image orientation.
156   // Returns false if memory allocation fails.
157   virtual bool SetOrientation(uint16_t degrees);
158 
159   // sets image orientation.
160   // Returns false if memory allocation fails.
161   virtual bool SetOrientationValue(ExifOrientation orientation_value);
162 
163   // sets the shutter speed.
164   // Returns false if memory allocation fails.
165   virtual bool SetShutterSpeed(float exposure_time);
166 
167   // sets the distance to the subject, given in meters.
168   // Returns false if memory allocation fails.
169   virtual bool SetSubjectDistance(float diopters);
170 
171   // sets the fractions of seconds for the <DateTime> tag.
172   // Returns false if memory allocation fails.
173   virtual bool SetSubsecTime(const std::string& subsec_time);
174 
175   // sets the white balance mode set when the image was shot.
176   // Returns false if memory allocation fails.
177   virtual bool SetWhiteBalance(uint8_t white_balance);
178 
179   // Generates APP1 segment.
180   // Returns false if generating APP1 segment fails.
181   virtual bool GenerateApp1(unsigned char* thumbnail_buffer, uint32_t size);
182 
183   // Gets buffer of APP1 segment. This method must be called only after calling
184   // GenerateAPP1().
185   virtual const uint8_t* GetApp1Buffer();
186 
187   // Gets length of APP1 segment. This method must be called only after calling
188   // GenerateAPP1().
189   virtual unsigned int GetApp1Length();
190 
191  protected:
192   // sets the version of this standard supported.
193   // Returns false if memory allocation fails.
194   virtual bool SetExifVersion(const std::string& exif_version);
195 
196   // Resets the pointers and memories.
197   virtual void Reset();
198 
199   // Adds a variable length tag to |exif_data_|. It will remove the original one
200   // if the tag exists.
201   // Returns the entry of the tag. The reference count of returned ExifEntry is
202   // two.
203   virtual std::unique_ptr<ExifEntry> AddVariableLengthEntry(ExifIfd ifd,
204                                                             ExifTag tag,
205                                                             ExifFormat format,
206                                                             uint64_t components,
207                                                             unsigned int size);
208 
209   // Adds a entry of |tag| in |exif_data_|. It won't remove the original one if
210   // the tag exists.
211   // Returns the entry of the tag. It adds one reference count to returned
212   // ExifEntry.
213   virtual std::unique_ptr<ExifEntry> AddEntry(ExifIfd ifd, ExifTag tag);
214 
215   // Helpe functions to add exif data with different types.
216   virtual bool SetShort(ExifIfd ifd, ExifTag tag, uint16_t value,
217                         const std::string& msg);
218 
219   virtual bool SetLong(ExifIfd ifd, ExifTag tag, uint32_t value,
220                        const std::string& msg);
221 
222   virtual bool SetRational(ExifIfd ifd, ExifTag tag, uint32_t numerator,
223                            uint32_t denominator, const std::string& msg);
224 
225   virtual bool SetSRational(ExifIfd ifd, ExifTag tag, int32_t numerator,
226                             int32_t denominator, const std::string& msg);
227 
228   virtual bool SetString(ExifIfd ifd, ExifTag tag, ExifFormat format,
229                          const std::string& buffer, const std::string& msg);
230 
ConvertToApex(float val)231   float ConvertToApex(float val) {
232     return 2.0f * log2f(val);
233   }
234 
235   // Destroys the buffer of APP1 segment if exists.
236   virtual void DestroyApp1();
237 
238   // The Exif data (APP1). Owned by this class.
239   ExifData* exif_data_;
240   // The raw data of APP1 segment. It's allocated by ExifMem in |exif_data_| but
241   // owned by this class.
242   uint8_t* app1_buffer_;
243   // The length of |app1_buffer_|.
244   unsigned int app1_length_;
245 
246   // How precise the float-to-rational conversion for EXIF tags would be.
247   const static int kRationalPrecision = 10000;
248 
249   SensorCharacteristics sensor_chars_;
250 };
251 
252 #define SET_SHORT(ifd, tag, value)                              \
253   do {                                                          \
254     if (SetShort(ifd, tag, value, #tag) == false) return false; \
255   } while (0);
256 
257 #define SET_LONG(ifd, tag, value)                              \
258   do {                                                         \
259     if (SetLong(ifd, tag, value, #tag) == false) return false; \
260   } while (0);
261 
262 #define SET_RATIONAL(ifd, tag, numerator, denominator)                \
263   do {                                                                \
264     if (SetRational(ifd, tag, numerator, denominator, #tag) == false) \
265       return false;                                                   \
266   } while (0);
267 
268 #define SET_SRATIONAL(ifd, tag, numerator, denominator)                \
269   do {                                                                 \
270     if (SetSRational(ifd, tag, numerator, denominator, #tag) == false) \
271       return false;                                                    \
272   } while (0);
273 
274 #define SET_STRING(ifd, tag, format, buffer)                              \
275   do {                                                                    \
276     if (SetString(ifd, tag, format, buffer, #tag) == false) return false; \
277   } while (0);
278 
279 // This comes from the Exif Version 2.2 standard table 6.
280 const char gExifAsciiPrefix[] = {0x41, 0x53, 0x43, 0x49, 0x49, 0x0, 0x0, 0x0};
281 
SetLatitudeOrLongitudeData(unsigned char * data,double num)282 static void SetLatitudeOrLongitudeData(unsigned char* data, double num) {
283   // Take the integer part of |num|.
284   ExifLong degrees = static_cast<ExifLong>(num);
285   ExifLong minutes = static_cast<ExifLong>(60 * (num - degrees));
286   ExifLong microseconds =
287       static_cast<ExifLong>(3600000000u * (num - degrees - minutes / 60.0));
288   exif_set_rational(data, EXIF_BYTE_ORDER_INTEL, {degrees, 1});
289   exif_set_rational(data + sizeof(ExifRational), EXIF_BYTE_ORDER_INTEL,
290                     {minutes, 1});
291   exif_set_rational(data + 2 * sizeof(ExifRational), EXIF_BYTE_ORDER_INTEL,
292                     {microseconds, 1000000});
293 }
294 
Create(SensorCharacteristics sensor_chars)295 ExifUtils* ExifUtils::Create(SensorCharacteristics sensor_chars) {
296   return new ExifUtilsImpl(sensor_chars);
297 }
298 
~ExifUtils()299 ExifUtils::~ExifUtils() {
300 }
301 
ExifUtilsImpl(SensorCharacteristics sensor_chars)302 ExifUtilsImpl::ExifUtilsImpl(SensorCharacteristics sensor_chars)
303     : exif_data_(nullptr),
304       app1_buffer_(nullptr),
305       app1_length_(0),
306       sensor_chars_(sensor_chars) {
307 }
308 
~ExifUtilsImpl()309 ExifUtilsImpl::~ExifUtilsImpl() {
310   Reset();
311 }
312 
Initialize()313 bool ExifUtilsImpl::Initialize() {
314   Reset();
315   exif_data_ = exif_data_new();
316   if (exif_data_ == nullptr) {
317     ALOGE("%s: allocate memory for exif_data_ failed", __FUNCTION__);
318     return false;
319   }
320   // set the image options.
321   exif_data_set_option(exif_data_, EXIF_DATA_OPTION_FOLLOW_SPECIFICATION);
322   exif_data_set_data_type(exif_data_, EXIF_DATA_TYPE_COMPRESSED);
323   exif_data_set_byte_order(exif_data_, EXIF_BYTE_ORDER_INTEL);
324 
325   // set exif version to 2.2.
326   if (!SetExifVersion("0220")) {
327     return false;
328   }
329 
330   return true;
331 }
332 
SetAperture(float aperture)333 bool ExifUtilsImpl::SetAperture(float aperture) {
334   float apex_value = ConvertToApex(aperture);
335   SET_RATIONAL(
336       EXIF_IFD_EXIF, EXIF_TAG_APERTURE_VALUE,
337       static_cast<uint32_t>(std::round(apex_value * kRationalPrecision)),
338       kRationalPrecision);
339   return true;
340 }
341 
SetColorSpace(uint16_t color_space)342 bool ExifUtilsImpl::SetColorSpace(uint16_t color_space) {
343   SET_SHORT(EXIF_IFD_EXIF, EXIF_TAG_COLOR_SPACE, color_space);
344   return true;
345 }
346 
SetDateTime(const struct tm & t)347 bool ExifUtilsImpl::SetDateTime(const struct tm& t) {
348   // The length is 20 bytes including NULL for termination in Exif standard.
349   char str[20];
350   int result = snprintf(str, sizeof(str), "%04i:%02i:%02i %02i:%02i:%02i",
351                         t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour,
352                         t.tm_min, t.tm_sec);
353   if (result != sizeof(str) - 1) {
354     ALOGW("%s: Input time is invalid", __FUNCTION__);
355     return false;
356   }
357   std::string buffer(str);
358   SET_STRING(EXIF_IFD_0, EXIF_TAG_DATE_TIME, EXIF_FORMAT_ASCII, buffer);
359   SET_STRING(EXIF_IFD_EXIF, EXIF_TAG_DATE_TIME_ORIGINAL, EXIF_FORMAT_ASCII,
360              buffer);
361   SET_STRING(EXIF_IFD_EXIF, EXIF_TAG_DATE_TIME_DIGITIZED, EXIF_FORMAT_ASCII,
362              buffer);
363   return true;
364 }
365 
SetDigitalZoomRatio(uint32_t crop_width,uint32_t crop_height,uint32_t sensor_width,uint32_t sensor_height)366 bool ExifUtilsImpl::SetDigitalZoomRatio(uint32_t crop_width,
367                                         uint32_t crop_height,
368                                         uint32_t sensor_width,
369                                         uint32_t sensor_height) {
370   float zoom_ratio_x = (crop_width == 0) ? 1.0 : 1.0 * sensor_width / crop_width;
371   float zoom_ratio_y =
372       (crop_height == 0) ? 1.0 : 1.0 * sensor_height / crop_height;
373   float zoom_ratio = std::max(zoom_ratio_x, zoom_ratio_y);
374   const static float no_zoom_threshold = 1.02f;
375 
376   if (zoom_ratio <= no_zoom_threshold) {
377     SET_RATIONAL(EXIF_IFD_EXIF, EXIF_TAG_DIGITAL_ZOOM_RATIO, 0, 1);
378   } else {
379     SET_RATIONAL(
380         EXIF_IFD_EXIF, EXIF_TAG_DIGITAL_ZOOM_RATIO,
381         static_cast<uint32_t>(std::round(zoom_ratio * kRationalPrecision)),
382         kRationalPrecision);
383   }
384   return true;
385 }
386 
SetExposureMode(uint8_t exposure_mode)387 bool ExifUtilsImpl::SetExposureMode(uint8_t exposure_mode) {
388   uint16_t mode = (exposure_mode == ANDROID_CONTROL_AE_MODE_OFF) ? 1 : 0;
389   SET_SHORT(EXIF_IFD_EXIF, EXIF_TAG_EXPOSURE_MODE, mode);
390   return true;
391 }
392 
SetExposureTime(float exposure_time)393 bool ExifUtilsImpl::SetExposureTime(float exposure_time) {
394   SET_RATIONAL(
395       EXIF_IFD_EXIF, EXIF_TAG_EXPOSURE_TIME,
396       static_cast<uint32_t>(std::round(exposure_time * kRationalPrecision)),
397       kRationalPrecision);
398   return true;
399 }
400 
SetFlash(uint8_t flash_available,uint8_t flash_state,uint8_t ae_mode)401 bool ExifUtilsImpl::SetFlash(uint8_t flash_available, uint8_t flash_state,
402                              uint8_t ae_mode) {
403   // EXIF_TAG_FLASH bits layout per EXIF standard:
404   // Bit 0:    0 - did not fire
405   //           1 - fired
406   // Bit 1-2:  status of return light
407   // Bit 3-4:  0 - unknown
408   //           1 - compulsory flash firing
409   //           2 - compulsory flash suppression
410   //           3 - auto mode
411   // Bit 5:    0 - flash function present
412   //           1 - no flash function
413   // Bit 6:    0 - no red-eye reduction mode or unknown
414   //           1 - red-eye reduction supported
415   uint16_t flash = 0x20;
416 
417   if (flash_available == ANDROID_FLASH_INFO_AVAILABLE_TRUE) {
418     flash = 0x00;
419 
420     if (flash_state == ANDROID_FLASH_STATE_FIRED) {
421       flash |= 0x1;
422     }
423     if (ae_mode == ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE) {
424       flash |= 0x40;
425     }
426 
427     uint16_t flash_mode = 0;
428     switch (ae_mode) {
429       case ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH:
430       case ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE:
431         flash_mode = 3;  // AUTO
432         break;
433       case ANDROID_CONTROL_AE_MODE_ON_ALWAYS_FLASH:
434       case ANDROID_CONTROL_AE_MODE_ON_EXTERNAL_FLASH:
435         flash_mode = 1;  // ON
436         break;
437       case ANDROID_CONTROL_AE_MODE_OFF:
438       case ANDROID_CONTROL_AE_MODE_ON:
439         flash_mode = 2;  // OFF
440         break;
441       default:
442         flash_mode = 0;  // UNKNOWN
443         break;
444     }
445     flash |= (flash_mode << 3);
446   }
447   SET_SHORT(EXIF_IFD_EXIF, EXIF_TAG_FLASH, flash);
448   return true;
449 }
450 
SetFNumber(float f_number)451 bool ExifUtilsImpl::SetFNumber(float f_number) {
452   SET_RATIONAL(EXIF_IFD_EXIF, EXIF_TAG_FNUMBER,
453                static_cast<uint32_t>(std::round(f_number * kRationalPrecision)),
454                kRationalPrecision);
455   return true;
456 }
457 
SetFocalLength(float focal_length)458 bool ExifUtilsImpl::SetFocalLength(float focal_length) {
459   uint32_t numerator =
460       static_cast<uint32_t>(std::round(focal_length * kRationalPrecision));
461   SET_RATIONAL(EXIF_IFD_EXIF, EXIF_TAG_FOCAL_LENGTH, numerator,
462                kRationalPrecision);
463   return true;
464 }
465 
SetFocalLengthIn35mmFilm(float focal_length,float sensor_size_x,float sensor_size_y)466 bool ExifUtilsImpl::SetFocalLengthIn35mmFilm(float focal_length,
467                                              float sensor_size_x,
468                                              float sensor_size_y) {
469   static const float film_diagonal = 43.27;  // diagonal of 35mm film
470   static const float min_sensor_diagonal = 0.01;
471   float sensor_diagonal =
472       std::sqrt(sensor_size_x * sensor_size_x + sensor_size_y * sensor_size_y);
473   sensor_diagonal = std::max(sensor_diagonal, min_sensor_diagonal);
474   float focal_length35mm_film =
475       std::round(focal_length * film_diagonal / sensor_diagonal);
476   focal_length35mm_film = std::min(1.0f * 65535, focal_length35mm_film);
477 
478   SET_SHORT(EXIF_IFD_EXIF, EXIF_TAG_FOCAL_LENGTH_IN_35MM_FILM,
479             static_cast<uint16_t>(focal_length35mm_film));
480   return true;
481 }
482 
SetGpsAltitude(double altitude)483 bool ExifUtilsImpl::SetGpsAltitude(double altitude) {
484   ExifTag ref_tag = static_cast<ExifTag>(EXIF_TAG_GPS_ALTITUDE_REF);
485   std::unique_ptr<ExifEntry> ref_entry =
486       AddVariableLengthEntry(EXIF_IFD_GPS, ref_tag, EXIF_FORMAT_BYTE, 1, 1);
487   if (!ref_entry) {
488     ALOGE("%s: Adding GPSAltitudeRef exif entry failed", __FUNCTION__);
489     return false;
490   }
491   if (altitude >= 0) {
492     *ref_entry->data = 0;
493   } else {
494     *ref_entry->data = 1;
495     altitude *= -1;
496   }
497 
498   ExifTag tag = static_cast<ExifTag>(EXIF_TAG_GPS_ALTITUDE);
499   std::unique_ptr<ExifEntry> entry = AddVariableLengthEntry(
500       EXIF_IFD_GPS, tag, EXIF_FORMAT_RATIONAL, 1, sizeof(ExifRational));
501   if (!entry) {
502     exif_content_remove_entry(exif_data_->ifd[EXIF_IFD_GPS], ref_entry.get());
503     ALOGE("%s: Adding GPSAltitude exif entry failed", __FUNCTION__);
504     return false;
505   }
506   exif_set_rational(entry->data, EXIF_BYTE_ORDER_INTEL,
507                     {static_cast<ExifLong>(altitude * 1000), 1000});
508 
509   return true;
510 }
511 
SetGpsLatitude(double latitude)512 bool ExifUtilsImpl::SetGpsLatitude(double latitude) {
513   const ExifTag ref_tag = static_cast<ExifTag>(EXIF_TAG_GPS_LATITUDE_REF);
514   std::unique_ptr<ExifEntry> ref_entry =
515       AddVariableLengthEntry(EXIF_IFD_GPS, ref_tag, EXIF_FORMAT_ASCII, 2, 2);
516   if (!ref_entry) {
517     ALOGE("%s: Adding GPSLatitudeRef exif entry failed", __FUNCTION__);
518     return false;
519   }
520   if (latitude >= 0) {
521     memcpy(ref_entry->data, "N", sizeof("N"));
522   } else {
523     memcpy(ref_entry->data, "S", sizeof("S"));
524     latitude *= -1;
525   }
526 
527   const ExifTag tag = static_cast<ExifTag>(EXIF_TAG_GPS_LATITUDE);
528   std::unique_ptr<ExifEntry> entry = AddVariableLengthEntry(
529       EXIF_IFD_GPS, tag, EXIF_FORMAT_RATIONAL, 3, 3 * sizeof(ExifRational));
530   if (!entry) {
531     exif_content_remove_entry(exif_data_->ifd[EXIF_IFD_GPS], ref_entry.get());
532     ALOGE("%s: Adding GPSLatitude exif entry failed", __FUNCTION__);
533     return false;
534   }
535   SetLatitudeOrLongitudeData(entry->data, latitude);
536 
537   return true;
538 }
539 
SetGpsLongitude(double longitude)540 bool ExifUtilsImpl::SetGpsLongitude(double longitude) {
541   ExifTag ref_tag = static_cast<ExifTag>(EXIF_TAG_GPS_LONGITUDE_REF);
542   std::unique_ptr<ExifEntry> ref_entry =
543       AddVariableLengthEntry(EXIF_IFD_GPS, ref_tag, EXIF_FORMAT_ASCII, 2, 2);
544   if (!ref_entry) {
545     ALOGE("%s: Adding GPSLongitudeRef exif entry failed", __FUNCTION__);
546     return false;
547   }
548   if (longitude >= 0) {
549     memcpy(ref_entry->data, "E", sizeof("E"));
550   } else {
551     memcpy(ref_entry->data, "W", sizeof("W"));
552     longitude *= -1;
553   }
554 
555   ExifTag tag = static_cast<ExifTag>(EXIF_TAG_GPS_LONGITUDE);
556   std::unique_ptr<ExifEntry> entry = AddVariableLengthEntry(
557       EXIF_IFD_GPS, tag, EXIF_FORMAT_RATIONAL, 3, 3 * sizeof(ExifRational));
558   if (!entry) {
559     exif_content_remove_entry(exif_data_->ifd[EXIF_IFD_GPS], ref_entry.get());
560     ALOGE("%s: Adding GPSLongitude exif entry failed", __FUNCTION__);
561     return false;
562   }
563   SetLatitudeOrLongitudeData(entry->data, longitude);
564 
565   return true;
566 }
567 
SetGpsProcessingMethod(const std::string & method)568 bool ExifUtilsImpl::SetGpsProcessingMethod(const std::string& method) {
569   std::string buffer =
570       std::string(gExifAsciiPrefix, sizeof(gExifAsciiPrefix)) + method;
571   SET_STRING(EXIF_IFD_GPS, static_cast<ExifTag>(EXIF_TAG_GPS_PROCESSING_METHOD),
572              EXIF_FORMAT_UNDEFINED, buffer);
573   return true;
574 }
575 
SetGpsTimestamp(const struct tm & t)576 bool ExifUtilsImpl::SetGpsTimestamp(const struct tm& t) {
577   const ExifTag date_tag = static_cast<ExifTag>(EXIF_TAG_GPS_DATE_STAMP);
578   const size_t kGpsDateStampSize = 11;
579   std::unique_ptr<ExifEntry> entry =
580       AddVariableLengthEntry(EXIF_IFD_GPS, date_tag, EXIF_FORMAT_ASCII,
581                              kGpsDateStampSize, kGpsDateStampSize);
582   if (!entry) {
583     ALOGE("%s: Adding GPSDateStamp exif entry failed", __FUNCTION__);
584     return false;
585   }
586   int result =
587       snprintf(reinterpret_cast<char*>(entry->data), kGpsDateStampSize,
588                "%04i:%02i:%02i", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday);
589   if (result != kGpsDateStampSize - 1) {
590     ALOGW("%s: Input time is invalid", __FUNCTION__);
591     return false;
592   }
593 
594   const ExifTag time_tag = static_cast<ExifTag>(EXIF_TAG_GPS_TIME_STAMP);
595   entry = AddVariableLengthEntry(EXIF_IFD_GPS, time_tag, EXIF_FORMAT_RATIONAL,
596                                  3, 3 * sizeof(ExifRational));
597   if (!entry) {
598     ALOGE("%s: Adding GPSTimeStamp exif entry failed", __FUNCTION__);
599     return false;
600   }
601   exif_set_rational(entry->data, EXIF_BYTE_ORDER_INTEL,
602                     {static_cast<ExifLong>(t.tm_hour), 1});
603   exif_set_rational(entry->data + sizeof(ExifRational), EXIF_BYTE_ORDER_INTEL,
604                     {static_cast<ExifLong>(t.tm_min), 1});
605   exif_set_rational(entry->data + 2 * sizeof(ExifRational),
606                     EXIF_BYTE_ORDER_INTEL, {static_cast<ExifLong>(t.tm_sec), 1});
607 
608   return true;
609 }
610 
SetImageHeight(uint32_t length)611 bool ExifUtilsImpl::SetImageHeight(uint32_t length) {
612   SET_SHORT(EXIF_IFD_0, EXIF_TAG_IMAGE_LENGTH, length);
613   SET_SHORT(EXIF_IFD_EXIF, EXIF_TAG_PIXEL_Y_DIMENSION, length);
614   return true;
615 }
616 
SetImageWidth(uint32_t width)617 bool ExifUtilsImpl::SetImageWidth(uint32_t width) {
618   SET_SHORT(EXIF_IFD_0, EXIF_TAG_IMAGE_WIDTH, width);
619   SET_SHORT(EXIF_IFD_EXIF, EXIF_TAG_PIXEL_X_DIMENSION, width);
620   return true;
621 }
622 
SetIsoSpeedRating(uint16_t iso_speed_ratings)623 bool ExifUtilsImpl::SetIsoSpeedRating(uint16_t iso_speed_ratings) {
624   SET_SHORT(EXIF_IFD_EXIF, EXIF_TAG_ISO_SPEED_RATINGS, iso_speed_ratings);
625   return true;
626 }
627 
SetMaxAperture(float aperture)628 bool ExifUtilsImpl::SetMaxAperture(float aperture) {
629   float maxAperture = ConvertToApex(aperture);
630   SET_RATIONAL(
631       EXIF_IFD_EXIF, EXIF_TAG_MAX_APERTURE_VALUE,
632       static_cast<uint32_t>(std::round(maxAperture * kRationalPrecision)),
633       kRationalPrecision);
634   return true;
635 }
636 
SetExposureBias(int32_t ev,uint32_t ev_step_numerator,uint32_t ev_step_denominator)637 bool ExifUtilsImpl::SetExposureBias(int32_t ev, uint32_t ev_step_numerator,
638                                     uint32_t ev_step_denominator) {
639   SET_RATIONAL(EXIF_IFD_EXIF, EXIF_TAG_EXPOSURE_BIAS_VALUE,
640                ev * ev_step_numerator, ev_step_denominator);
641   return true;
642 }
643 
SetOrientation(uint16_t degrees)644 bool ExifUtilsImpl::SetOrientation(uint16_t degrees) {
645   ExifOrientation value = ExifOrientation::ORIENTATION_0_DEGREES;
646   switch (degrees) {
647     case 90:
648       value = ExifOrientation::ORIENTATION_90_DEGREES;
649       break;
650     case 180:
651       value = ExifOrientation::ORIENTATION_180_DEGREES;
652       break;
653     case 270:
654       value = ExifOrientation::ORIENTATION_270_DEGREES;
655       break;
656     default:
657       break;
658   }
659   return SetOrientationValue(value);
660 }
661 
SetOrientationValue(ExifOrientation orientation_value)662 bool ExifUtilsImpl::SetOrientationValue(ExifOrientation orientation_value) {
663   SET_SHORT(EXIF_IFD_0, EXIF_TAG_ORIENTATION, orientation_value);
664   return true;
665 }
666 
SetShutterSpeed(float exposure_time)667 bool ExifUtilsImpl::SetShutterSpeed(float exposure_time) {
668   float shutter_speed = -log2f(exposure_time);
669   SET_SRATIONAL(EXIF_IFD_EXIF, EXIF_TAG_SHUTTER_SPEED_VALUE,
670                 static_cast<uint32_t>(shutter_speed * kRationalPrecision),
671                 kRationalPrecision);
672   return true;
673 }
674 
SetSubjectDistance(float diopters)675 bool ExifUtilsImpl::SetSubjectDistance(float diopters) {
676   const static float kInfinityDiopters = 1.0e-6;
677   uint32_t numerator, denominator;
678   uint16_t distance_range;
679   if (diopters > kInfinityDiopters) {
680     float focus_distance = 1.0f / diopters;
681     numerator =
682         static_cast<uint32_t>(std::round(focus_distance * kRationalPrecision));
683     denominator = kRationalPrecision;
684 
685     if (focus_distance < 1.0f) {
686       distance_range = 1;  // Macro
687     } else if (focus_distance < 3.0f) {
688       distance_range = 2;  // Close
689     } else {
690       distance_range = 3;  // Distant
691     }
692   } else {
693     numerator = 0xFFFFFFFF;
694     denominator = 1;
695     distance_range = 3;  // Distant
696   }
697   SET_RATIONAL(EXIF_IFD_EXIF, EXIF_TAG_SUBJECT_DISTANCE, numerator, denominator);
698   SET_SHORT(EXIF_IFD_EXIF, EXIF_TAG_SUBJECT_DISTANCE_RANGE, distance_range);
699   return true;
700 }
701 
SetSubsecTime(const std::string & subsec_time)702 bool ExifUtilsImpl::SetSubsecTime(const std::string& subsec_time) {
703   SET_STRING(EXIF_IFD_EXIF, EXIF_TAG_SUB_SEC_TIME, EXIF_FORMAT_ASCII,
704              subsec_time);
705   SET_STRING(EXIF_IFD_EXIF, EXIF_TAG_SUB_SEC_TIME_ORIGINAL, EXIF_FORMAT_ASCII,
706              subsec_time);
707   SET_STRING(EXIF_IFD_EXIF, EXIF_TAG_SUB_SEC_TIME_DIGITIZED, EXIF_FORMAT_ASCII,
708              subsec_time);
709   return true;
710 }
711 
SetWhiteBalance(uint8_t white_balance)712 bool ExifUtilsImpl::SetWhiteBalance(uint8_t white_balance) {
713   uint16_t whiteBalance =
714       (white_balance == ANDROID_CONTROL_AWB_MODE_AUTO) ? 0 : 1;
715   SET_SHORT(EXIF_IFD_EXIF, EXIF_TAG_WHITE_BALANCE, whiteBalance);
716   return true;
717 }
718 
GenerateApp1(unsigned char * thumbnail_buffer,uint32_t size)719 bool ExifUtilsImpl::GenerateApp1(unsigned char* thumbnail_buffer,
720                                  uint32_t size) {
721   DestroyApp1();
722   exif_data_->data = thumbnail_buffer;
723   exif_data_->size = size;
724   // Save the result into |app1_buffer_|.
725   exif_data_save_data(exif_data_, &app1_buffer_, &app1_length_);
726   if (!app1_length_) {
727     ALOGE("%s: Allocate memory for app1_buffer_ failed", __FUNCTION__);
728     return false;
729   }
730   /*
731    * The JPEG segment size is 16 bits in spec. The size of APP1 segment should
732    * be smaller than 65533 because there are two bytes for segment size field.
733    */
734   if (app1_length_ > 65533) {
735     DestroyApp1();
736     ALOGE("%s: The size of APP1 segment is too large", __FUNCTION__);
737     return false;
738   }
739   return true;
740 }
741 
GetApp1Buffer()742 const uint8_t* ExifUtilsImpl::GetApp1Buffer() {
743   return app1_buffer_;
744 }
745 
GetApp1Length()746 unsigned int ExifUtilsImpl::GetApp1Length() {
747   return app1_length_;
748 }
749 
SetExifVersion(const std::string & exif_version)750 bool ExifUtilsImpl::SetExifVersion(const std::string& exif_version) {
751   SET_STRING(EXIF_IFD_EXIF, EXIF_TAG_EXIF_VERSION, EXIF_FORMAT_UNDEFINED,
752              exif_version);
753   return true;
754 }
755 
SetMake(const std::string & make)756 bool ExifUtilsImpl::SetMake(const std::string& make) {
757   SET_STRING(EXIF_IFD_0, EXIF_TAG_MAKE, EXIF_FORMAT_UNDEFINED, make);
758   return true;
759 }
760 
SetModel(const std::string & model)761 bool ExifUtilsImpl::SetModel(const std::string& model) {
762   SET_STRING(EXIF_IFD_0, EXIF_TAG_MODEL, EXIF_FORMAT_UNDEFINED, model);
763   return true;
764 }
765 
Reset()766 void ExifUtilsImpl::Reset() {
767   DestroyApp1();
768   if (exif_data_) {
769     /*
770      * Since we decided to ignore the original APP1, we are sure that there is
771      * no thumbnail allocated by libexif. |exif_data_->data| is actually
772      * allocated by JpegCompressor. sets |exif_data_->data| to nullptr to
773      * prevent exif_data_unref() destroy it incorrectly.
774      */
775     exif_data_->data = nullptr;
776     exif_data_->size = 0;
777     exif_data_unref(exif_data_);
778     exif_data_ = nullptr;
779   }
780 }
781 
AddVariableLengthEntry(ExifIfd ifd,ExifTag tag,ExifFormat format,uint64_t components,unsigned int size)782 std::unique_ptr<ExifEntry> ExifUtilsImpl::AddVariableLengthEntry(
783     ExifIfd ifd, ExifTag tag, ExifFormat format, uint64_t components,
784     unsigned int size) {
785   // Remove old entry if exists.
786   exif_content_remove_entry(exif_data_->ifd[ifd],
787                             exif_content_get_entry(exif_data_->ifd[ifd], tag));
788   ExifMem* mem = exif_mem_new_default();
789   if (!mem) {
790     ALOGE("%s: Allocate memory for exif entry failed", __FUNCTION__);
791     return nullptr;
792   }
793   std::unique_ptr<ExifEntry> entry(exif_entry_new_mem(mem));
794   if (!entry) {
795     ALOGE("%s: Allocate memory for exif entry failed", __FUNCTION__);
796     exif_mem_unref(mem);
797     return nullptr;
798   }
799   void* tmp_buffer = exif_mem_alloc(mem, size);
800   if (!tmp_buffer) {
801     ALOGE("%s: Allocate memory for exif entry failed", __FUNCTION__);
802     exif_mem_unref(mem);
803     return nullptr;
804   }
805 
806   entry->data = static_cast<unsigned char*>(tmp_buffer);
807   entry->tag = tag;
808   entry->format = format;
809   entry->components = components;
810   entry->size = size;
811 
812   exif_content_add_entry(exif_data_->ifd[ifd], entry.get());
813   exif_mem_unref(mem);
814 
815   return entry;
816 }
817 
AddEntry(ExifIfd ifd,ExifTag tag)818 std::unique_ptr<ExifEntry> ExifUtilsImpl::AddEntry(ExifIfd ifd, ExifTag tag) {
819   std::unique_ptr<ExifEntry> entry(
820       exif_content_get_entry(exif_data_->ifd[ifd], tag));
821   if (entry) {
822     // exif_content_get_entry() won't ref the entry, so we ref here.
823     exif_entry_ref(entry.get());
824     return entry;
825   }
826   entry.reset(exif_entry_new());
827   if (!entry) {
828     ALOGE("%s: Allocate memory for exif entry failed", __FUNCTION__);
829     return nullptr;
830   }
831   entry->tag = tag;
832   exif_content_add_entry(exif_data_->ifd[ifd], entry.get());
833   exif_entry_initialize(entry.get(), tag);
834   return entry;
835 }
836 
SetShort(ExifIfd ifd,ExifTag tag,uint16_t value,const std::string & msg)837 bool ExifUtilsImpl::SetShort(ExifIfd ifd, ExifTag tag, uint16_t value,
838                              const std::string& msg) {
839   std::unique_ptr<ExifEntry> entry = AddEntry(ifd, tag);
840   if (!entry) {
841     ALOGE("%s: Adding '%s' entry failed", __FUNCTION__, msg.c_str());
842     return false;
843   }
844   exif_set_short(entry->data, EXIF_BYTE_ORDER_INTEL, value);
845   return true;
846 }
847 
SetLong(ExifIfd ifd,ExifTag tag,uint32_t value,const std::string & msg)848 bool ExifUtilsImpl::SetLong(ExifIfd ifd, ExifTag tag, uint32_t value,
849                             const std::string& msg) {
850   std::unique_ptr<ExifEntry> entry = AddEntry(ifd, tag);
851   if (!entry) {
852     ALOGE("%s: Adding '%s' entry failed", __FUNCTION__, msg.c_str());
853     return false;
854   }
855   exif_set_long(entry->data, EXIF_BYTE_ORDER_INTEL, value);
856   return true;
857 }
858 
SetRational(ExifIfd ifd,ExifTag tag,uint32_t numerator,uint32_t denominator,const std::string & msg)859 bool ExifUtilsImpl::SetRational(ExifIfd ifd, ExifTag tag, uint32_t numerator,
860                                 uint32_t denominator, const std::string& msg) {
861   std::unique_ptr<ExifEntry> entry = AddEntry(ifd, tag);
862   if (!entry) {
863     ALOGE("%s: Adding '%s' entry failed", __FUNCTION__, msg.c_str());
864     return false;
865   }
866   exif_set_rational(entry->data, EXIF_BYTE_ORDER_INTEL,
867                     {numerator, denominator});
868   return true;
869 }
870 
SetSRational(ExifIfd ifd,ExifTag tag,int32_t numerator,int32_t denominator,const std::string & msg)871 bool ExifUtilsImpl::SetSRational(ExifIfd ifd, ExifTag tag, int32_t numerator,
872                                  int32_t denominator, const std::string& msg) {
873   std::unique_ptr<ExifEntry> entry = AddEntry(ifd, tag);
874   if (!entry) {
875     ALOGE("%s: Adding '%s' entry failed", __FUNCTION__, msg.c_str());
876     return false;
877   }
878   exif_set_srational(entry->data, EXIF_BYTE_ORDER_INTEL,
879                      {numerator, denominator});
880   return true;
881 }
882 
SetString(ExifIfd ifd,ExifTag tag,ExifFormat format,const std::string & buffer,const std::string & msg)883 bool ExifUtilsImpl::SetString(ExifIfd ifd, ExifTag tag, ExifFormat format,
884                               const std::string& buffer,
885                               const std::string& msg) {
886   size_t entry_size = buffer.length();
887   // Since the exif format is undefined, NULL termination is not necessary.
888   if (format == EXIF_FORMAT_ASCII) {
889     entry_size++;
890   }
891   std::unique_ptr<ExifEntry> entry =
892       AddVariableLengthEntry(ifd, tag, format, entry_size, entry_size);
893   if (!entry) {
894     ALOGE("%s: Adding '%s' entry failed", __FUNCTION__, msg.c_str());
895     return false;
896   }
897   memcpy(entry->data, buffer.c_str(), entry_size);
898   return true;
899 }
900 
DestroyApp1()901 void ExifUtilsImpl::DestroyApp1() {
902   /*
903    * Since there is no API to access ExifMem in ExifData->priv, we use free
904    * here, which is the default free function in libexif. See
905    * exif_data_save_data() for detail.
906    */
907   free(app1_buffer_);
908   app1_buffer_ = nullptr;
909   app1_length_ = 0;
910 }
911 
SetFromMetadata(const HalCameraMetadata & metadata,size_t image_width,size_t image_height)912 bool ExifUtilsImpl::SetFromMetadata(const HalCameraMetadata& metadata,
913                                     size_t image_width, size_t image_height) {
914   if (!SetImageWidth(image_width) || !SetImageHeight(image_height)) {
915     ALOGE("%s: setting image resolution failed.", __FUNCTION__);
916     return false;
917   }
918 
919   struct timespec tp;
920   struct tm time_info;
921   bool time_available = clock_gettime(CLOCK_REALTIME, &tp) != -1;
922   localtime_r(&tp.tv_sec, &time_info);
923   if (!SetDateTime(time_info)) {
924     ALOGE("%s: setting data time failed.", __FUNCTION__);
925     return false;
926   }
927 
928   float focal_length;
929   camera_metadata_ro_entry entry;
930   auto ret = metadata.Get(ANDROID_LENS_FOCAL_LENGTH, &entry);
931   if (ret == OK) {
932     focal_length = entry.data.f[0];
933 
934     if (!SetFocalLength(focal_length)) {
935       ALOGE("%s: setting focal length failed.", __FUNCTION__);
936       return false;
937     }
938 
939     if (!SetFocalLengthIn35mmFilm(focal_length, sensor_chars_.physical_size[0],
940                                   sensor_chars_.physical_size[1])) {
941       ALOGE("%s: setting focal length in 35mm failed.", __FUNCTION__);
942       return false;
943     }
944   } else {
945     ALOGV("%s: Cannot find focal length in metadata.", __FUNCTION__);
946   }
947 
948   ret = metadata.Get(ANDROID_SCALER_CROP_REGION, &entry);
949   if (ret == OK) {
950     if (!SetDigitalZoomRatio(entry.data.i32[2], entry.data.i32[3],
951                              sensor_chars_.width, sensor_chars_.height)) {
952       ALOGE("%s: setting digital zoom ratio failed.", __FUNCTION__);
953       return false;
954     }
955   }
956 
957   ret = metadata.Get(ANDROID_JPEG_GPS_COORDINATES, &entry);
958   if (ret == OK) {
959     if (entry.count < 3) {
960       ALOGE("%s: Gps coordinates in metadata is not complete.", __FUNCTION__);
961       return false;
962     }
963     if (!SetGpsLatitude(entry.data.d[0])) {
964       ALOGE("%s: setting gps latitude failed.", __FUNCTION__);
965       return false;
966     }
967     if (!SetGpsLongitude(entry.data.d[1])) {
968       ALOGE("%s: setting gps longitude failed.", __FUNCTION__);
969       return false;
970     }
971     if (!SetGpsAltitude(entry.data.d[2])) {
972       ALOGE("%s: setting gps altitude failed.", __FUNCTION__);
973       return false;
974     }
975   }
976 
977   ret = metadata.Get(ANDROID_JPEG_GPS_PROCESSING_METHOD, &entry);
978   if (ret == OK) {
979     std::string method_str(reinterpret_cast<const char*>(entry.data.u8));
980     if (!SetGpsProcessingMethod(method_str)) {
981       ALOGE("%s: setting gps processing method failed.", __FUNCTION__);
982       return false;
983     }
984   }
985 
986   ret = metadata.Get(ANDROID_JPEG_GPS_TIMESTAMP, &entry);
987   if (time_available && (ret == OK)) {
988     time_t timestamp = static_cast<time_t>(entry.data.i64[0]);
989     if (gmtime_r(&timestamp, &time_info)) {
990       if (!SetGpsTimestamp(time_info)) {
991         ALOGE("%s: setting gps timestamp failed.", __FUNCTION__);
992         return false;
993       }
994     } else {
995       ALOGE("%s: Time transformation failed.", __FUNCTION__);
996       return false;
997     }
998   }
999 
1000   ret = metadata.Get(ANDROID_JPEG_ORIENTATION, &entry);
1001   if (ret == OK) {
1002     if (!SetOrientation(entry.data.i32[0])) {
1003       ALOGE("%s: setting orientation failed.", __FUNCTION__);
1004       return false;
1005     }
1006   }
1007 
1008   ret = metadata.Get(ANDROID_SENSOR_EXPOSURE_TIME, &entry);
1009   if (ret == OK) {
1010     float exposure_time = 1.0f * entry.data.i64[0] / 1e9;
1011     if (!SetExposureTime(exposure_time)) {
1012       ALOGE("%s: setting exposure time failed.", __FUNCTION__);
1013       return false;
1014     }
1015 
1016     if (!SetShutterSpeed(exposure_time)) {
1017       ALOGE("%s: setting shutter speed failed.", __FUNCTION__);
1018       return false;
1019     }
1020   }
1021 
1022   ret = metadata.Get(ANDROID_LENS_FOCUS_DISTANCE, &entry);
1023   if (ret == OK) {
1024     if (!SetSubjectDistance(entry.data.f[0])) {
1025       ALOGE("%s: setting subject distance failed.", __FUNCTION__);
1026       return false;
1027     }
1028   }
1029 
1030   ret = metadata.Get(ANDROID_SENSOR_SENSITIVITY, &entry);
1031   if (ret == OK) {
1032     int32_t iso = entry.data.i32[0];
1033     camera_metadata_ro_entry post_raw_sens_entry;
1034     metadata.Get(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1035                  &post_raw_sens_entry);
1036     if (post_raw_sens_entry.count > 0) {
1037       iso = iso * post_raw_sens_entry.data.i32[0] / 100;
1038     }
1039 
1040     if (!SetIsoSpeedRating(static_cast<uint16_t>(iso))) {
1041       ALOGE("%s: setting iso rating failed.", __FUNCTION__);
1042       return false;
1043     }
1044   }
1045 
1046   ret = metadata.Get(ANDROID_LENS_APERTURE, &entry);
1047   if (ret == OK) {
1048     if (!SetFNumber(entry.data.f[0])) {
1049       ALOGE("%s: setting F number failed.", __FUNCTION__);
1050       return false;
1051     }
1052     if (!SetAperture(entry.data.f[0])) {
1053       ALOGE("%s: setting aperture failed.", __FUNCTION__);
1054       return false;
1055     }
1056   }
1057 
1058   static const uint16_t kSRGBColorSpace = 1;
1059   if (!SetColorSpace(kSRGBColorSpace)) {
1060     ALOGE("%s: setting color space failed.", __FUNCTION__);
1061     return false;
1062   }
1063 
1064   camera_metadata_ro_entry flash_state_entry;
1065   metadata.Get(ANDROID_FLASH_STATE, &flash_state_entry);
1066   camera_metadata_ro_entry ae_mode_entry;
1067   metadata.Get(ANDROID_CONTROL_AE_MODE, &ae_mode_entry);
1068   uint8_t flash_state = flash_state_entry.count > 0
1069                             ? flash_state_entry.data.u8[0]
1070                             : ANDROID_FLASH_STATE_UNAVAILABLE;
1071   uint8_t ae_mode = ae_mode_entry.count > 0 ? ae_mode_entry.data.u8[0]
1072                                             : ANDROID_CONTROL_AE_MODE_OFF;
1073 
1074   if (!SetFlash(sensor_chars_.is_flash_supported, flash_state, ae_mode)) {
1075     ALOGE("%s: setting flash failed.", __FUNCTION__);
1076     return false;
1077   }
1078 
1079   ret = metadata.Get(ANDROID_CONTROL_AWB_MODE, &entry);
1080   if (ret == OK) {
1081     if (!SetWhiteBalance(entry.data.u8[0])) {
1082       ALOGE("%s: setting white balance failed.", __FUNCTION__);
1083       return false;
1084     }
1085   }
1086 
1087   ret = metadata.Get(ANDROID_CONTROL_AE_MODE, &entry);
1088   if (ret == OK) {
1089     if (!SetExposureMode(entry.data.u8[0])) {
1090       ALOGE("%s: setting exposure mode failed.", __FUNCTION__);
1091       return false;
1092     }
1093   }
1094   if (time_available) {
1095     char str[4];
1096     if (snprintf(str, sizeof(str), "%03ld", tp.tv_nsec / 1000000) < 0) {
1097       ALOGE("%s: Subsec is invalid: %ld", __FUNCTION__, tp.tv_nsec);
1098       return false;
1099     }
1100     if (!SetSubsecTime(std::string(str))) {
1101       ALOGE("%s: setting subsec time failed.", __FUNCTION__);
1102       return false;
1103     }
1104   }
1105 
1106   return true;
1107 }
1108 
1109 }  // namespace android
1110