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