summaryrefslogtreecommitdiff
path: root/common/hal/aidl_service/aidl_utils.cc
blob: 332d1a1903be01b5e14b3658b98356d0f19f9012 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "GCH_AidlUtils"
// #define LOG_NDEBUG 0
#include "aidl_utils.h"

#include <aidlcommonsupport/NativeHandle.h>
#include <log/log.h>
#include <system/camera_metadata.h>

#include <regex>

#include "aidl_camera_device.h"
#include "aidl_camera_provider.h"

namespace android {
namespace hardware {
namespace camera {
namespace implementation {
namespace aidl_utils {

using AidlCameraProvider = provider::implementation::AidlCameraProvider;
using AidlCameraDevice = device::implementation::AidlCameraDevice;
using AidlStatus = aidl::android::hardware::camera::common::Status;
using DynamicRangeProfile = google_camera_hal::DynamicRangeProfile;
using ColorSpaceProfile = google_camera_hal::ColorSpaceProfile;

ScopedAStatus ConvertToAidlReturn(status_t hal_status) {
  switch (hal_status) {
    case OK:
      return ScopedAStatus::ok();
    case BAD_VALUE:
      return ScopedAStatus::fromServiceSpecificError(
          static_cast<int32_t>(Status::ILLEGAL_ARGUMENT));
    case -EBUSY:
      return ScopedAStatus::fromServiceSpecificError(
          static_cast<int32_t>(Status::CAMERA_IN_USE));
    case -EUSERS:
      return ScopedAStatus::fromServiceSpecificError(
          static_cast<int32_t>(Status::MAX_CAMERAS_IN_USE));
    case UNKNOWN_TRANSACTION:
    case INVALID_OPERATION:
      return ScopedAStatus::fromServiceSpecificError(
          static_cast<int32_t>(Status::OPERATION_NOT_SUPPORTED));
    case DEAD_OBJECT:
      return ScopedAStatus::fromServiceSpecificError(
          static_cast<int32_t>(Status::CAMERA_DISCONNECTED));
    default:
      return ScopedAStatus::fromServiceSpecificError(
          static_cast<int32_t>(Status::INTERNAL_ERROR));
  }
}

status_t ConvertToAidlVendorTagType(
    google_camera_hal::CameraMetadataType hal_type,
    CameraMetadataType* aidl_type) {
  if (aidl_type == nullptr) {
    ALOGE("%s: aidl_type is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  switch (hal_type) {
    case google_camera_hal::CameraMetadataType::kByte:
      *aidl_type = CameraMetadataType::BYTE;
      break;
    case google_camera_hal::CameraMetadataType::kInt32:
      *aidl_type = CameraMetadataType::INT32;
      break;
    case google_camera_hal::CameraMetadataType::kFloat:
      *aidl_type = CameraMetadataType::FLOAT;
      break;
    case google_camera_hal::CameraMetadataType::kInt64:
      *aidl_type = CameraMetadataType::INT64;
      break;
    case google_camera_hal::CameraMetadataType::kDouble:
      *aidl_type = CameraMetadataType::DOUBLE;
      break;
    case google_camera_hal::CameraMetadataType::kRational:
      *aidl_type = CameraMetadataType::RATIONAL;
      break;
    default:
      ALOGE("%s: Unknown google_camera_hal::CameraMetadataType: %u",
            __FUNCTION__, hal_type);
      return BAD_VALUE;
  }

  return OK;
}

status_t ConvertToAidlVendorTagSections(
    const std::vector<google_camera_hal::VendorTagSection>& hal_sections,
    std::vector<VendorTagSection>* aidl_sections) {
  if (aidl_sections == nullptr) {
    ALOGE("%s: aidl_sections is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  aidl_sections->resize(hal_sections.size());
  for (uint32_t i = 0; i < hal_sections.size(); i++) {
    (*aidl_sections)[i].sectionName = hal_sections[i].section_name;
    (*aidl_sections)[i].tags.resize(hal_sections[i].tags.size());

    for (uint32_t j = 0; j < hal_sections[i].tags.size(); j++) {
      (*aidl_sections)[i].tags[j].tagId = hal_sections[i].tags[j].tag_id;
      (*aidl_sections)[i].tags[j].tagName = hal_sections[i].tags[j].tag_name;
      status_t res =
          ConvertToAidlVendorTagType(hal_sections[i].tags[j].tag_type,
                                     &(*aidl_sections)[i].tags[j].tagType);
      if (res != OK) {
        ALOGE("%s: Converting to aidl vendor tag type failed. ", __FUNCTION__);
        return res;
      }
    }
  }
  return OK;
}

status_t ConvertToAidlResourceCost(
    const google_camera_hal::CameraResourceCost& hal_cost,
    CameraResourceCost* aidl_cost) {
  if (aidl_cost == nullptr) {
    ALOGE("%s: aidl_cost is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  aidl_cost->resourceCost = hal_cost.resource_cost;
  aidl_cost->conflictingDevices.resize(hal_cost.conflicting_devices.size());

  for (uint32_t i = 0; i < hal_cost.conflicting_devices.size(); i++) {
    aidl_cost->conflictingDevices[i] =
        "device@" + AidlCameraDevice::kDeviceVersion + "/" +
        AidlCameraProvider::kProviderName + "/" +
        std::to_string(hal_cost.conflicting_devices[i]);
  }

  return OK;
}

status_t ConvertToHalTemplateType(
    RequestTemplate aidl_template,
    google_camera_hal::RequestTemplate* hal_template) {
  if (hal_template == nullptr) {
    ALOGE("%s: hal_template is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  switch (aidl_template) {
    case RequestTemplate::PREVIEW:
      *hal_template = google_camera_hal::RequestTemplate::kPreview;
      break;
    case RequestTemplate::STILL_CAPTURE:
      *hal_template = google_camera_hal::RequestTemplate::kStillCapture;
      break;
    case RequestTemplate::VIDEO_RECORD:
      *hal_template = google_camera_hal::RequestTemplate::kVideoRecord;
      break;
    case RequestTemplate::VIDEO_SNAPSHOT:
      *hal_template = google_camera_hal::RequestTemplate::kVideoSnapshot;
      break;
    case RequestTemplate::ZERO_SHUTTER_LAG:
      *hal_template = google_camera_hal::RequestTemplate::kZeroShutterLag;
      break;
    case RequestTemplate::MANUAL:
      *hal_template = google_camera_hal::RequestTemplate::kManual;
      break;
    default:
      ALOGE("%s: Unknown AIDL RequestTemplate: %u", __FUNCTION__, aidl_template);
      return BAD_VALUE;
  }

  return OK;
}

status_t ConvertToAidlHalStreamConfig(
    const std::vector<google_camera_hal::HalStream>& hal_configured_streams,
    std::vector<HalStream>* aidl_hal_streams) {
  if (aidl_hal_streams == nullptr) {
    ALOGE("%s: aidl_hal_streams is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  aidl_hal_streams->resize(hal_configured_streams.size());

  for (uint32_t i = 0; i < hal_configured_streams.size(); i++) {
    auto& dst = (*aidl_hal_streams)[i];
    dst.supportOffline = false;
    if (hal_configured_streams[i].is_physical_camera_stream) {
      dst.physicalCameraId =
          std::to_string(hal_configured_streams[i].physical_camera_id);
    }

    dst.overrideDataSpace =
        static_cast<aidl::android::hardware::graphics::common::Dataspace>(
            hal_configured_streams[i].override_data_space);

    dst.id = hal_configured_streams[i].id;

    dst.overrideFormat =
        static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
            hal_configured_streams[i].override_format);

    dst.producerUsage =
        static_cast<aidl::android::hardware::graphics::common::BufferUsage>(
            hal_configured_streams[i].producer_usage);

    dst.consumerUsage =
        static_cast<aidl::android::hardware::graphics::common::BufferUsage>(
            hal_configured_streams[i].consumer_usage);

    dst.maxBuffers = hal_configured_streams[i].max_buffers;
  }

  return OK;
}

status_t WriteToResultMetadataQueue(
    camera_metadata_t* metadata,
    AidlMessageQueue<int8_t, SynchronizedReadWrite>* result_metadata_queue) {
  if (result_metadata_queue == nullptr) {
    return BAD_VALUE;
  }

  if (result_metadata_queue->availableToWrite() <= 0) {
    ALOGW("%s: result_metadata_queue is not available to write", __FUNCTION__);
    return BAD_VALUE;
  }

  uint32_t size = get_camera_metadata_size(metadata);
  bool success = result_metadata_queue->write(
      reinterpret_cast<const int8_t*>(metadata), size);
  if (!success) {
    ALOGW("%s: Writing to result metadata queue failed. (size=%u)",
          __FUNCTION__, size);
    return INVALID_OPERATION;
  }

  return OK;
}

// Try writing result metadata to result metadata queue. If failed, return
// the metadata to the caller in out_hal_metadata.
status_t TryWritingToResultMetadataQueue(
    std::unique_ptr<google_camera_hal::HalCameraMetadata> hal_metadata,
    AidlMessageQueue<int8_t, SynchronizedReadWrite>* result_metadata_queue,
    uint64_t* fmq_result_size,
    std::unique_ptr<google_camera_hal::HalCameraMetadata>* out_hal_metadata) {
  if (out_hal_metadata == nullptr) {
    ALOGE("%s: out_hal_metadata is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  *out_hal_metadata = std::move(hal_metadata);

  if (fmq_result_size == nullptr) {
    ALOGE("%s: fmq_result_size is nullptr", __FUNCTION__);
    return BAD_VALUE;
  }

  *fmq_result_size = 0;
  if (*out_hal_metadata == nullptr) {
    return OK;
  }

  camera_metadata_t* metadata = (*out_hal_metadata)->ReleaseCameraMetadata();
  // Temporarily use the raw metadata to write to metadata queue.
  status_t res = WriteToResultMetadataQueue(metadata, result_metadata_queue);
  *out_hal_metadata = google_camera_hal::HalCameraMetadata::Create(metadata);

  if (res != OK) {
    ALOGW("%s: Writing to result metadata queue failed: %s(%d)", __FUNCTION__,
          strerror(-res), res);
    return res;
  }

  *fmq_result_size = (*out_hal_metadata)->GetCameraMetadataSize();
  *out_hal_metadata = nullptr;
  return OK;
}

status_t ConvertToAidlResultMetadata(
    AidlMessageQueue<int8_t, SynchronizedReadWrite>* result_metadata_queue,
    std::unique_ptr<google_camera_hal::HalCameraMetadata> hal_metadata,
    std::vector<uint8_t>* aidl_metadata, uint64_t* fmq_result_size) {
  if (TryWritingToResultMetadataQueue(std::move(hal_metadata),
                                      result_metadata_queue, fmq_result_size,
                                      &hal_metadata) == OK) {
    return OK;
  }

  // If writing to metadata queue failed, attach the metadata to aidl_metadata.
  if (aidl_metadata == nullptr) {
    ALOGE("%s: aidl_metadata is nullptr", __FUNCTION__);
    return BAD_VALUE;
  }

  uint32_t metadata_size = hal_metadata->GetCameraMetadataSize();
  uint8_t* metadata_p =
      reinterpret_cast<uint8_t*>(hal_metadata->ReleaseCameraMetadata());
  // TODO: Do we reallly need to copy here ?
  aidl_metadata->assign(metadata_p, metadata_p + metadata_size);

  return OK;
}

status_t ConvertToAidlBufferStatus(google_camera_hal::BufferStatus hal_status,
                                   BufferStatus* aidl_status) {
  if (aidl_status == nullptr) {
    ALOGE("%s: aidl_status is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  switch (hal_status) {
    case google_camera_hal::BufferStatus::kOk:
      *aidl_status = BufferStatus::OK;
      break;
    case google_camera_hal::BufferStatus::kError:
      *aidl_status = BufferStatus::ERROR;
      break;
    default:
      ALOGE("%s: Unknown HAL buffer status: %u", __FUNCTION__, hal_status);
      return BAD_VALUE;
  }

  return OK;
}

aidl::android::hardware::common::NativeHandle makeToAidlIfNotNull(
    const native_handle_t* nh) {
  if (nh == nullptr) {
    return aidl::android::hardware::common::NativeHandle();
  }
  return makeToAidl(nh);
}

status_t ConvertToAidlStreamBuffer(
    const google_camera_hal::StreamBuffer& hal_buffer,
    StreamBuffer* aidl_buffer) {
  if (aidl_buffer == nullptr) {
    ALOGE("%s: aidl_buffer is nullptr", __FUNCTION__);
    return BAD_VALUE;
  }

  aidl_buffer->streamId = hal_buffer.stream_id;
  aidl_buffer->bufferId = hal_buffer.buffer_id;
  aidl_buffer->buffer = aidl::android::hardware::common::NativeHandle();

  status_t res =
      ConvertToAidlBufferStatus(hal_buffer.status, &aidl_buffer->status);
  if (res != OK) {
    ALOGE("%s: Converting to AIDL buffer status failed: %s(%d)", __FUNCTION__,
          strerror(-res), res);
    return res;
  }

  aidl_buffer->acquireFence = aidl::android::hardware::common::NativeHandle();
  aidl_buffer->releaseFence = makeToAidlIfNotNull(hal_buffer.release_fence);
  return OK;
}

status_t ConvertToAidlCaptureResultInternal(
    AidlMessageQueue<int8_t, SynchronizedReadWrite>* result_metadata_queue,
    google_camera_hal::CaptureResult* hal_result, CaptureResult* aidl_result) {
  if (aidl_result == nullptr) {
    ALOGE("%s: aidl_result is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  if (hal_result == nullptr) {
    ALOGE("%s: hal_result is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  aidl_result->frameNumber = hal_result->frame_number;

  status_t res = ConvertToAidlResultMetadata(
      result_metadata_queue, std::move(hal_result->result_metadata),
      &aidl_result->result.metadata, (uint64_t*)&aidl_result->fmqResultSize);
  if (res != OK) {
    ALOGE("%s: Converting to AIDL result metadata failed: %s(%d).",
          __FUNCTION__, strerror(-res), res);
    return res;
  }

  aidl_result->outputBuffers.resize(hal_result->output_buffers.size());
  for (uint32_t i = 0; i < aidl_result->outputBuffers.size(); i++) {
    res = ConvertToAidlStreamBuffer(hal_result->output_buffers[i],
                                    &aidl_result->outputBuffers[i]);
    if (res != OK) {
      ALOGE("%s: Converting to AIDL output stream buffer failed: %s(%d)",
            __FUNCTION__, strerror(-res), res);
      return res;
    }
  }

  uint32_t num_input_buffers = hal_result->input_buffers.size();
  if (num_input_buffers > 0) {
    if (num_input_buffers > 1) {
      ALOGW("%s: HAL result should not have more than 1 input buffer. (=%u)",
            __FUNCTION__, num_input_buffers);
    }

    res = ConvertToAidlStreamBuffer(hal_result->input_buffers[0],
                                    &aidl_result->inputBuffer);
    if (res != OK) {
      ALOGE("%s: Converting to AIDL input stream buffer failed: %s(%d)",
            __FUNCTION__, strerror(-res), res);
      return res;
    }
  } else {
    aidl_result->inputBuffer.streamId = -1;
  }

  aidl_result->partialResult = hal_result->partial_result;
  return OK;
}

status_t ConvertToAidlCaptureResult(
    AidlMessageQueue<int8_t, SynchronizedReadWrite>* result_metadata_queue,
    std::unique_ptr<google_camera_hal::CaptureResult> hal_result,
    CaptureResult* aidl_result) {
  if (aidl_result == nullptr) {
    ALOGE("%s: aidl_result is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  if (hal_result == nullptr) {
    ALOGE("%s: hal_result is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  status_t res = ConvertToAidlCaptureResultInternal(
      result_metadata_queue, hal_result.get(), aidl_result);
  if (res != OK) {
    ALOGE("%s: Converting to AIDL result internal failed: %s(%d).",
          __FUNCTION__, strerror(-res), res);
    return res;
  }

  uint32_t num_physical_metadata = hal_result->physical_metadata.size();
  aidl_result->physicalCameraMetadata.resize(num_physical_metadata);

  for (uint32_t i = 0; i < num_physical_metadata; i++) {
    aidl_result->physicalCameraMetadata[i].physicalCameraId =
        std::to_string(hal_result->physical_metadata[i].physical_camera_id);

    res = ConvertToAidlResultMetadata(
        result_metadata_queue,
        std::move(hal_result->physical_metadata[i].metadata),
        &aidl_result->physicalCameraMetadata[i].metadata.metadata,
        (uint64_t*)&aidl_result->physicalCameraMetadata[i].fmqMetadataSize);
    if (res != OK) {
      ALOGE("%s: Converting to AIDL physical metadata failed: %s(%d).",
            __FUNCTION__, strerror(-res), res);
      return res;
    }
  }

  return OK;
}

status_t ConvertToAidlErrorMessage(
    const google_camera_hal::ErrorMessage& hal_error, NotifyMsg* aidl_msg) {
  using Tag = aidl::android::hardware::camera::device::NotifyMsg::Tag;
  if (aidl_msg == nullptr) {
    ALOGE("%s: aidl_msg is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  ErrorMsg aidl_error;
  aidl_error.frameNumber = hal_error.frame_number;
  aidl_error.errorStreamId = hal_error.error_stream_id;

  switch (hal_error.error_code) {
    case google_camera_hal::ErrorCode::kErrorDevice:
      aidl_error.errorCode = ErrorCode::ERROR_DEVICE;
      break;
    case google_camera_hal::ErrorCode::kErrorRequest:
      aidl_error.errorCode = ErrorCode::ERROR_REQUEST;
      break;
    case google_camera_hal::ErrorCode::kErrorResult:
      aidl_error.errorCode = ErrorCode::ERROR_RESULT;
      break;
    case google_camera_hal::ErrorCode::kErrorBuffer:
      aidl_error.errorCode = ErrorCode::ERROR_BUFFER;
      break;
    default:
      ALOGE("%s: Unknown error code: %u", __FUNCTION__, hal_error.error_code);
      return BAD_VALUE;
  }
  aidl_msg->set<Tag::error>(aidl_error);
  return OK;
}

status_t ConvertToAidlShutterMessage(
    const google_camera_hal::ShutterMessage& hal_shutter, NotifyMsg* aidl_msg) {
  using Tag = aidl::android::hardware::camera::device::NotifyMsg::Tag;
  if (aidl_msg == nullptr) {
    ALOGE("%s: aidl_msg is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }
  ShutterMsg aidl_shutter;
  aidl_shutter.frameNumber = hal_shutter.frame_number;
  aidl_shutter.timestamp = hal_shutter.timestamp_ns;
  aidl_shutter.readoutTimestamp = hal_shutter.readout_timestamp_ns;
  aidl_msg->set<Tag::shutter>(aidl_shutter);
  return OK;
}

status_t ConverToAidlNotifyMessage(
    const google_camera_hal::NotifyMessage& hal_message,
    NotifyMsg* aidl_message) {
  if (aidl_message == nullptr) {
    ALOGE("%s: aidl_message is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  status_t res;
  switch (hal_message.type) {
    case google_camera_hal::MessageType::kError:
      res = ConvertToAidlErrorMessage(hal_message.message.error, aidl_message);
      if (res != OK) {
        ALOGE("%s: Converting to AIDL error message failed: %s(%d)",
              __FUNCTION__, strerror(-res), res);
        return res;
      }
      break;
    case google_camera_hal::MessageType::kShutter:
      res = ConvertToAidlShutterMessage(hal_message.message.shutter,
                                        aidl_message);
      if (res != OK) {
        ALOGE("%s: Converting to AIDL shutter message failed: %s(%d)",
              __FUNCTION__, strerror(-res), res);
        return res;
      }
      break;
    default:
      ALOGE("%s: Unknown message type: %u", __FUNCTION__, hal_message.type);
      return BAD_VALUE;
  }

  return OK;
}

status_t ConvertToAidlCameraDeviceStatus(
    google_camera_hal::CameraDeviceStatus hal_camera_device_status,
    CameraDeviceStatus* aidl_camera_device_status) {
  if (aidl_camera_device_status == nullptr) {
    ALOGE("%s: aidl_camera_device_status is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  switch (hal_camera_device_status) {
    case google_camera_hal::CameraDeviceStatus::kNotPresent:
      *aidl_camera_device_status = CameraDeviceStatus::NOT_PRESENT;
      break;
    case google_camera_hal::CameraDeviceStatus::kPresent:
      *aidl_camera_device_status = CameraDeviceStatus::PRESENT;
      break;
    case google_camera_hal::CameraDeviceStatus::kEnumerating:
      *aidl_camera_device_status = CameraDeviceStatus::ENUMERATING;
      break;
    default:
      ALOGE("%s: Unknown HAL camera device status: %u", __FUNCTION__,
            hal_camera_device_status);
      return BAD_VALUE;
  }

  return OK;
}

status_t ConvertToAidlTorchModeStatus(
    google_camera_hal::TorchModeStatus hal_torch_status,
    TorchModeStatus* aidl_torch_status) {
  if (aidl_torch_status == nullptr) {
    ALOGE("%s: aidl_torch_status is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  switch (hal_torch_status) {
    case google_camera_hal::TorchModeStatus::kNotAvailable:
      *aidl_torch_status = TorchModeStatus::NOT_AVAILABLE;
      break;
    case google_camera_hal::TorchModeStatus::kAvailableOff:
      *aidl_torch_status = TorchModeStatus::AVAILABLE_OFF;
      break;
    case google_camera_hal::TorchModeStatus::kAvailableOn:
      *aidl_torch_status = TorchModeStatus::AVAILABLE_ON;
      break;
    default:
      ALOGE("%s: Unknown HAL torch mode status: %u", __FUNCTION__,
            hal_torch_status);
      return BAD_VALUE;
  }

  return OK;
}

status_t ConvertToAidlBufferRequest(
    const std::vector<google_camera_hal::BufferRequest>& hal_buffer_requests,
    std::vector<BufferRequest>* aidl_buffer_requests) {
  if (aidl_buffer_requests == nullptr) {
    ALOGE("%s: aidl_buffer_request is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  aidl_buffer_requests->resize(hal_buffer_requests.size());
  for (uint32_t i = 0; i < hal_buffer_requests.size(); i++) {
    (*aidl_buffer_requests)[i].streamId = hal_buffer_requests[i].stream_id;
    (*aidl_buffer_requests)[i].numBuffersRequested =
        hal_buffer_requests[i].num_buffers_requested;
  }
  return OK;
}

status_t ConvertToHalBufferStatus(BufferStatus aidl_status,
                                  google_camera_hal::BufferStatus* hal_status) {
  if (hal_status == nullptr) {
    ALOGE("%s: hal_status is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  switch (aidl_status) {
    case BufferStatus::OK:
      *hal_status = google_camera_hal::BufferStatus::kOk;
      break;
    case BufferStatus::ERROR:
      *hal_status = google_camera_hal::BufferStatus::kError;
      break;
    default:
      ALOGE("%s: Unknown AIDL buffer status: %u", __FUNCTION__, aidl_status);
      return BAD_VALUE;
  }

  return OK;
}

bool IsAidlNativeHandleNull(const NativeHandle& handle) {
  return (handle.fds.size() == 0 && handle.ints.size() == 0);
}

native_handle_t* makeFromAidlIfNotNull(const NativeHandle& handle) {
  if (IsAidlNativeHandleNull(handle)) {
    return nullptr;
  }
  return makeFromAidl(handle);
}

// We have a handles_to_delete parameter since makeFromAidl creates a
// native_handle_t
status_t ConvertToHalStreamBuffer(
    const StreamBuffer& aidl_buffer, google_camera_hal::StreamBuffer* hal_buffer,
    std::vector<native_handle_t*>* handles_to_delete) {
  if (hal_buffer == nullptr || handles_to_delete == nullptr) {
    ALOGE("%s: hal_buffer / handles_to_delete is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  hal_buffer->stream_id = aidl_buffer.streamId;
  hal_buffer->buffer_id = aidl_buffer.bufferId;
  native_handle_t* buf_handle = makeFromAidlIfNotNull(aidl_buffer.buffer);
  hal_buffer->buffer = buf_handle;
  if (buf_handle != nullptr) {
    handles_to_delete->emplace_back(buf_handle);
  }

  status_t res =
      ConvertToHalBufferStatus(aidl_buffer.status, &hal_buffer->status);
  if (res != OK) {
    ALOGE("%s: Converting to HAL buffer status failed: %s(%d)", __FUNCTION__,
          strerror(-res), res);
    return res;
  }

  native_handle_t* acquire_handle =
      makeFromAidlIfNotNull(aidl_buffer.acquireFence);
  native_handle_t* release_handle =
      makeFromAidlIfNotNull(aidl_buffer.releaseFence);
  hal_buffer->acquire_fence = acquire_handle;
  hal_buffer->release_fence = release_handle;
  if (acquire_handle != nullptr) {
    handles_to_delete->emplace_back(acquire_handle);
  }

  if (release_handle != nullptr) {
    handles_to_delete->emplace_back(release_handle);
  }

  return OK;
}

status_t ConvertToHalMetadata(
    uint32_t message_queue_setting_size,
    AidlMessageQueue<int8_t, SynchronizedReadWrite>* request_metadata_queue,
    const std::vector<uint8_t>& request_settings,
    std::unique_ptr<google_camera_hal::HalCameraMetadata>* hal_metadata) {
  if (hal_metadata == nullptr) {
    ALOGE("%s: hal_metadata is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  const camera_metadata_t* metadata = nullptr;
  std::vector<int8_t> metadata_queue_settings;
  const size_t min_camera_metadata_size =
      calculate_camera_metadata_size(/*entry_count=*/0, /*data_count=*/0);

  if (message_queue_setting_size == 0) {
    // Use the settings in the request.
    if (request_settings.size() != 0) {
      if (request_settings.size() < min_camera_metadata_size) {
        ALOGE("%s: The size of request_settings is %zu, which is not valid",
              __FUNCTION__, request_settings.size());
        return BAD_VALUE;
      }

      metadata =
          reinterpret_cast<const camera_metadata_t*>(request_settings.data());

      size_t metadata_size = get_camera_metadata_size(metadata);
      if (metadata_size != request_settings.size()) {
        ALOGE(
            "%s: Mismatch between camera metadata size (%zu) and request "
            "setting size (%zu)",
            __FUNCTION__, metadata_size, request_settings.size());
        return BAD_VALUE;
      }
    }
  } else {
    // Read the settings from request metadata queue.
    if (request_metadata_queue == nullptr) {
      ALOGE("%s: request_metadata_queue is nullptr", __FUNCTION__);
      return BAD_VALUE;
    }
    if (message_queue_setting_size < min_camera_metadata_size) {
      ALOGE("%s: invalid message queue setting size: %u", __FUNCTION__,
            message_queue_setting_size);
      return BAD_VALUE;
    }

    metadata_queue_settings.resize(message_queue_setting_size);
    bool success = request_metadata_queue->read(metadata_queue_settings.data(),
                                                message_queue_setting_size);
    if (!success) {
      ALOGE("%s: Failed to read from request metadata queue.", __FUNCTION__);
      return BAD_VALUE;
    }

    metadata = reinterpret_cast<const camera_metadata_t*>(
        metadata_queue_settings.data());

    size_t metadata_size = get_camera_metadata_size(metadata);
    if (metadata_size != message_queue_setting_size) {
      ALOGE(
          "%s: Mismatch between camera metadata size (%zu) and message "
          "queue setting size (%u)",
          __FUNCTION__, metadata_size, message_queue_setting_size);
      return BAD_VALUE;
    }
  }

  if (metadata == nullptr) {
    *hal_metadata = nullptr;
    return OK;
  }

  // Validates the injected metadata structure. This prevents memory access
  // violation that could be introduced by malformed metadata.
  // (b/236688120) In general we trust metadata sent from Framework, but this is
  // to defend an exploit chain that skips Framework's validation.
  if (validate_camera_metadata_structure(metadata, /*expected_size=*/NULL) !=
      OK) {
    ALOGE("%s: Failed to validate the metadata structure", __FUNCTION__);
    return BAD_VALUE;
  }

  *hal_metadata = google_camera_hal::HalCameraMetadata::Clone(metadata);
  return OK;
}

status_t ConvertToHalCaptureRequest(
    const CaptureRequest& aidl_request,
    AidlMessageQueue<int8_t, SynchronizedReadWrite>* request_metadata_queue,
    google_camera_hal::CaptureRequest* hal_request,
    std::vector<native_handle_t*>* handles_to_delete) {
  if (hal_request == nullptr) {
    ALOGE("%s: hal_request is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  hal_request->frame_number = aidl_request.frameNumber;

  status_t res = ConvertToHalMetadata(
      aidl_request.fmqSettingsSize, request_metadata_queue,
      aidl_request.settings.metadata, &hal_request->settings);
  if (res != OK) {
    ALOGE("%s: Converting metadata failed: %s(%d)", __FUNCTION__,
          strerror(-res), res);
    return res;
  }

  google_camera_hal::StreamBuffer hal_buffer = {};
  if (!IsAidlNativeHandleNull(aidl_request.inputBuffer.buffer)) {
    res = ConvertToHalStreamBuffer(aidl_request.inputBuffer, &hal_buffer,
                                   handles_to_delete);
    if (res != OK) {
      ALOGE("%s: Converting hal stream buffer failed: %s(%d)", __FUNCTION__,
            strerror(-res), res);
      return res;
    }

    hal_request->input_buffers.push_back(hal_buffer);
    hal_request->input_width = aidl_request.inputWidth;
    hal_request->input_height = aidl_request.inputHeight;
  }

  for (auto& buffer : aidl_request.outputBuffers) {
    hal_buffer = {};
    status_t res =
        ConvertToHalStreamBuffer(buffer, &hal_buffer, handles_to_delete);
    if (res != OK) {
      ALOGE("%s: Converting hal stream buffer failed: %s(%d)", __FUNCTION__,
            strerror(-res), res);
      return res;
    }

    hal_request->output_buffers.push_back(hal_buffer);
  }

  for (auto aidl_physical_settings : aidl_request.physicalCameraSettings) {
    std::unique_ptr<google_camera_hal::HalCameraMetadata> hal_physical_settings;
    res = ConvertToHalMetadata(
        aidl_physical_settings.fmqSettingsSize, request_metadata_queue,
        aidl_physical_settings.settings.metadata, &hal_physical_settings);
    if (res != OK) {
      ALOGE("%s: Converting to HAL metadata failed: %s(%d)", __FUNCTION__,
            strerror(-res), res);
      return res;
    }

    uint32_t camera_id = std::stoul(aidl_physical_settings.physicalCameraId);
    hal_request->physical_camera_settings.emplace(
        camera_id, std::move(hal_physical_settings));
  }

  return OK;
}

status_t ConvertToHalBufferCaches(
    const std::vector<BufferCache>& aidl_buffer_caches,
    std::vector<google_camera_hal::BufferCache>* hal_buffer_caches) {
  if (hal_buffer_caches == nullptr) {
    ALOGE("%s: hal_buffer_caches is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  for (auto aidl_cache : aidl_buffer_caches) {
    google_camera_hal::BufferCache hal_cache;
    hal_cache.stream_id = aidl_cache.streamId;
    hal_cache.buffer_id = aidl_cache.bufferId;

    hal_buffer_caches->push_back(hal_cache);
  }

  return OK;
}

status_t ConvertToHalStreamConfigurationMode(
    StreamConfigurationMode aidl_mode,
    google_camera_hal::StreamConfigurationMode* hal_mode) {
  if (hal_mode == nullptr) {
    ALOGE("%s: hal_mode is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  switch (aidl_mode) {
    case StreamConfigurationMode::NORMAL_MODE:
      *hal_mode = google_camera_hal::StreamConfigurationMode::kNormal;
      break;
    case StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE:
      *hal_mode =
          google_camera_hal::StreamConfigurationMode::kConstrainedHighSpeed;
      break;
    default:
      ALOGE("%s: Unknown configuration mode %u", __FUNCTION__, aidl_mode);
      return BAD_VALUE;
  }

  return OK;
}

static bool sensorPixelModeContains(const Stream& aidl_stream, uint32_t key) {
  using aidl::android::hardware::camera::metadata::SensorPixelMode;
  for (auto& i : aidl_stream.sensorPixelModesUsed) {
    if (i == static_cast<SensorPixelMode>(key)) {
      return true;
    }
  }
  return false;
}

void FixSensorPixelModesInStreamConfig(
    StreamConfiguration* out_aidl_stream_config) {
  if (out_aidl_stream_config == nullptr) {
    ALOGE("%s: input stream config is NULL", __FUNCTION__);
    return;
  }

  // Get the sensor pixel modes in the stream config, do one pass and check if
  // default is present in all.
  using SensorPixelMode =
      aidl::android::hardware::camera::metadata::SensorPixelMode;
  for (const auto& stream : out_aidl_stream_config->streams) {
    const auto& sensorPixelModes = stream.sensorPixelModesUsed;
    if ((std::count(sensorPixelModes.begin(), sensorPixelModes.end(),
                    static_cast<SensorPixelMode>(
                        ANDROID_SENSOR_PIXEL_MODE_DEFAULT)) == 0)) {
      return;
    }
  }

  // All of them contain DEFAULT, just override them to be default only.
  for (auto& stream : out_aidl_stream_config->streams) {
    stream.sensorPixelModesUsed.clear();
    stream.sensorPixelModesUsed.push_back(
        static_cast<SensorPixelMode>(ANDROID_SENSOR_PIXEL_MODE_DEFAULT));
  }
}

status_t ConvertToHalStreamConfig(
    const StreamConfiguration& aidl_stream_config,
    google_camera_hal::StreamConfiguration* hal_stream_config) {
  if (hal_stream_config == nullptr) {
    ALOGE("%s: hal_stream_config is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  status_t res;

  for (auto aidl_stream : aidl_stream_config.streams) {
    google_camera_hal::Stream hal_stream;
    res = ConvertToHalStream(aidl_stream, &hal_stream);
    if (res != OK) {
      ALOGE("%s: Converting to HAL stream failed: %s(%d)", __FUNCTION__,
            strerror(-res), res);
      return res;
    }
    hal_stream_config->streams.push_back(hal_stream);
  }

  res = ConvertToHalStreamConfigurationMode(aidl_stream_config.operationMode,
                                            &hal_stream_config->operation_mode);
  if (res != OK) {
    ALOGE("%s: Converting to HAL opeation mode failed: %s(%d)", __FUNCTION__,
          strerror(-res), res);
    return res;
  }

  res = ConvertToHalMetadata(0, nullptr,
                             aidl_stream_config.sessionParams.metadata,
                             &hal_stream_config->session_params);
  if (res != OK) {
    ALOGE("%s: Converting to HAL metadata failed: %s(%d)", __FUNCTION__,
          strerror(-res), res);
    return res;
  }

  hal_stream_config->stream_config_counter =
      aidl_stream_config.streamConfigCounter;
  hal_stream_config->multi_resolution_input_image =
      aidl_stream_config.multiResolutionInputImage;
  hal_stream_config->log_id = aidl_stream_config.logId;

  return OK;
}

status_t ConvertToHalStreamType(StreamType aidl_stream_type,
                                google_camera_hal::StreamType* hal_stream_type) {
  if (hal_stream_type == nullptr) {
    ALOGE("%s: hal_stream_type is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  switch (aidl_stream_type) {
    case StreamType::OUTPUT:
      *hal_stream_type = google_camera_hal::StreamType::kOutput;
      break;
    case StreamType::INPUT:
      *hal_stream_type = google_camera_hal::StreamType::kInput;
      break;
    default:
      ALOGE("%s: Unknown stream type: %u", __FUNCTION__, aidl_stream_type);
      return BAD_VALUE;
  }

  return OK;
}

status_t ConvertToHalStreamRotation(
    StreamRotation aidl_stream_rotation,
    google_camera_hal::StreamRotation* hal_stream_rotation) {
  if (hal_stream_rotation == nullptr) {
    ALOGE("%s: hal_stream_rotation is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  switch (aidl_stream_rotation) {
    case StreamRotation::ROTATION_0:
      *hal_stream_rotation = google_camera_hal::StreamRotation::kRotation0;
      break;
    case StreamRotation::ROTATION_90:
      *hal_stream_rotation = google_camera_hal::StreamRotation::kRotation90;
      break;
    case StreamRotation::ROTATION_180:
      *hal_stream_rotation = google_camera_hal::StreamRotation::kRotation180;
      break;
    case StreamRotation::ROTATION_270:
      *hal_stream_rotation = google_camera_hal::StreamRotation::kRotation270;
      break;
    default:
      ALOGE("%s: Unknown stream rotation: %u", __FUNCTION__,
            aidl_stream_rotation);
      return BAD_VALUE;
  }

  return OK;
}

status_t ConvertToHalStream(const Stream& aidl_stream,
                            google_camera_hal::Stream* hal_stream) {
  if (hal_stream == nullptr) {
    ALOGE("%s: hal_stream is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  *hal_stream = {};

  hal_stream->id = aidl_stream.id;

  status_t res =
      ConvertToHalStreamType(aidl_stream.streamType, &hal_stream->stream_type);
  if (res != OK) {
    ALOGE("%s: Converting to HAL stream type failed: %s(%d)", __FUNCTION__,
          strerror(-res), res);
    return res;
  }

  hal_stream->width = aidl_stream.width;
  hal_stream->height = aidl_stream.height;
  hal_stream->format = (android_pixel_format_t)aidl_stream.format;
  hal_stream->usage = (uint64_t)aidl_stream.usage;
  hal_stream->data_space = (android_dataspace_t)aidl_stream.dataSpace;

  res = ConvertToHalStreamRotation(aidl_stream.rotation, &hal_stream->rotation);
  if (res != OK) {
    ALOGE("%s: Converting to HAL stream rotation failed: %s(%d)", __FUNCTION__,
          strerror(-res), res);
    return res;
  }

  if (aidl_stream.physicalCameraId.empty()) {
    hal_stream->is_physical_camera_stream = false;
  } else {
    hal_stream->is_physical_camera_stream = true;
    hal_stream->physical_camera_id = std::stoul(aidl_stream.physicalCameraId);
  }

  hal_stream->buffer_size = aidl_stream.bufferSize;
  hal_stream->group_id = aidl_stream.groupId;

  hal_stream->intended_for_max_resolution_mode = sensorPixelModeContains(
      aidl_stream, ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION);
  hal_stream->intended_for_default_resolution_mode =
      aidl_stream.sensorPixelModesUsed.size() > 0
          ? sensorPixelModeContains(aidl_stream,
                                    ANDROID_SENSOR_PIXEL_MODE_DEFAULT)
          : true;
  hal_stream->dynamic_profile =
      static_cast<DynamicRangeProfile>(aidl_stream.dynamicRangeProfile);
  hal_stream->color_space =
      static_cast<ColorSpaceProfile>(aidl_stream.colorSpace);

  hal_stream->use_case =
      static_cast<camera_metadata_enum_android_scaler_available_stream_use_cases>(
          aidl_stream.useCase);

  return OK;
}

status_t ConvertToHalBufferRequestStatus(
    const BufferRequestStatus& aidl_buffer_request_status,
    google_camera_hal::BufferRequestStatus* hal_buffer_request_status) {
  if (hal_buffer_request_status == nullptr) {
    ALOGE("%s: hal_buffer_request_status is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  switch (aidl_buffer_request_status) {
    case BufferRequestStatus::OK:
      *hal_buffer_request_status = google_camera_hal::BufferRequestStatus::kOk;
      break;
    case BufferRequestStatus::FAILED_PARTIAL:
      *hal_buffer_request_status =
          google_camera_hal::BufferRequestStatus::kFailedPartial;
      break;
    case BufferRequestStatus::FAILED_CONFIGURING:
      *hal_buffer_request_status =
          google_camera_hal::BufferRequestStatus::kFailedConfiguring;
      break;
    case BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS:
      *hal_buffer_request_status =
          google_camera_hal::BufferRequestStatus::kFailedIllegalArgs;
      break;
    case BufferRequestStatus::FAILED_UNKNOWN:
      *hal_buffer_request_status =
          google_camera_hal::BufferRequestStatus::kFailedUnknown;
      break;
    default:
      ALOGE("%s: Failed unknown buffer request error code %d", __FUNCTION__,
            aidl_buffer_request_status);
      return BAD_VALUE;
  }

  return OK;
}

status_t ConvertToHalBufferReturnStatus(
    const StreamBufferRet& aidl_stream_buffer_return,
    google_camera_hal::BufferReturn* hal_buffer_return) {
  using Tag = aidl::android::hardware::camera::device::StreamBuffersVal::Tag;
  if (hal_buffer_return == nullptr) {
    ALOGE("%s: hal_buffer_return is nullptr.", __FUNCTION__);
    return BAD_VALUE;
  }

  if (aidl_stream_buffer_return.val.getTag() == Tag::error) {
    switch (aidl_stream_buffer_return.val.get<Tag::error>()) {
      case StreamBufferRequestError::NO_BUFFER_AVAILABLE:
        hal_buffer_return->val.error =
            google_camera_hal::StreamBufferRequestError::kNoBufferAvailable;
        break;
      case StreamBufferRequestError::MAX_BUFFER_EXCEEDED:
        hal_buffer_return->val.error =
            google_camera_hal::StreamBufferRequestError::kMaxBufferExceeded;
        break;
      case StreamBufferRequestError::STREAM_DISCONNECTED:
        hal_buffer_return->val.error =
            google_camera_hal::StreamBufferRequestError::kStreamDisconnected;
        break;
      case StreamBufferRequestError::UNKNOWN_ERROR:
        hal_buffer_return->val.error =
            google_camera_hal::StreamBufferRequestError::kUnknownError;
        break;
      default:
        ALOGE("%s: Unknown StreamBufferRequestError %d", __FUNCTION__,
              aidl_stream_buffer_return.val.get<Tag::error>());
        return BAD_VALUE;
    }
  } else {
    hal_buffer_return->val.error =
        google_camera_hal::StreamBufferRequestError::kOk;
  }

  return OK;
}

status_t ConvertToHalDeviceState(
    int64_t aidl_device_state,
    google_camera_hal::DeviceState& hal_device_state) {
  switch (aidl_device_state) {
    case ICameraProvider::DEVICE_STATE_NORMAL:
      hal_device_state = google_camera_hal::DeviceState::kNormal;
      break;
    case ICameraProvider::DEVICE_STATE_BACK_COVERED:
      hal_device_state = google_camera_hal::DeviceState::kBackCovered;
      break;
    case ICameraProvider::DEVICE_STATE_FRONT_COVERED:
      hal_device_state = google_camera_hal::DeviceState::kFrontCovered;
      break;
    case ICameraProvider::DEVICE_STATE_FOLDED:
      hal_device_state = google_camera_hal::DeviceState::kFolded;
      break;
    default:
      ALOGE("%s: Failed unknown device state", __FUNCTION__);
      return BAD_VALUE;
  }

  return OK;
}

}  // namespace aidl_utils
}  // namespace implementation
}  // namespace camera
}  // namespace hardware
}  // namespace android