• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2011-2018, 2020 The Linux Foundation. All rights reserved.
3  * Not a Contribution
4  *
5  * Copyright (C) 2010 The Android Open Source Project
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 
20 #define DEBUG 0
21 
22 #include "gr_buf_mgr.h"
23 
24 #include <QtiGralloc.h>
25 #include <QtiGrallocPriv.h>
26 #include <gralloctypes/Gralloc4.h>
27 #include <sys/mman.h>
28 
29 #include <algorithm>
30 #include <iomanip>
31 #include <sstream>
32 #include <string>
33 #include <utility>
34 #include <vector>
35 
36 #include "gr_adreno_info.h"
37 #include "gr_buf_descriptor.h"
38 #include "gr_priv_handle.h"
39 #include "gr_utils.h"
40 #include "qdMetaData.h"
41 #include "qd_utils.h"
42 
43 namespace gralloc {
44 
45 using aidl::android::hardware::graphics::common::BlendMode;
46 using aidl::android::hardware::graphics::common::Cta861_3;
47 using aidl::android::hardware::graphics::common::Dataspace;
48 using aidl::android::hardware::graphics::common::PlaneLayout;
49 using aidl::android::hardware::graphics::common::PlaneLayoutComponent;
50 using aidl::android::hardware::graphics::common::Rect;
51 using aidl::android::hardware::graphics::common::Smpte2086;
52 using aidl::android::hardware::graphics::common::StandardMetadataType;
53 using aidl::android::hardware::graphics::common::XyColor;
54 using ::android::hardware::graphics::common::V1_2::PixelFormat;
55 
GetBufferInfo(const BufferDescriptor & descriptor)56 static BufferInfo GetBufferInfo(const BufferDescriptor &descriptor) {
57   return BufferInfo(descriptor.GetWidth(), descriptor.GetHeight(), descriptor.GetFormat(),
58                     descriptor.GetUsage());
59 }
60 
getMetaDataSize(uint64_t reserved_region_size)61 static uint64_t getMetaDataSize(uint64_t reserved_region_size) {
62 // Only include the reserved region size when using Metadata_t V2
63 #ifndef METADATA_V2
64   reserved_region_size = 0;
65 #endif
66   return static_cast<uint64_t>(ROUND_UP_PAGESIZE(sizeof(MetaData_t) + reserved_region_size));
67 }
68 
unmapAndReset(private_handle_t * handle,uint64_t reserved_region_size=0)69 static void unmapAndReset(private_handle_t *handle, uint64_t reserved_region_size = 0) {
70   if (private_handle_t::validate(handle) == 0 && handle->base_metadata) {
71     munmap(reinterpret_cast<void *>(handle->base_metadata), getMetaDataSize(reserved_region_size));
72     handle->base_metadata = 0;
73   }
74 }
75 
validateAndMap(private_handle_t * handle,uint64_t reserved_region_size=0)76 static int validateAndMap(private_handle_t *handle, uint64_t reserved_region_size = 0) {
77   if (private_handle_t::validate(handle)) {
78     ALOGE("%s: Private handle is invalid - handle:%p", __func__, handle);
79     return -1;
80   }
81   if (handle->fd_metadata < 0) {
82     // Silently return, metadata cannot be used
83     return -1;
84   }
85 
86   if (!handle->base_metadata) {
87     uint64_t size = getMetaDataSize(reserved_region_size);
88     void *base = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, handle->fd_metadata, 0);
89     if (base == reinterpret_cast<void *>(MAP_FAILED)) {
90       ALOGE("%s: metadata mmap failed - handle:%p fd: %d err: %s", __func__, handle,
91             handle->fd_metadata, strerror(errno));
92       return -1;
93     }
94     handle->base_metadata = (uintptr_t)base;
95 #ifdef METADATA_V2
96     // The allocator process gets the reserved region size from the BufferDescriptor.
97     // When importing to another process, the reserved size is unknown until mapping the metadata,
98     // hence the re-mapping below
99     auto metadata = reinterpret_cast<MetaData_t*>(handle->base_metadata);
100     if (reserved_region_size == 0 && metadata->reservedSize) {
101         size = getMetaDataSize(metadata->reservedSize);
102         unmapAndReset(handle);
103         void *new_base = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED,
104                               handle->fd_metadata, 0);
105         if (new_base == reinterpret_cast<void*>(MAP_FAILED)) {
106           ALOGE("%s: metadata mmap failed - handle:%p fd: %d err: %s",
107                 __func__, handle, handle->fd_metadata, strerror(errno));
108           return -1;
109         }
110         handle->base_metadata = (uintptr_t)new_base;
111     }
112 #endif
113   }
114   return 0;
115 }
116 
dataspaceToColorMetadata(Dataspace dataspace,ColorMetaData * color_metadata)117 static Error dataspaceToColorMetadata(Dataspace dataspace, ColorMetaData *color_metadata) {
118   ColorMetaData out;
119   uint32_t primaries = (uint32_t)dataspace & (uint32_t)Dataspace::STANDARD_MASK;
120   uint32_t transfer = (uint32_t)dataspace & (uint32_t)Dataspace::TRANSFER_MASK;
121   uint32_t range = (uint32_t)dataspace & (uint32_t)Dataspace::RANGE_MASK;
122 
123   switch (primaries) {
124     case (uint32_t)Dataspace::STANDARD_BT709:
125       out.colorPrimaries = ColorPrimaries_BT709_5;
126       break;
127     // TODO(tbalacha): verify this is equivalent
128     case (uint32_t)Dataspace::STANDARD_BT470M:
129       out.colorPrimaries = ColorPrimaries_BT470_6M;
130       break;
131     case (uint32_t)Dataspace::STANDARD_BT601_625:
132     case (uint32_t)Dataspace::STANDARD_BT601_625_UNADJUSTED:
133       out.colorPrimaries = ColorPrimaries_BT601_6_625;
134       break;
135     case (uint32_t)Dataspace::STANDARD_BT601_525:
136     case (uint32_t)Dataspace::STANDARD_BT601_525_UNADJUSTED:
137       out.colorPrimaries = ColorPrimaries_BT601_6_525;
138       break;
139     case (uint32_t)Dataspace::STANDARD_FILM:
140       out.colorPrimaries = ColorPrimaries_GenericFilm;
141       break;
142     case (uint32_t)Dataspace::STANDARD_BT2020:
143       out.colorPrimaries = ColorPrimaries_BT2020;
144       break;
145     case (uint32_t)Dataspace::STANDARD_ADOBE_RGB:
146       out.colorPrimaries = ColorPrimaries_AdobeRGB;
147       break;
148     case (uint32_t)Dataspace::STANDARD_DCI_P3:
149       out.colorPrimaries = ColorPrimaries_DCIP3;
150       break;
151     default:
152       return Error::UNSUPPORTED;
153       /*
154        ColorPrimaries_SMPTE_240M;
155        ColorPrimaries_SMPTE_ST428;
156        ColorPrimaries_EBU3213;
157       */
158   }
159 
160   switch (transfer) {
161     case (uint32_t)Dataspace::TRANSFER_SRGB:
162       out.transfer = Transfer_sRGB;
163       break;
164     case (uint32_t)Dataspace::TRANSFER_GAMMA2_2:
165       out.transfer = Transfer_Gamma2_2;
166       break;
167     case (uint32_t)Dataspace::TRANSFER_GAMMA2_8:
168       out.transfer = Transfer_Gamma2_8;
169       break;
170     case (uint32_t)Dataspace::TRANSFER_SMPTE_170M:
171       out.transfer = Transfer_SMPTE_170M;
172       break;
173     case (uint32_t)Dataspace::TRANSFER_LINEAR:
174       out.transfer = Transfer_Linear;
175       break;
176     case (uint32_t)Dataspace::TRANSFER_HLG:
177       out.transfer = Transfer_HLG;
178       break;
179     default:
180       return Error::UNSUPPORTED;
181       /*
182       Transfer_SMPTE_240M
183       Transfer_Log
184       Transfer_Log_Sqrt
185       Transfer_XvYCC
186       Transfer_BT1361
187       Transfer_sYCC
188       Transfer_BT2020_2_1
189       Transfer_BT2020_2_2
190       Transfer_SMPTE_ST2084
191       Transfer_ST_428
192       */
193   }
194 
195   switch (range) {
196     case (uint32_t)Dataspace::RANGE_FULL:
197       out.range = Range_Full;
198       break;
199     case (uint32_t)Dataspace::RANGE_LIMITED:
200       out.range = Range_Limited;
201       break;
202     case (uint32_t)Dataspace::RANGE_EXTENDED:
203       out.range = Range_Extended;
204       break;
205     default:
206       return Error::UNSUPPORTED;
207   }
208 
209   color_metadata->colorPrimaries = out.colorPrimaries;
210   color_metadata->transfer = out.transfer;
211   color_metadata->range = out.range;
212   return Error::NONE;
213 }
colorMetadataToDataspace(ColorMetaData color_metadata,Dataspace * dataspace)214 static Error colorMetadataToDataspace(ColorMetaData color_metadata, Dataspace *dataspace) {
215   Dataspace primaries, transfer, range = Dataspace::UNKNOWN;
216 
217   switch (color_metadata.colorPrimaries) {
218     case ColorPrimaries_BT709_5:
219       primaries = Dataspace::STANDARD_BT709;
220       break;
221     // TODO(tbalacha): verify this is equivalent
222     case ColorPrimaries_BT470_6M:
223       primaries = Dataspace::STANDARD_BT470M;
224       break;
225     case ColorPrimaries_BT601_6_625:
226       primaries = Dataspace::STANDARD_BT601_625;
227       break;
228     case ColorPrimaries_BT601_6_525:
229       primaries = Dataspace::STANDARD_BT601_525;
230       break;
231     case ColorPrimaries_GenericFilm:
232       primaries = Dataspace::STANDARD_FILM;
233       break;
234     case ColorPrimaries_BT2020:
235       primaries = Dataspace::STANDARD_BT2020;
236       break;
237     case ColorPrimaries_AdobeRGB:
238       primaries = Dataspace::STANDARD_ADOBE_RGB;
239       break;
240     case ColorPrimaries_DCIP3:
241       primaries = Dataspace::STANDARD_DCI_P3;
242       break;
243     default:
244       return Error::UNSUPPORTED;
245       /*
246        ColorPrimaries_SMPTE_240M;
247        ColorPrimaries_SMPTE_ST428;
248        ColorPrimaries_EBU3213;
249       */
250   }
251 
252   switch (color_metadata.transfer) {
253     case Transfer_sRGB:
254       transfer = Dataspace::TRANSFER_SRGB;
255       break;
256     case Transfer_Gamma2_2:
257       transfer = Dataspace::TRANSFER_GAMMA2_2;
258       break;
259     case Transfer_Gamma2_8:
260       transfer = Dataspace::TRANSFER_GAMMA2_8;
261       break;
262     case Transfer_SMPTE_170M:
263       transfer = Dataspace::TRANSFER_SMPTE_170M;
264       break;
265     case Transfer_Linear:
266       transfer = Dataspace::TRANSFER_LINEAR;
267       break;
268     case Transfer_HLG:
269       transfer = Dataspace::TRANSFER_HLG;
270       break;
271     default:
272       return Error::UNSUPPORTED;
273       /*
274       Transfer_SMPTE_240M
275       Transfer_Log
276       Transfer_Log_Sqrt
277       Transfer_XvYCC
278       Transfer_BT1361
279       Transfer_sYCC
280       Transfer_BT2020_2_1
281       Transfer_BT2020_2_2
282       Transfer_SMPTE_ST2084
283       Transfer_ST_428
284       */
285   }
286 
287   switch (color_metadata.range) {
288     case Range_Full:
289       range = Dataspace::RANGE_FULL;
290       break;
291     case Range_Limited:
292       range = Dataspace::RANGE_LIMITED;
293       break;
294     case Range_Extended:
295       range = Dataspace::RANGE_EXTENDED;
296       break;
297     default:
298       return Error::UNSUPPORTED;
299   }
300 
301   *dataspace = (Dataspace)((uint32_t)primaries | (uint32_t)transfer | (uint32_t)range);
302   return Error::NONE;
303 }
304 
getComponentSizeAndOffset(int32_t format,PlaneLayoutComponent & comp)305 static Error getComponentSizeAndOffset(int32_t format, PlaneLayoutComponent &comp) {
306   switch (format) {
307     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RGBA_8888):
308     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RGBX_8888):
309     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RGB_888):
310       comp.sizeInBits = 8;
311       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
312         comp.offsetInBits = 0;
313       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
314         comp.offsetInBits = 8;
315       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
316         comp.offsetInBits = 16;
317       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_A.value &&
318                  format != HAL_PIXEL_FORMAT_RGB_888) {
319         comp.offsetInBits = 24;
320       } else {
321         return Error::BAD_VALUE;
322       }
323       break;
324     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RGB_565):
325       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
326         comp.offsetInBits = 0;
327         comp.sizeInBits = 5;
328       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
329         comp.offsetInBits = 5;
330         comp.sizeInBits = 6;
331       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
332         comp.offsetInBits = 11;
333         comp.sizeInBits = 5;
334       } else {
335         return Error::BAD_VALUE;
336       }
337       break;
338     case static_cast<int32_t>(HAL_PIXEL_FORMAT_BGR_565):
339       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
340         comp.offsetInBits = 11;
341         comp.sizeInBits = 5;
342       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
343         comp.offsetInBits = 5;
344         comp.sizeInBits = 6;
345       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
346         comp.offsetInBits = 0;
347         comp.sizeInBits = 5;
348       } else {
349         return Error::BAD_VALUE;
350       }
351       break;
352     case static_cast<int32_t>(HAL_PIXEL_FORMAT_BGRA_8888):
353     case static_cast<int32_t>(HAL_PIXEL_FORMAT_BGRX_8888):
354     case static_cast<int32_t>(HAL_PIXEL_FORMAT_BGR_888):
355       comp.sizeInBits = 8;
356       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
357         comp.offsetInBits = 16;
358       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
359         comp.offsetInBits = 8;
360       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
361         comp.offsetInBits = 0;
362       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_A.value &&
363                  format != HAL_PIXEL_FORMAT_BGR_888) {
364         comp.offsetInBits = 24;
365       } else {
366         return Error::BAD_VALUE;
367       }
368       break;
369     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RGBA_5551):
370       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
371         comp.sizeInBits = 5;
372         comp.offsetInBits = 0;
373       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
374         comp.sizeInBits = 5;
375         comp.offsetInBits = 5;
376       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
377         comp.sizeInBits = 5;
378         comp.offsetInBits = 10;
379       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_A.value) {
380         comp.sizeInBits = 1;
381         comp.offsetInBits = 15;
382       } else {
383         return Error::BAD_VALUE;
384       }
385       break;
386     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RGBA_4444):
387       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
388         comp.sizeInBits = 4;
389         comp.offsetInBits = 0;
390       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
391         comp.sizeInBits = 4;
392         comp.offsetInBits = 4;
393       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
394         comp.sizeInBits = 4;
395         comp.offsetInBits = 8;
396       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_A.value) {
397         comp.sizeInBits = 4;
398         comp.offsetInBits = 12;
399       } else {
400         return Error::BAD_VALUE;
401       }
402       break;
403     case static_cast<int32_t>(HAL_PIXEL_FORMAT_R_8):
404     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RG_88):
405       comp.sizeInBits = 8;
406       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
407         comp.offsetInBits = 0;
408       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value &&
409                  format != HAL_PIXEL_FORMAT_R_8) {
410         comp.offsetInBits = 8;
411       } else {
412         return Error::BAD_VALUE;
413       }
414       break;
415     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RGBA_1010102):
416     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RGBX_1010102):
417       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
418         comp.sizeInBits = 10;
419         comp.offsetInBits = 0;
420       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
421         comp.sizeInBits = 10;
422         comp.offsetInBits = 10;
423       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
424         comp.sizeInBits = 10;
425         comp.offsetInBits = 20;
426       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_A.value) {
427         comp.sizeInBits = 2;
428         comp.offsetInBits = 30;
429       } else {
430         return Error::BAD_VALUE;
431       }
432       break;
433     case static_cast<int32_t>(HAL_PIXEL_FORMAT_ARGB_2101010):
434     case static_cast<int32_t>(HAL_PIXEL_FORMAT_XRGB_2101010):
435       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
436         comp.sizeInBits = 10;
437         comp.offsetInBits = 2;
438       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
439         comp.sizeInBits = 10;
440         comp.offsetInBits = 12;
441       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
442         comp.sizeInBits = 10;
443         comp.offsetInBits = 22;
444       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_A.value) {
445         comp.sizeInBits = 2;
446         comp.offsetInBits = 0;
447       } else {
448         return Error::BAD_VALUE;
449       }
450       break;
451     case static_cast<int32_t>(HAL_PIXEL_FORMAT_BGRA_1010102):
452     case static_cast<int32_t>(HAL_PIXEL_FORMAT_BGRX_1010102):
453       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
454         comp.sizeInBits = 10;
455         comp.offsetInBits = 20;
456       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
457         comp.sizeInBits = 10;
458         comp.offsetInBits = 10;
459       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
460         comp.sizeInBits = 10;
461         comp.offsetInBits = 0;
462       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_A.value) {
463         comp.sizeInBits = 2;
464         comp.offsetInBits = 30;
465       } else {
466         return Error::BAD_VALUE;
467       }
468       break;
469     case static_cast<int32_t>(HAL_PIXEL_FORMAT_ABGR_2101010):
470     case static_cast<int32_t>(HAL_PIXEL_FORMAT_XBGR_2101010):
471       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
472         comp.sizeInBits = 10;
473         comp.offsetInBits = 22;
474       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
475         comp.sizeInBits = 10;
476         comp.offsetInBits = 12;
477       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
478         comp.sizeInBits = 10;
479         comp.offsetInBits = 2;
480       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_A.value) {
481         comp.sizeInBits = 2;
482         comp.offsetInBits = 0;
483       } else {
484         return Error::BAD_VALUE;
485       }
486       break;
487     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RGBA_FP16):
488       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_R.value) {
489         comp.sizeInBits = 16;
490         comp.offsetInBits = 0;
491       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_G.value) {
492         comp.sizeInBits = 16;
493         comp.offsetInBits = 16;
494       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_B.value) {
495         comp.sizeInBits = 16;
496         comp.offsetInBits = 32;
497       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_A.value) {
498         comp.sizeInBits = 16;
499         comp.offsetInBits = 48;
500       } else {
501         return Error::BAD_VALUE;
502       }
503       break;
504     case static_cast<int32_t>(HAL_PIXEL_FORMAT_YCbCr_420_SP):
505     case static_cast<int32_t>(HAL_PIXEL_FORMAT_YCbCr_422_SP):
506     case static_cast<int32_t>(HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS):
507     case static_cast<int32_t>(HAL_PIXEL_FORMAT_NV12_ENCODEABLE):
508       comp.sizeInBits = 8;
509       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_Y.value ||
510           comp.type.value == android::gralloc4::PlaneLayoutComponentType_CB.value) {
511         comp.offsetInBits = 0;
512       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_CR.value) {
513         comp.offsetInBits = 8;
514       } else {
515         return Error::BAD_VALUE;
516       }
517       break;
518     case static_cast<int32_t>(HAL_PIXEL_FORMAT_YCrCb_420_SP):
519     case static_cast<int32_t>(HAL_PIXEL_FORMAT_YCrCb_422_SP):
520     case static_cast<int32_t>(HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO):
521     case static_cast<int32_t>(HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS):
522     case static_cast<int32_t>(HAL_PIXEL_FORMAT_NV21_ZSL):
523       comp.sizeInBits = 8;
524       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_Y.value ||
525           comp.type.value == android::gralloc4::PlaneLayoutComponentType_CR.value) {
526         comp.offsetInBits = 0;
527       } else if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_CB.value) {
528         comp.offsetInBits = 8;
529       } else {
530         return Error::BAD_VALUE;
531       }
532       break;
533     case static_cast<int32_t>(HAL_PIXEL_FORMAT_Y16):
534       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_Y.value) {
535         comp.offsetInBits = 0;
536         comp.sizeInBits = 16;
537       } else {
538         return Error::BAD_VALUE;
539       }
540       break;
541     case static_cast<int32_t>(HAL_PIXEL_FORMAT_YV12):
542       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_Y.value ||
543           comp.type.value == android::gralloc4::PlaneLayoutComponentType_CB.value ||
544           comp.type.value == android::gralloc4::PlaneLayoutComponentType_CR.value) {
545         comp.offsetInBits = 0;
546         comp.sizeInBits = 8;
547       } else {
548         return Error::BAD_VALUE;
549       }
550       break;
551     case static_cast<int32_t>(HAL_PIXEL_FORMAT_Y8):
552       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_Y.value) {
553         comp.offsetInBits = 0;
554         comp.sizeInBits = 8;
555       } else {
556         return Error::BAD_VALUE;
557       }
558       break;
559     case static_cast<int32_t>(HAL_PIXEL_FORMAT_YCbCr_420_P010):
560       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_Y.value ||
561           comp.type.value == android::gralloc4::PlaneLayoutComponentType_CB.value ||
562           comp.type.value == android::gralloc4::PlaneLayoutComponentType_CR.value) {
563         comp.offsetInBits = 0;
564         comp.sizeInBits = 10;
565       } else {
566         return Error::BAD_VALUE;
567       }
568       break;
569     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RAW16):
570       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_RAW.value) {
571         comp.offsetInBits = 0;
572         comp.sizeInBits = 16;
573       } else {
574         return Error::BAD_VALUE;
575       }
576       break;
577     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RAW12):
578     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RAW10):
579     case static_cast<int32_t>(HAL_PIXEL_FORMAT_BLOB):
580       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_RAW.value) {
581         comp.offsetInBits = 0;
582         comp.sizeInBits = -1;
583       } else {
584         return Error::BAD_VALUE;
585       }
586       break;
587     case static_cast<int32_t>(HAL_PIXEL_FORMAT_RAW8):
588       if (comp.type.value == android::gralloc4::PlaneLayoutComponentType_RAW.value) {
589         comp.offsetInBits = 0;
590         comp.sizeInBits = 8;
591       } else {
592         return Error::BAD_VALUE;
593       }
594       break;
595     default:
596       ALOGE("Offset and size in bits unknown for format %d", format);
597       return Error::UNSUPPORTED;
598   }
599   return Error::NONE;
600 }
601 
grallocToStandardPlaneLayoutComponentType(uint32_t in,std::vector<PlaneLayoutComponent> * components,int32_t format)602 static void grallocToStandardPlaneLayoutComponentType(uint32_t in,
603                                                       std::vector<PlaneLayoutComponent> *components,
604                                                       int32_t format) {
605   PlaneLayoutComponent comp;
606   comp.offsetInBits = -1;
607   comp.sizeInBits = -1;
608 
609   if (in & PLANE_COMPONENT_Y) {
610     comp.type = android::gralloc4::PlaneLayoutComponentType_Y;
611     if (getComponentSizeAndOffset(format, comp) == Error::NONE)
612       components->push_back(comp);
613   }
614 
615   if (in & PLANE_COMPONENT_Cb) {
616     comp.type = android::gralloc4::PlaneLayoutComponentType_CB;
617     if (getComponentSizeAndOffset(format, comp) == Error::NONE)
618       components->push_back(comp);
619   }
620 
621   if (in & PLANE_COMPONENT_Cr) {
622     comp.type = android::gralloc4::PlaneLayoutComponentType_CR;
623     if (getComponentSizeAndOffset(format, comp) == Error::NONE)
624       components->push_back(comp);
625   }
626 
627   if (in & PLANE_COMPONENT_R) {
628     comp.type = android::gralloc4::PlaneLayoutComponentType_R;
629     if (getComponentSizeAndOffset(format, comp) == Error::NONE)
630       components->push_back(comp);
631   }
632 
633   if (in & PLANE_COMPONENT_G) {
634     comp.type = android::gralloc4::PlaneLayoutComponentType_G;
635     if (getComponentSizeAndOffset(format, comp) == Error::NONE)
636       components->push_back(comp);
637   }
638 
639   if (in & PLANE_COMPONENT_B) {
640     comp.type = android::gralloc4::PlaneLayoutComponentType_B;
641     if (getComponentSizeAndOffset(format, comp) == Error::NONE)
642       components->push_back(comp);
643   }
644 
645   if (in & PLANE_COMPONENT_A) {
646     comp.type = android::gralloc4::PlaneLayoutComponentType_A;
647     if (getComponentSizeAndOffset(format, comp) == Error::NONE)
648       components->push_back(comp);
649   }
650 
651   if (in & PLANE_COMPONENT_RAW) {
652     comp.type = android::gralloc4::PlaneLayoutComponentType_RAW;
653     if (getComponentSizeAndOffset(format, comp) == Error::NONE)
654       components->push_back(comp);
655   }
656 
657   if (in & PLANE_COMPONENT_META) {
658     comp.type = qtigralloc::PlaneLayoutComponentType_Meta;
659     components->push_back(comp);
660   }
661 }
662 
getFormatLayout(private_handle_t * handle,std::vector<PlaneLayout> * out)663 static Error getFormatLayout(private_handle_t *handle, std::vector<PlaneLayout> *out) {
664   std::vector<PlaneLayout> plane_info;
665   int plane_count = 0;
666   BufferInfo info(handle->unaligned_width, handle->unaligned_height, handle->format, handle->usage);
667 
668   gralloc::PlaneLayoutInfo plane_layout[8] = {};
669   if (gralloc::IsYuvFormat(handle->format)) {
670     gralloc::GetYUVPlaneInfo(info, handle->format, handle->width, handle->height, handle->flags,
671                              &plane_count, plane_layout);
672   } else if (gralloc::IsUncompressedRGBFormat(handle->format) ||
673              gralloc::IsCompressedRGBFormat(handle->format)) {
674     gralloc::GetRGBPlaneInfo(info, handle->format, handle->width, handle->height, handle->flags,
675                              &plane_count, plane_layout);
676   } else {
677     return Error::BAD_BUFFER;
678   }
679   plane_info.resize(plane_count);
680   for (int i = 0; i < plane_count; i++) {
681     std::vector<PlaneLayoutComponent> components;
682     grallocToStandardPlaneLayoutComponentType(plane_layout[i].component, &plane_info[i].components,
683                                               handle->format);
684     plane_info[i].horizontalSubsampling = (1ull << plane_layout[i].h_subsampling);
685     plane_info[i].verticalSubsampling = (1ull << plane_layout[i].v_subsampling);
686     plane_info[i].offsetInBytes = static_cast<int64_t>(plane_layout[i].offset);
687     plane_info[i].sampleIncrementInBits = static_cast<int64_t>(plane_layout[i].step * 8);
688     plane_info[i].strideInBytes = static_cast<int64_t>(plane_layout[i].stride_bytes);
689     plane_info[i].totalSizeInBytes = static_cast<int64_t>(plane_layout[i].size);
690     plane_info[i].widthInSamples = handle->unaligned_width >> plane_layout[i].h_subsampling;
691     plane_info[i].heightInSamples = handle->unaligned_height >> plane_layout[i].v_subsampling;
692   }
693   *out = plane_info;
694   return Error::NONE;
695 }
696 
BufferManager()697 BufferManager::BufferManager() : next_id_(0) {
698   handles_map_.clear();
699   allocator_ = new Allocator();
700   allocator_->Init();
701 }
702 
GetInstance()703 BufferManager *BufferManager::GetInstance() {
704   static BufferManager *instance = new BufferManager();
705   return instance;
706 }
707 
~BufferManager()708 BufferManager::~BufferManager() {
709   if (allocator_) {
710     delete allocator_;
711   }
712 }
713 
SetGrallocDebugProperties(gralloc::GrallocProperties props)714 void BufferManager::SetGrallocDebugProperties(gralloc::GrallocProperties props) {
715   allocator_->SetProperties(props);
716   AdrenoMemInfo::GetInstance()->AdrenoSetProperties(props);
717 }
718 
FreeBuffer(std::shared_ptr<Buffer> buf)719 Error BufferManager::FreeBuffer(std::shared_ptr<Buffer> buf) {
720   auto hnd = buf->handle;
721   ALOGD_IF(DEBUG, "FreeBuffer handle:%p", hnd);
722 
723   if (private_handle_t::validate(hnd) != 0) {
724     ALOGE("FreeBuffer: Invalid handle: %p", hnd);
725     return Error::BAD_BUFFER;
726   }
727 
728   if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset, hnd->fd,
729                              buf->ion_handle_main) != 0) {
730     return Error::BAD_BUFFER;
731   }
732 
733   auto meta_size = getMetaDataSize(buf->reserved_size);
734 
735   if (allocator_->FreeBuffer(reinterpret_cast<void *>(hnd->base_metadata), meta_size,
736                              hnd->offset_metadata, hnd->fd_metadata, buf->ion_handle_meta) != 0) {
737     return Error::BAD_BUFFER;
738   }
739 
740   private_handle_t *handle = const_cast<private_handle_t *>(hnd);
741   handle->fd = -1;
742   handle->fd_metadata = -1;
743   if (!(handle->flags & private_handle_t::PRIV_FLAGS_CLIENT_ALLOCATED)) {
744     delete handle;
745   }
746   return Error::NONE;
747 }
748 
ValidateBufferSize(private_handle_t const * hnd,BufferInfo info)749 Error BufferManager::ValidateBufferSize(private_handle_t const *hnd, BufferInfo info) {
750   unsigned int size, alignedw, alignedh;
751   info.format = GetImplDefinedFormat(info.usage, info.format);
752   int ret = GetBufferSizeAndDimensions(info, &size, &alignedw, &alignedh);
753   if (ret < 0) {
754     return Error::BAD_BUFFER;
755   }
756   auto ion_fd_size = static_cast<unsigned int>(lseek(hnd->fd, 0, SEEK_END));
757   if (size != ion_fd_size) {
758     return Error::BAD_VALUE;
759   }
760   return Error::NONE;
761 }
762 
RegisterHandleLocked(const private_handle_t * hnd,int ion_handle,int ion_handle_meta)763 void BufferManager::RegisterHandleLocked(const private_handle_t *hnd, int ion_handle,
764                                          int ion_handle_meta) {
765   auto buffer = std::make_shared<Buffer>(hnd, ion_handle, ion_handle_meta);
766 
767   if (hnd->base_metadata) {
768     auto metadata = reinterpret_cast<MetaData_t *>(hnd->base_metadata);
769 #ifdef METADATA_V2
770     buffer->reserved_size = metadata->reservedSize;
771     if (buffer->reserved_size > 0) {
772       buffer->reserved_region_ptr =
773           reinterpret_cast<void *>(hnd->base_metadata + sizeof(MetaData_t));
774     } else {
775       buffer->reserved_region_ptr = nullptr;
776     }
777 #else
778     buffer->reserved_region_ptr = reinterpret_cast<void *>(&(metadata->reservedRegion.data));
779     buffer->reserved_size = metadata->reservedRegion.size;
780 #endif
781   }
782 
783   handles_map_.emplace(std::make_pair(hnd, buffer));
784 }
785 
ImportHandleLocked(private_handle_t * hnd)786 Error BufferManager::ImportHandleLocked(private_handle_t *hnd) {
787   if (private_handle_t::validate(hnd) != 0) {
788     ALOGE("ImportHandleLocked: Invalid handle: %p", hnd);
789     return Error::BAD_BUFFER;
790   }
791   ALOGD_IF(DEBUG, "Importing handle:%p id: %" PRIu64, hnd, hnd->id);
792   int ion_handle = allocator_->ImportBuffer(hnd->fd);
793   if (ion_handle < 0) {
794     ALOGE("Failed to import ion buffer: hnd: %p, fd:%d, id:%" PRIu64, hnd, hnd->fd, hnd->id);
795     return Error::BAD_BUFFER;
796   }
797   int ion_handle_meta = allocator_->ImportBuffer(hnd->fd_metadata);
798   if (ion_handle_meta < 0) {
799     ALOGE("Failed to import ion metadata buffer: hnd: %p, fd:%d, id:%" PRIu64, hnd, hnd->fd,
800           hnd->id);
801     return Error::BAD_BUFFER;
802   }
803   // Initialize members that aren't transported
804   hnd->size = static_cast<unsigned int>(lseek(hnd->fd, 0, SEEK_END));
805   hnd->offset = 0;
806   hnd->offset_metadata = 0;
807   hnd->base = 0;
808   hnd->base_metadata = 0;
809   hnd->gpuaddr = 0;
810 
811   if (validateAndMap(hnd)) {
812     ALOGE("Failed to map metadata: hnd: %p, fd:%d, id:%" PRIu64, hnd, hnd->fd, hnd->id);
813     return Error::BAD_BUFFER;
814   }
815 
816   RegisterHandleLocked(hnd, ion_handle, ion_handle_meta);
817   return Error::NONE;
818 }
819 
GetBufferFromHandleLocked(const private_handle_t * hnd)820 std::shared_ptr<BufferManager::Buffer> BufferManager::GetBufferFromHandleLocked(
821     const private_handle_t *hnd) {
822   auto it = handles_map_.find(hnd);
823   if (it != handles_map_.end()) {
824     return it->second;
825   } else {
826     return nullptr;
827   }
828 }
829 
MapBuffer(private_handle_t const * handle)830 Error BufferManager::MapBuffer(private_handle_t const *handle) {
831   private_handle_t *hnd = const_cast<private_handle_t *>(handle);
832   ALOGD_IF(DEBUG, "Map buffer handle:%p id: %" PRIu64, hnd, hnd->id);
833 
834   hnd->base = 0;
835   if (allocator_->MapBuffer(reinterpret_cast<void **>(&hnd->base), hnd->size, hnd->offset,
836                             hnd->fd) != 0) {
837     return Error::BAD_BUFFER;
838   }
839   return Error::NONE;
840 }
841 
IsBufferImported(const private_handle_t * hnd)842 Error BufferManager::IsBufferImported(const private_handle_t *hnd) {
843   std::lock_guard<std::mutex> lock(buffer_lock_);
844   auto buf = GetBufferFromHandleLocked(hnd);
845   if (buf != nullptr) {
846     return Error::NONE;
847   }
848   return Error::BAD_BUFFER;
849 }
850 
RetainBuffer(private_handle_t const * hnd)851 Error BufferManager::RetainBuffer(private_handle_t const *hnd) {
852   ALOGD_IF(DEBUG, "Retain buffer handle:%p id: %" PRIu64, hnd, hnd->id);
853   auto err = Error::NONE;
854   std::lock_guard<std::mutex> lock(buffer_lock_);
855   auto buf = GetBufferFromHandleLocked(hnd);
856   if (buf != nullptr) {
857     buf->IncRef();
858   } else {
859     private_handle_t *handle = const_cast<private_handle_t *>(hnd);
860     err = ImportHandleLocked(handle);
861   }
862   return err;
863 }
864 
ReleaseBuffer(private_handle_t const * hnd)865 Error BufferManager::ReleaseBuffer(private_handle_t const *hnd) {
866   ALOGD_IF(DEBUG, "Release buffer handle:%p", hnd);
867   std::lock_guard<std::mutex> lock(buffer_lock_);
868   auto buf = GetBufferFromHandleLocked(hnd);
869   if (buf == nullptr) {
870     ALOGE("Could not find handle: %p id: %" PRIu64, hnd, hnd->id);
871     return Error::BAD_BUFFER;
872   } else {
873     if (buf->DecRef()) {
874       handles_map_.erase(hnd);
875       // Unmap, close ion handle and close fd
876       FreeBuffer(buf);
877     }
878   }
879   return Error::NONE;
880 }
881 
LockBuffer(const private_handle_t * hnd,uint64_t usage)882 Error BufferManager::LockBuffer(const private_handle_t *hnd, uint64_t usage) {
883   std::lock_guard<std::mutex> lock(buffer_lock_);
884   auto err = Error::NONE;
885   ALOGD_IF(DEBUG, "LockBuffer buffer handle:%p id: %" PRIu64, hnd, hnd->id);
886 
887   // If buffer is not meant for CPU return err
888   if (!CpuCanAccess(usage)) {
889     return Error::BAD_VALUE;
890   }
891 
892   auto buf = GetBufferFromHandleLocked(hnd);
893   if (buf == nullptr) {
894     return Error::BAD_BUFFER;
895   }
896 
897   if (hnd->base == 0) {
898     // we need to map for real
899     err = MapBuffer(hnd);
900   }
901 
902   // Invalidate if CPU reads in software and there are non-CPU
903   // writers. No need to do this for the metadata buffer as it is
904   // only read/written in software.
905 
906   // todo use handle here
907   if (err == Error::NONE && (hnd->flags & private_handle_t::PRIV_FLAGS_USES_ION) &&
908       (hnd->flags & private_handle_t::PRIV_FLAGS_CACHED)) {
909     if (allocator_->CleanBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
910                                 buf->ion_handle_main, CACHE_INVALIDATE, hnd->fd)) {
911       return Error::BAD_BUFFER;
912     }
913   }
914 
915   // Mark the buffer to be flushed after CPU write.
916   if (err == Error::NONE && CpuCanWrite(usage)) {
917     private_handle_t *handle = const_cast<private_handle_t *>(hnd);
918     handle->flags |= private_handle_t::PRIV_FLAGS_NEEDS_FLUSH;
919   }
920 
921   return err;
922 }
923 
FlushBuffer(const private_handle_t * handle)924 Error BufferManager::FlushBuffer(const private_handle_t *handle) {
925   std::lock_guard<std::mutex> lock(buffer_lock_);
926   auto status = Error::NONE;
927 
928   private_handle_t *hnd = const_cast<private_handle_t *>(handle);
929   auto buf = GetBufferFromHandleLocked(hnd);
930   if (buf == nullptr) {
931     return Error::BAD_BUFFER;
932   }
933 
934   if (allocator_->CleanBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
935                               buf->ion_handle_main, CACHE_CLEAN, hnd->fd) != 0) {
936     status = Error::BAD_BUFFER;
937   }
938 
939   return status;
940 }
941 
RereadBuffer(const private_handle_t * handle)942 Error BufferManager::RereadBuffer(const private_handle_t *handle) {
943   std::lock_guard<std::mutex> lock(buffer_lock_);
944   auto status = Error::NONE;
945 
946   private_handle_t *hnd = const_cast<private_handle_t *>(handle);
947   auto buf = GetBufferFromHandleLocked(hnd);
948   if (buf == nullptr) {
949     return Error::BAD_BUFFER;
950   }
951 
952   if (allocator_->CleanBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
953                               buf->ion_handle_main, CACHE_INVALIDATE, hnd->fd) != 0) {
954     status = Error::BAD_BUFFER;
955   }
956 
957   return status;
958 }
959 
UnlockBuffer(const private_handle_t * handle)960 Error BufferManager::UnlockBuffer(const private_handle_t *handle) {
961   std::lock_guard<std::mutex> lock(buffer_lock_);
962   auto status = Error::NONE;
963 
964   private_handle_t *hnd = const_cast<private_handle_t *>(handle);
965   auto buf = GetBufferFromHandleLocked(hnd);
966   if (buf == nullptr) {
967     return Error::BAD_BUFFER;
968   }
969 
970   if (hnd->flags & private_handle_t::PRIV_FLAGS_NEEDS_FLUSH) {
971     if (allocator_->CleanBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
972                                 buf->ion_handle_main, CACHE_CLEAN, hnd->fd) != 0) {
973       status = Error::BAD_BUFFER;
974     }
975     hnd->flags &= ~private_handle_t::PRIV_FLAGS_NEEDS_FLUSH;
976   } else {
977     if (allocator_->CleanBuffer(reinterpret_cast<void *>(hnd->base), hnd->size, hnd->offset,
978                                 buf->ion_handle_main, CACHE_READ_DONE, hnd->fd) != 0) {
979       status = Error::BAD_BUFFER;
980     }
981   }
982 
983   return status;
984 }
985 
AllocateBuffer(const BufferDescriptor & descriptor,buffer_handle_t * handle,unsigned int bufferSize,bool testAlloc)986 Error BufferManager::AllocateBuffer(const BufferDescriptor &descriptor, buffer_handle_t *handle,
987                                     unsigned int bufferSize, bool testAlloc) {
988   if (!handle)
989     return Error::BAD_BUFFER;
990   std::lock_guard<std::mutex> buffer_lock(buffer_lock_);
991 
992   uint64_t usage = descriptor.GetUsage();
993   int format = GetImplDefinedFormat(usage, descriptor.GetFormat());
994   uint32_t layer_count = descriptor.GetLayerCount();
995 
996   unsigned int size;
997   unsigned int alignedw, alignedh;
998   int err = 0;
999 
1000   int buffer_type = GetBufferType(format);
1001   BufferInfo info = GetBufferInfo(descriptor);
1002   info.format = format;
1003   info.layer_count = layer_count;
1004 
1005   GraphicsMetadata graphics_metadata = {};
1006   err = GetBufferSizeAndDimensions(info, &size, &alignedw, &alignedh, &graphics_metadata);
1007   if (err < 0) {
1008     return Error::BAD_DESCRIPTOR;
1009   }
1010 
1011   if (testAlloc) {
1012     return Error::NONE;
1013   }
1014 
1015   size = (bufferSize >= size) ? bufferSize : size;
1016   uint64_t flags = 0;
1017   auto page_size = UINT(getpagesize());
1018   AllocData data;
1019   data.align = GetDataAlignment(format, usage);
1020   data.size = size;
1021   data.handle = (uintptr_t)handle;
1022   data.uncached = UseUncached(format, usage);
1023 
1024   // Allocate buffer memory
1025   err = allocator_->AllocateMem(&data, usage, format);
1026   if (err) {
1027     ALOGE("gralloc failed to allocate err=%s format %d size %d WxH %dx%d usage %" PRIu64,
1028           strerror(-err), format, size, alignedw, alignedh, usage);
1029     return Error::NO_RESOURCES;
1030   }
1031 
1032   // Allocate memory for MetaData
1033   AllocData e_data;
1034   e_data.size = static_cast<unsigned int>(getMetaDataSize(descriptor.GetReservedSize()));
1035   e_data.handle = data.handle;
1036   e_data.align = page_size;
1037 
1038   err = allocator_->AllocateMem(&e_data, 0, 0);
1039   if (err) {
1040     ALOGE("gralloc failed to allocate metadata error=%s", strerror(-err));
1041     return Error::NO_RESOURCES;
1042   }
1043 
1044   flags = GetHandleFlags(format, usage);
1045   flags |= data.alloc_type;
1046 
1047   // Create handle
1048   private_handle_t *hnd = new private_handle_t(
1049       data.fd, e_data.fd, INT(flags), INT(alignedw), INT(alignedh), descriptor.GetWidth(),
1050       descriptor.GetHeight(), format, buffer_type, data.size, usage);
1051 
1052   hnd->id = ++next_id_;
1053   hnd->base = 0;
1054   hnd->base_metadata = 0;
1055   hnd->layer_count = layer_count;
1056 
1057   bool use_adreno_for_size = CanUseAdrenoForSize(buffer_type, usage);
1058   if (use_adreno_for_size) {
1059     setMetaDataAndUnmap(hnd, SET_GRAPHICS_METADATA, reinterpret_cast<void *>(&graphics_metadata));
1060   }
1061 
1062 #ifdef METADATA_V2
1063   auto error = validateAndMap(hnd, descriptor.GetReservedSize());
1064 #else
1065   auto error = validateAndMap(hnd);
1066 #endif
1067 
1068   if (error != 0) {
1069     ALOGE("validateAndMap failed");
1070     return Error::BAD_BUFFER;
1071   }
1072   auto metadata = reinterpret_cast<MetaData_t *>(hnd->base_metadata);
1073   auto nameLength = std::min(descriptor.GetName().size(), size_t(MAX_NAME_LEN - 1));
1074   nameLength = descriptor.GetName().copy(metadata->name, nameLength);
1075   metadata->name[nameLength] = '\0';
1076 
1077 #ifdef METADATA_V2
1078   metadata->reservedSize = descriptor.GetReservedSize();
1079 #else
1080   metadata->reservedRegion.size =
1081       std::min(descriptor.GetReservedSize(), (uint64_t)RESERVED_REGION_SIZE);
1082 #endif
1083   metadata->crop.top = 0;
1084   metadata->crop.left = 0;
1085   metadata->crop.right = hnd->width;
1086   metadata->crop.bottom = hnd->height;
1087 
1088   unmapAndReset(hnd, descriptor.GetReservedSize());
1089 
1090   *handle = hnd;
1091 
1092   RegisterHandleLocked(hnd, data.ion_handle, e_data.ion_handle);
1093   ALOGD_IF(DEBUG, "Allocated buffer handle: %p id: %" PRIu64, hnd, hnd->id);
1094   if (DEBUG) {
1095     private_handle_t::Dump(hnd);
1096   }
1097   return Error::NONE;
1098 }
1099 
Dump(std::ostringstream * os)1100 Error BufferManager::Dump(std::ostringstream *os) {
1101   std::lock_guard<std::mutex> buffer_lock(buffer_lock_);
1102   for (auto it : handles_map_) {
1103     auto buf = it.second;
1104     auto hnd = buf->handle;
1105     *os << "handle id: " << std::setw(4) << hnd->id;
1106     *os << " fd: " << std::setw(3) << hnd->fd;
1107     *os << " fd_meta: " << std::setw(3) << hnd->fd_metadata;
1108     *os << " wxh: " << std::setw(4) << hnd->width << " x " << std::setw(4) << hnd->height;
1109     *os << " uwxuh: " << std::setw(4) << hnd->unaligned_width << " x ";
1110     *os << std::setw(4) << hnd->unaligned_height;
1111     *os << " size: " << std::setw(9) << hnd->size;
1112     *os << std::hex << std::setfill('0');
1113     *os << " priv_flags: "
1114         << "0x" << std::setw(8) << hnd->flags;
1115     *os << " usage: "
1116         << "0x" << std::setw(8) << hnd->usage;
1117     // TODO(user): get format string from qdutils
1118     *os << " format: "
1119         << "0x" << std::setw(8) << hnd->format;
1120     *os << std::dec << std::setfill(' ') << std::endl;
1121   }
1122   return Error::NONE;
1123 }
1124 
1125 // Get list of private handles in handles_map_
GetAllHandles(std::vector<const private_handle_t * > * out_handle_list)1126 Error BufferManager::GetAllHandles(std::vector<const private_handle_t *> *out_handle_list) {
1127   std::lock_guard<std::mutex> lock(buffer_lock_);
1128   if (handles_map_.empty()) {
1129     return Error::NO_RESOURCES;
1130   }
1131   out_handle_list->reserve(handles_map_.size());
1132   for (auto handle : handles_map_) {
1133     out_handle_list->push_back(handle.first);
1134   }
1135   return Error::NONE;
1136 }
1137 
GetReservedRegion(private_handle_t * handle,void ** reserved_region,uint64_t * reserved_region_size)1138 Error BufferManager::GetReservedRegion(private_handle_t *handle, void **reserved_region,
1139                                        uint64_t *reserved_region_size) {
1140   std::lock_guard<std::mutex> lock(buffer_lock_);
1141   if (!handle)
1142     return Error::BAD_BUFFER;
1143 
1144   auto buf = GetBufferFromHandleLocked(handle);
1145   if (buf == nullptr)
1146     return Error::BAD_BUFFER;
1147   if (!handle->base_metadata) {
1148     return Error::BAD_BUFFER;
1149   }
1150 
1151   *reserved_region = buf->reserved_region_ptr;
1152   *reserved_region_size = buf->reserved_size;
1153 
1154   return Error::NONE;
1155 }
1156 
GetMetadata(private_handle_t * handle,int64_t metadatatype_value,hidl_vec<uint8_t> * out)1157 Error BufferManager::GetMetadata(private_handle_t *handle, int64_t metadatatype_value,
1158                                  hidl_vec<uint8_t> *out) {
1159   std::lock_guard<std::mutex> lock(buffer_lock_);
1160   if (!handle)
1161     return Error::BAD_BUFFER;
1162   auto buf = GetBufferFromHandleLocked(handle);
1163   if (buf == nullptr)
1164     return Error::BAD_BUFFER;
1165 
1166   if (!handle->base_metadata) {
1167     return Error::BAD_BUFFER;
1168   }
1169 
1170   auto metadata = reinterpret_cast<MetaData_t *>(handle->base_metadata);
1171 
1172   Error error = Error::NONE;
1173   switch (metadatatype_value) {
1174     case (int64_t)StandardMetadataType::BUFFER_ID:
1175       android::gralloc4::encodeBufferId((uint64_t)handle->id, out);
1176       break;
1177     case (int64_t)StandardMetadataType::NAME: {
1178       std::string name(metadata->name);
1179       android::gralloc4::encodeName(name, out);
1180       break;
1181     }
1182     case (int64_t)StandardMetadataType::WIDTH:
1183       android::gralloc4::encodeWidth((uint64_t)handle->unaligned_width, out);
1184       break;
1185     case (int64_t)StandardMetadataType::HEIGHT:
1186       android::gralloc4::encodeHeight((uint64_t)handle->unaligned_height, out);
1187       break;
1188     case (int64_t)StandardMetadataType::LAYER_COUNT:
1189       android::gralloc4::encodeLayerCount((uint64_t)handle->layer_count, out);
1190       break;
1191     case (int64_t)StandardMetadataType::PIXEL_FORMAT_REQUESTED:
1192       // TODO(tbalacha): need to return IMPLEMENTATION_DEFINED,
1193       // which wouldn't be known from private_handle_t
1194       android::gralloc4::encodePixelFormatRequested((PixelFormat)handle->format, out);
1195       break;
1196     case (int64_t)StandardMetadataType::PIXEL_FORMAT_FOURCC: {
1197       uint32_t drm_format = 0;
1198       uint64_t drm_format_modifier = 0;
1199       GetDRMFormat(handle->format, handle->flags, &drm_format, &drm_format_modifier);
1200       android::gralloc4::encodePixelFormatFourCC(drm_format, out);
1201       break;
1202     }
1203     case (int64_t)StandardMetadataType::PIXEL_FORMAT_MODIFIER: {
1204       uint32_t drm_format = 0;
1205       uint64_t drm_format_modifier = 0;
1206       GetDRMFormat(handle->format, handle->flags, &drm_format, &drm_format_modifier);
1207       android::gralloc4::encodePixelFormatModifier(drm_format_modifier, out);
1208       break;
1209     }
1210     case (int64_t)StandardMetadataType::USAGE:
1211       android::gralloc4::encodeUsage((uint64_t)handle->usage, out);
1212       break;
1213     case (int64_t)StandardMetadataType::ALLOCATION_SIZE:
1214       android::gralloc4::encodeAllocationSize((uint64_t)handle->size, out);
1215       break;
1216     case (int64_t)StandardMetadataType::PROTECTED_CONTENT: {
1217       uint64_t protected_content = (handle->flags & qtigralloc::PRIV_FLAGS_SECURE_BUFFER) ? 1 : 0;
1218       android::gralloc4::encodeProtectedContent(protected_content, out);
1219       break;
1220     }
1221     case (int64_t)StandardMetadataType::CHROMA_SITING:
1222       android::gralloc4::encodeChromaSiting(android::gralloc4::ChromaSiting_None, out);
1223       break;
1224     case (int64_t)StandardMetadataType::DATASPACE:
1225 #ifdef METADATA_V2
1226       if (metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)]) {
1227 #endif
1228         Dataspace dataspace;
1229         colorMetadataToDataspace(metadata->color, &dataspace);
1230         android::gralloc4::encodeDataspace(dataspace, out);
1231 #ifdef METADATA_V2
1232       } else {
1233         android::gralloc4::encodeDataspace(Dataspace::UNKNOWN, out);
1234       }
1235 #endif
1236       break;
1237     case (int64_t)StandardMetadataType::INTERLACED:
1238       if (metadata->interlaced > 0) {
1239         android::gralloc4::encodeInterlaced(qtigralloc::Interlaced_Qti, out);
1240       } else {
1241         android::gralloc4::encodeInterlaced(android::gralloc4::Interlaced_None, out);
1242       }
1243       break;
1244     case (int64_t)StandardMetadataType::COMPRESSION:
1245       if (handle->flags & qtigralloc::PRIV_FLAGS_UBWC_ALIGNED ||
1246           handle->flags & qtigralloc::PRIV_FLAGS_UBWC_ALIGNED_PI) {
1247         android::gralloc4::encodeCompression(qtigralloc::Compression_QtiUBWC, out);
1248       } else {
1249         android::gralloc4::encodeCompression(android::gralloc4::Compression_None, out);
1250       }
1251       break;
1252     case (int64_t)StandardMetadataType::PLANE_LAYOUTS: {
1253       std::vector<PlaneLayout> plane_layouts;
1254       getFormatLayout(handle, &plane_layouts);
1255       android::gralloc4::encodePlaneLayouts(plane_layouts, out);
1256       break;
1257     }
1258     case (int64_t)StandardMetadataType::BLEND_MODE:
1259       android::gralloc4::encodeBlendMode((BlendMode)metadata->blendMode, out);
1260       break;
1261     case (int64_t)StandardMetadataType::SMPTE2086: {
1262       if (metadata->color.masteringDisplayInfo.colorVolumeSEIEnabled) {
1263         Smpte2086 mastering_display_values;
1264         mastering_display_values.primaryRed = {
1265             static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[0][0]) /
1266                 50000.0f,
1267             static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[0][1]) /
1268                 50000.0f};
1269         mastering_display_values.primaryGreen = {
1270             static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[1][0]) /
1271                 50000.0f,
1272             static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[1][1]) /
1273                 50000.0f};
1274         mastering_display_values.primaryBlue = {
1275             static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[2][0]) /
1276                 50000.0f,
1277             static_cast<float>(metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[2][1]) /
1278                 50000.0f};
1279         mastering_display_values.whitePoint = {
1280             static_cast<float>(metadata->color.masteringDisplayInfo.primaries.whitePoint[0]) /
1281                 50000.0f,
1282             static_cast<float>(metadata->color.masteringDisplayInfo.primaries.whitePoint[1]) /
1283                 50000.0f};
1284         mastering_display_values.maxLuminance =
1285             static_cast<float>(metadata->color.masteringDisplayInfo.maxDisplayLuminance);
1286         mastering_display_values.minLuminance =
1287             static_cast<float>(metadata->color.masteringDisplayInfo.minDisplayLuminance) / 10000.0f;
1288         android::gralloc4::encodeSmpte2086(mastering_display_values, out);
1289       } else {
1290         android::gralloc4::encodeSmpte2086(std::nullopt, out);
1291       }
1292       break;
1293     }
1294     case (int64_t)StandardMetadataType::CTA861_3: {
1295       if (metadata->color.contentLightLevel.lightLevelSEIEnabled) {
1296         Cta861_3 content_light_level;
1297         content_light_level.maxContentLightLevel =
1298             static_cast<float>(metadata->color.contentLightLevel.maxContentLightLevel);
1299         content_light_level.maxFrameAverageLightLevel =
1300             static_cast<float>(metadata->color.contentLightLevel.minPicAverageLightLevel) /
1301             10000.0f;
1302         android::gralloc4::encodeCta861_3(content_light_level, out);
1303       } else {
1304         android::gralloc4::encodeCta861_3(std::nullopt, out);
1305       }
1306       break;
1307     }
1308     case (int64_t)StandardMetadataType::SMPTE2094_40: {
1309       if (metadata->color.dynamicMetaDataValid &&
1310           metadata->color.dynamicMetaDataLen <= HDR_DYNAMIC_META_DATA_SZ) {
1311         std::vector<uint8_t> dynamic_metadata_payload;
1312         dynamic_metadata_payload.resize(metadata->color.dynamicMetaDataLen);
1313         dynamic_metadata_payload.assign(
1314             metadata->color.dynamicMetaDataPayload,
1315             metadata->color.dynamicMetaDataPayload + metadata->color.dynamicMetaDataLen);
1316         android::gralloc4::encodeSmpte2094_40(dynamic_metadata_payload, out);
1317       } else {
1318         android::gralloc4::encodeSmpte2094_40(std::nullopt, out);
1319       }
1320       break;
1321     }
1322     case (int64_t)StandardMetadataType::CROP: {
1323       // Crop is the same for all planes
1324       std::vector<Rect> out_crop = {{metadata->crop.left, metadata->crop.top, metadata->crop.right,
1325                                      metadata->crop.bottom}};
1326       android::gralloc4::encodeCrop(out_crop, out);
1327       break;
1328     }
1329     case QTI_VT_TIMESTAMP:
1330       android::gralloc4::encodeUint64(qtigralloc::MetadataType_VTTimestamp, metadata->vtTimeStamp,
1331                                       out);
1332       break;
1333     case QTI_COLOR_METADATA:
1334       qtigralloc::encodeColorMetadata(metadata->color, out);
1335       break;
1336     case QTI_PP_PARAM_INTERLACED:
1337       android::gralloc4::encodeInt32(qtigralloc::MetadataType_PPParamInterlaced,
1338                                      metadata->interlaced, out);
1339       break;
1340     case QTI_VIDEO_PERF_MODE:
1341       android::gralloc4::encodeUint32(qtigralloc::MetadataType_VideoPerfMode,
1342                                       metadata->isVideoPerfMode, out);
1343       break;
1344     case QTI_GRAPHICS_METADATA:
1345       qtigralloc::encodeGraphicsMetadata(metadata->graphics_metadata, out);
1346       break;
1347     case QTI_UBWC_CR_STATS_INFO:
1348       qtigralloc::encodeUBWCStats(metadata->ubwcCRStats, out);
1349       break;
1350     case QTI_REFRESH_RATE:
1351       android::gralloc4::encodeFloat(qtigralloc::MetadataType_RefreshRate, metadata->refreshrate,
1352                                      out);
1353       break;
1354     case QTI_MAP_SECURE_BUFFER:
1355       android::gralloc4::encodeInt32(qtigralloc::MetadataType_MapSecureBuffer,
1356                                      metadata->mapSecureBuffer, out);
1357       break;
1358     case QTI_LINEAR_FORMAT:
1359       android::gralloc4::encodeUint32(qtigralloc::MetadataType_LinearFormat, metadata->linearFormat,
1360                                       out);
1361       break;
1362     case QTI_SINGLE_BUFFER_MODE:
1363       android::gralloc4::encodeUint32(qtigralloc::MetadataType_SingleBufferMode,
1364                                       metadata->isSingleBufferMode, out);
1365       break;
1366     case QTI_CVP_METADATA:
1367       qtigralloc::encodeCVPMetadata(metadata->cvpMetadata, out);
1368       break;
1369     case QTI_VIDEO_HISTOGRAM_STATS:
1370       qtigralloc::encodeVideoHistogramMetadata(metadata->video_histogram_stats, out);
1371       break;
1372     case QTI_FD:
1373       android::gralloc4::encodeInt32(qtigralloc::MetadataType_FD, handle->fd, out);
1374       break;
1375     case QTI_PRIVATE_FLAGS:
1376       android::gralloc4::encodeInt32(qtigralloc::MetadataType_PrivateFlags, handle->flags, out);
1377       break;
1378     case QTI_ALIGNED_WIDTH_IN_PIXELS:
1379       android::gralloc4::encodeUint32(qtigralloc::MetadataType_AlignedWidthInPixels, handle->width,
1380                                       out);
1381       break;
1382     case QTI_ALIGNED_HEIGHT_IN_PIXELS:
1383       android::gralloc4::encodeUint32(qtigralloc::MetadataType_AlignedHeightInPixels,
1384                                       handle->height, out);
1385       break;
1386 #ifdef METADATA_V2
1387     case QTI_STANDARD_METADATA_STATUS:
1388       qtigralloc::encodeMetadataState(metadata->isStandardMetadataSet, out);
1389       break;
1390     case QTI_VENDOR_METADATA_STATUS:
1391       qtigralloc::encodeMetadataState(metadata->isVendorMetadataSet, out);
1392       break;
1393 #endif
1394     default:
1395       error = Error::UNSUPPORTED;
1396   }
1397 
1398   return error;
1399 }
1400 
SetMetadata(private_handle_t * handle,int64_t metadatatype_value,hidl_vec<uint8_t> in)1401 Error BufferManager::SetMetadata(private_handle_t *handle, int64_t metadatatype_value,
1402                                  hidl_vec<uint8_t> in) {
1403   std::lock_guard<std::mutex> lock(buffer_lock_);
1404   if (!handle)
1405     return Error::BAD_BUFFER;
1406 
1407   auto buf = GetBufferFromHandleLocked(handle);
1408   if (buf == nullptr)
1409     return Error::BAD_BUFFER;
1410 
1411   if (!handle->base_metadata) {
1412     return Error::BAD_BUFFER;
1413   }
1414   if (in.size() == 0) {
1415     return Error::UNSUPPORTED;
1416   }
1417 
1418   if (in.size() == 0) {
1419     return Error::UNSUPPORTED;
1420   }
1421 
1422   auto metadata = reinterpret_cast<MetaData_t *>(handle->base_metadata);
1423 
1424 #ifdef METADATA_V2
1425   // By default, set these to true
1426   // Reset to false for special cases below
1427   if (IS_VENDOR_METADATA_TYPE(metadatatype_value)) {
1428     metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(metadatatype_value)] = true;
1429   } else {
1430     metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)] = true;
1431   }
1432 #endif
1433 
1434   switch (metadatatype_value) {
1435     // These are constant (unchanged after allocation)
1436     case (int64_t)StandardMetadataType::BUFFER_ID:
1437     case (int64_t)StandardMetadataType::NAME:
1438     case (int64_t)StandardMetadataType::WIDTH:
1439     case (int64_t)StandardMetadataType::HEIGHT:
1440     case (int64_t)StandardMetadataType::LAYER_COUNT:
1441     case (int64_t)StandardMetadataType::PIXEL_FORMAT_REQUESTED:
1442     case (int64_t)StandardMetadataType::USAGE:
1443       return Error::BAD_VALUE;
1444     case (int64_t)StandardMetadataType::PIXEL_FORMAT_FOURCC:
1445     case (int64_t)StandardMetadataType::PIXEL_FORMAT_MODIFIER:
1446     case (int64_t)StandardMetadataType::PROTECTED_CONTENT:
1447     case (int64_t)StandardMetadataType::ALLOCATION_SIZE:
1448     case (int64_t)StandardMetadataType::PLANE_LAYOUTS:
1449     case (int64_t)StandardMetadataType::CHROMA_SITING:
1450     case (int64_t)StandardMetadataType::INTERLACED:
1451     case (int64_t)StandardMetadataType::COMPRESSION:
1452     case QTI_FD:
1453     case QTI_PRIVATE_FLAGS:
1454     case QTI_ALIGNED_WIDTH_IN_PIXELS:
1455     case QTI_ALIGNED_HEIGHT_IN_PIXELS:
1456       return Error::UNSUPPORTED;
1457     case (int64_t)StandardMetadataType::DATASPACE:
1458       Dataspace dataspace;
1459       android::gralloc4::decodeDataspace(in, &dataspace);
1460       dataspaceToColorMetadata(dataspace, &metadata->color);
1461       break;
1462     case (int64_t)StandardMetadataType::BLEND_MODE:
1463       BlendMode mode;
1464       android::gralloc4::decodeBlendMode(in, &mode);
1465       metadata->blendMode = (int32_t)mode;
1466       break;
1467     case (int64_t)StandardMetadataType::SMPTE2086: {
1468       std::optional<Smpte2086> mastering_display_values;
1469       android::gralloc4::decodeSmpte2086(in, &mastering_display_values);
1470       if (mastering_display_values != std::nullopt) {
1471         metadata->color.masteringDisplayInfo.colorVolumeSEIEnabled = true;
1472 
1473         metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[0][0] =
1474             static_cast<uint32_t>(mastering_display_values->primaryRed.x * 50000.0f);
1475         metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[0][1] =
1476             static_cast<uint32_t>(mastering_display_values->primaryRed.y * 50000.0f);
1477 
1478         metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[1][0] =
1479             static_cast<uint32_t>(mastering_display_values->primaryGreen.x * 50000.0f);
1480         metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[1][1] =
1481             static_cast<uint32_t>(mastering_display_values->primaryGreen.y * 50000.0f);
1482 
1483         metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[2][0] =
1484             static_cast<uint32_t>(mastering_display_values->primaryBlue.x * 50000.0f);
1485         metadata->color.masteringDisplayInfo.primaries.rgbPrimaries[2][1] =
1486             static_cast<uint32_t>(mastering_display_values->primaryBlue.y * 50000.0f);
1487 
1488         metadata->color.masteringDisplayInfo.primaries.whitePoint[0] =
1489             static_cast<uint32_t>(mastering_display_values->whitePoint.x * 50000.0f);
1490         metadata->color.masteringDisplayInfo.primaries.whitePoint[1] =
1491             static_cast<uint32_t>(mastering_display_values->whitePoint.y * 50000.0f);
1492 
1493         metadata->color.masteringDisplayInfo.maxDisplayLuminance =
1494             static_cast<uint32_t>(mastering_display_values->maxLuminance);
1495         metadata->color.masteringDisplayInfo.minDisplayLuminance =
1496             static_cast<uint32_t>(mastering_display_values->minLuminance * 10000.0f);
1497       } else {
1498 #ifdef METADATA_V2
1499         metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)] =
1500             false;
1501 #endif
1502         metadata->color.masteringDisplayInfo.colorVolumeSEIEnabled = false;
1503       }
1504       break;
1505     }
1506     case (int64_t)StandardMetadataType::CTA861_3: {
1507       std::optional<Cta861_3> content_light_level;
1508       android::gralloc4::decodeCta861_3(in, &content_light_level);
1509       if (content_light_level != std::nullopt) {
1510         metadata->color.contentLightLevel.lightLevelSEIEnabled = true;
1511         metadata->color.contentLightLevel.maxContentLightLevel =
1512             static_cast<uint32_t>(content_light_level->maxContentLightLevel);
1513         metadata->color.contentLightLevel.minPicAverageLightLevel =
1514             static_cast<uint32_t>(content_light_level->maxFrameAverageLightLevel * 10000.0f);
1515       } else {
1516 #ifdef METADATA_V2
1517         metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)] =
1518             false;
1519 #endif
1520         metadata->color.contentLightLevel.lightLevelSEIEnabled = false;
1521       }
1522       break;
1523     }
1524     case (int64_t)StandardMetadataType::SMPTE2094_40: {
1525       std::optional<std::vector<uint8_t>> dynamic_metadata_payload;
1526       android::gralloc4::decodeSmpte2094_40(in, &dynamic_metadata_payload);
1527       if (dynamic_metadata_payload != std::nullopt) {
1528         if (dynamic_metadata_payload->size() > HDR_DYNAMIC_META_DATA_SZ ||
1529             dynamic_metadata_payload->size() == 0)
1530           return Error::BAD_VALUE;
1531 
1532         metadata->color.dynamicMetaDataLen = dynamic_metadata_payload->size();
1533         std::copy(dynamic_metadata_payload->begin(), dynamic_metadata_payload->end(),
1534                   metadata->color.dynamicMetaDataPayload);
1535         metadata->color.dynamicMetaDataValid = true;
1536       } else {
1537         // Reset metadata by passing in std::nullopt
1538 #ifdef METADATA_V2
1539         metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)] =
1540             false;
1541 #endif
1542         metadata->color.dynamicMetaDataValid = false;
1543       }
1544       break;
1545     }
1546     case (int64_t)StandardMetadataType::CROP: {
1547       std::vector<Rect> in_crop;
1548       android::gralloc4::decodeCrop(in, &in_crop);
1549       if (in_crop.size() != 1)
1550         return Error::UNSUPPORTED;
1551 
1552       metadata->crop.left = in_crop[0].left;
1553       metadata->crop.top = in_crop[0].top;
1554       metadata->crop.right = in_crop[0].right;
1555       metadata->crop.bottom = in_crop[0].bottom;
1556       break;
1557     }
1558     case QTI_VT_TIMESTAMP:
1559       android::gralloc4::decodeUint64(qtigralloc::MetadataType_VTTimestamp, in,
1560                                       &metadata->vtTimeStamp);
1561       break;
1562     case QTI_COLOR_METADATA:
1563       ColorMetaData color;
1564       qtigralloc::decodeColorMetadata(in, &color);
1565       metadata->color = color;
1566       break;
1567     case QTI_PP_PARAM_INTERLACED:
1568       android::gralloc4::decodeInt32(qtigralloc::MetadataType_PPParamInterlaced, in,
1569                                      &metadata->interlaced);
1570       break;
1571     case QTI_VIDEO_PERF_MODE:
1572       android::gralloc4::decodeUint32(qtigralloc::MetadataType_VideoPerfMode, in,
1573                                       &metadata->isVideoPerfMode);
1574       break;
1575     case QTI_GRAPHICS_METADATA:
1576       qtigralloc::decodeGraphicsMetadata(in, &metadata->graphics_metadata);
1577       break;
1578     case QTI_UBWC_CR_STATS_INFO:
1579       qtigralloc::decodeUBWCStats(in, &metadata->ubwcCRStats[0]);
1580       break;
1581     case QTI_REFRESH_RATE:
1582       android::gralloc4::decodeFloat(qtigralloc::MetadataType_RefreshRate, in,
1583                                      &metadata->refreshrate);
1584       break;
1585     case QTI_MAP_SECURE_BUFFER:
1586       android::gralloc4::decodeInt32(qtigralloc::MetadataType_MapSecureBuffer, in,
1587                                      &metadata->mapSecureBuffer);
1588       break;
1589     case QTI_LINEAR_FORMAT:
1590       android::gralloc4::decodeUint32(qtigralloc::MetadataType_LinearFormat, in,
1591                                       &metadata->linearFormat);
1592       break;
1593     case QTI_SINGLE_BUFFER_MODE:
1594       android::gralloc4::decodeUint32(qtigralloc::MetadataType_SingleBufferMode, in,
1595                                       &metadata->isSingleBufferMode);
1596       break;
1597     case QTI_CVP_METADATA:
1598       qtigralloc::decodeCVPMetadata(in, &metadata->cvpMetadata);
1599       break;
1600     case QTI_VIDEO_HISTOGRAM_STATS:
1601       qtigralloc::decodeVideoHistogramMetadata(in, &metadata->video_histogram_stats);
1602       break;
1603     default:
1604 #ifdef METADATA_V2
1605       if (IS_VENDOR_METADATA_TYPE(metadatatype_value)) {
1606         metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(metadatatype_value)] = false;
1607       } else {
1608         metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX(metadatatype_value)] =
1609             false;
1610       }
1611 #endif
1612       return Error::BAD_VALUE;
1613   }
1614 
1615   return Error::NONE;
1616 }
1617 
1618 }  //  namespace gralloc
1619