xref: /aosp_15_r20/frameworks/av/media/libstagefright/Utils.cpp (revision ec779b8e0859a360c3d303172224686826e6e0e1)
1 /*
2  * Copyright (C) 2009 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "Utils"
19 #include <utils/Log.h>
20 #include <ctype.h>
21 #include <stdio.h>
22 #include <sys/stat.h>
23 
24 #include <utility>
25 #include <vector>
26 
27 #include <media/esds/ESDS.h>
28 #include "include/HevcUtils.h"
29 
30 #include <cutils/properties.h>
31 #include <media/stagefright/CodecBase.h>
32 #include <media/stagefright/foundation/ABuffer.h>
33 #include <media/stagefright/foundation/ADebug.h>
34 #include <media/stagefright/foundation/ALookup.h>
35 #include <media/stagefright/foundation/AMessage.h>
36 #include <media/stagefright/foundation/ByteUtils.h>
37 #include <media/stagefright/foundation/OpusHeader.h>
38 #include <media/stagefright/MetaData.h>
39 #include <media/stagefright/MediaCodecConstants.h>
40 #include <media/stagefright/MediaDefs.h>
41 #include <media/AudioSystem.h>
42 #include <media/MediaPlayerInterface.h>
43 #include <media/stagefright/Utils.h>
44 #include <media/AudioParameter.h>
45 #include <system/audio.h>
46 
47 #include <com_android_media_extractor_flags.h>
48 
49 // TODO : Remove the defines once mainline media is built against NDK >= 31.
50 // The mp4 extractor is part of mainline and builds against NDK 29 as of
51 // writing. These keys are available only from NDK 31:
52 #define AMEDIAFORMAT_KEY_MPEGH_PROFILE_LEVEL_INDICATION \
53   "mpegh-profile-level-indication"
54 #define AMEDIAFORMAT_KEY_MPEGH_REFERENCE_CHANNEL_LAYOUT \
55   "mpegh-reference-channel-layout"
56 #define AMEDIAFORMAT_KEY_MPEGH_COMPATIBLE_SETS \
57   "mpegh-compatible-sets"
58 
59 namespace {
60     // TODO: this should possibly be handled in an else
61     constexpr static int32_t AACObjectNull = 0;
62 
63     // TODO: decide if we should just not transmit the level in this case
64     constexpr static int32_t DolbyVisionLevelUnknown = 0;
65 }
66 
67 namespace android {
68 
copyNALUToABuffer(sp<ABuffer> * buffer,const uint8_t * ptr,size_t length)69 static status_t copyNALUToABuffer(sp<ABuffer> *buffer, const uint8_t *ptr, size_t length) {
70     if (((*buffer)->size() + 4 + length) > ((*buffer)->capacity() - (*buffer)->offset())) {
71         sp<ABuffer> tmpBuffer = new (std::nothrow) ABuffer((*buffer)->size() + 4 + length + 1024);
72         if (tmpBuffer.get() == NULL || tmpBuffer->base() == NULL) {
73             return NO_MEMORY;
74         }
75         memcpy(tmpBuffer->data(), (*buffer)->data(), (*buffer)->size());
76         tmpBuffer->setRange(0, (*buffer)->size());
77         (*buffer) = tmpBuffer;
78     }
79 
80     memcpy((*buffer)->data() + (*buffer)->size(), "\x00\x00\x00\x01", 4);
81     memcpy((*buffer)->data() + (*buffer)->size() + 4, ptr, length);
82     (*buffer)->setRange((*buffer)->offset(), (*buffer)->size() + 4 + length);
83     return OK;
84 }
85 
86 #if 0
87 static void convertMetaDataToMessageInt32(
88         const sp<MetaData> &meta, sp<AMessage> &msg, uint32_t key, const char *name) {
89     int32_t value;
90     if (meta->findInt32(key, &value)) {
91         msg->setInt32(name, value);
92     }
93 }
94 #endif
95 
convertMetaDataToMessageColorAspects(const MetaDataBase * meta,sp<AMessage> & msg)96 static void convertMetaDataToMessageColorAspects(const MetaDataBase *meta, sp<AMessage> &msg) {
97     // 0 values are unspecified
98     int32_t range = 0;
99     int32_t primaries = 0;
100     int32_t transferFunction = 0;
101     int32_t colorMatrix = 0;
102     meta->findInt32(kKeyColorRange, &range);
103     meta->findInt32(kKeyColorPrimaries, &primaries);
104     meta->findInt32(kKeyTransferFunction, &transferFunction);
105     meta->findInt32(kKeyColorMatrix, &colorMatrix);
106     ColorAspects colorAspects;
107     memset(&colorAspects, 0, sizeof(colorAspects));
108     colorAspects.mRange = (ColorAspects::Range)range;
109     colorAspects.mPrimaries = (ColorAspects::Primaries)primaries;
110     colorAspects.mTransfer = (ColorAspects::Transfer)transferFunction;
111     colorAspects.mMatrixCoeffs = (ColorAspects::MatrixCoeffs)colorMatrix;
112 
113     int32_t rangeMsg, standardMsg, transferMsg;
114     if (CodecBase::convertCodecColorAspectsToPlatformAspects(
115             colorAspects, &rangeMsg, &standardMsg, &transferMsg) != OK) {
116         return;
117     }
118 
119     // save specified values to msg
120     if (rangeMsg != 0) {
121         msg->setInt32("color-range", rangeMsg);
122     }
123     if (standardMsg != 0) {
124         msg->setInt32("color-standard", standardMsg);
125     }
126     if (transferMsg != 0) {
127         msg->setInt32("color-transfer", transferMsg);
128     }
129 }
130 
131 /**
132  * Returns true if, and only if, the given format corresponds to HDR10 or HDR10+.
133  */
isHdr10or10Plus(const sp<AMessage> & format)134 static bool isHdr10or10Plus(const sp<AMessage> &format) {
135 
136     // if user/container supplied HDR static info without transfer set, assume true
137     if ((format->contains("hdr-static-info") || format->contains("hdr10-plus-info"))
138             && !format->contains("color-transfer")) {
139         return true;
140     }
141     // otherwise, verify that an HDR transfer function is set
142     int32_t transfer;
143     if (format->findInt32("color-transfer", &transfer)) {
144         return transfer == ColorUtils::kColorTransferST2084;
145     }
146     return false;
147 }
148 
parseAacProfileFromCsd(const sp<ABuffer> & csd,sp<AMessage> & format)149 static void parseAacProfileFromCsd(const sp<ABuffer> &csd, sp<AMessage> &format) {
150     if (csd->size() < 2) {
151         return;
152     }
153 
154     uint16_t audioObjectType = U16_AT((uint8_t*)csd->data());
155     if ((audioObjectType & 0xF800) == 0xF800) {
156         audioObjectType = 32 + ((audioObjectType >> 5) & 0x3F);
157     } else {
158         audioObjectType >>= 11;
159     }
160 
161 
162     const static ALookup<uint16_t, int32_t> profiles {
163         { 1,  AACObjectMain     },
164         { 2,  AACObjectLC       },
165         { 3,  AACObjectSSR      },
166         { 4,  AACObjectLTP      },
167         { 5,  AACObjectHE       },
168         { 6,  AACObjectScalable },
169         { 17, AACObjectERLC     },
170         { 23, AACObjectLD       },
171         { 29, AACObjectHE_PS    },
172         { 39, AACObjectELD      },
173         { 42, AACObjectXHE      },
174     };
175 
176     int32_t profile;
177     if (profiles.map(audioObjectType, &profile)) {
178         format->setInt32("profile", profile);
179     }
180 }
181 
parseAvcProfileLevelFromAvcc(const uint8_t * ptr,size_t size,sp<AMessage> & format)182 static void parseAvcProfileLevelFromAvcc(const uint8_t *ptr, size_t size, sp<AMessage> &format) {
183     if (size < 4 || ptr[0] != 1) {  // configurationVersion == 1
184         return;
185     }
186     const uint8_t profile = ptr[1];
187     const uint8_t constraints = ptr[2];
188     const uint8_t level = ptr[3];
189 
190     const static ALookup<uint8_t, int32_t> levels {
191         {  9, AVCLevel1b }, // technically, 9 is only used for High+ profiles
192         { 10, AVCLevel1  },
193         { 11, AVCLevel11 }, // prefer level 1.1 for the value 11
194         { 11, AVCLevel1b },
195         { 12, AVCLevel12 },
196         { 13, AVCLevel13 },
197         { 20, AVCLevel2  },
198         { 21, AVCLevel21 },
199         { 22, AVCLevel22 },
200         { 30, AVCLevel3  },
201         { 31, AVCLevel31 },
202         { 32, AVCLevel32 },
203         { 40, AVCLevel4  },
204         { 41, AVCLevel41 },
205         { 42, AVCLevel42 },
206         { 50, AVCLevel5  },
207         { 51, AVCLevel51 },
208         { 52, AVCLevel52 },
209         { 60, AVCLevel6  },
210         { 61, AVCLevel61 },
211         { 62, AVCLevel62 },
212     };
213     const static ALookup<uint8_t, int32_t> profiles {
214         { 66, AVCProfileBaseline },
215         { 77, AVCProfileMain     },
216         { 88, AVCProfileExtended },
217         { 100, AVCProfileHigh    },
218         { 110, AVCProfileHigh10  },
219         { 122, AVCProfileHigh422 },
220         { 244, AVCProfileHigh444 },
221     };
222 
223     // set profile & level if they are recognized
224     int32_t codecProfile;
225     int32_t codecLevel;
226     if (profiles.map(profile, &codecProfile)) {
227         if (profile == 66 && (constraints & 0x40)) {
228             codecProfile = AVCProfileConstrainedBaseline;
229         } else if (profile == 100 && (constraints & 0x0C) == 0x0C) {
230             codecProfile = AVCProfileConstrainedHigh;
231         }
232         format->setInt32("profile", codecProfile);
233         if (levels.map(level, &codecLevel)) {
234             // for 9 && 11 decide level based on profile and constraint_set3 flag
235             if (level == 11 && (profile == 66 || profile == 77 || profile == 88)) {
236                 codecLevel = (constraints & 0x10) ? AVCLevel1b : AVCLevel11;
237             }
238             format->setInt32("level", codecLevel);
239         }
240     }
241 }
242 
getDolbyVisionProfileTable()243 static const ALookup<uint8_t, int32_t>&  getDolbyVisionProfileTable() {
244     static const ALookup<uint8_t, int32_t> profileTable = {
245         {1, DolbyVisionProfileDvavPen},
246         {3, DolbyVisionProfileDvheDen},
247         {4, DolbyVisionProfileDvheDtr},
248         {5, DolbyVisionProfileDvheStn},
249         {6, DolbyVisionProfileDvheDth},
250         {7, DolbyVisionProfileDvheDtb},
251         {8, DolbyVisionProfileDvheSt},
252         {9, DolbyVisionProfileDvavSe},
253         {10, DolbyVisionProfileDvav110},
254     };
255     return profileTable;
256 }
257 
getDolbyVisionLevelsTable()258 static const ALookup<uint8_t, int32_t>&  getDolbyVisionLevelsTable() {
259     static const ALookup<uint8_t, int32_t> levelsTable = {
260         {0, DolbyVisionLevelUnknown},
261         {1, DolbyVisionLevelHd24},
262         {2, DolbyVisionLevelHd30},
263         {3, DolbyVisionLevelFhd24},
264         {4, DolbyVisionLevelFhd30},
265         {5, DolbyVisionLevelFhd60},
266         {6, DolbyVisionLevelUhd24},
267         {7, DolbyVisionLevelUhd30},
268         {8, DolbyVisionLevelUhd48},
269         {9, DolbyVisionLevelUhd60},
270         {10, DolbyVisionLevelUhd120},
271         {11, DolbyVisionLevel8k30},
272         {12, DolbyVisionLevel8k60},
273     };
274     return levelsTable;
275 }
parseDolbyVisionProfileLevelFromDvcc(const uint8_t * ptr,size_t size,sp<AMessage> & format)276 static void parseDolbyVisionProfileLevelFromDvcc(const uint8_t *ptr, size_t size, sp<AMessage> &format) {
277     // dv_major.dv_minor Should be 1.0 or 2.1
278     if (size != 24 || ((ptr[0] != 1 || ptr[1] != 0) && (ptr[0] != 2 || ptr[1] != 1))) {
279         ALOGV("Size %zu, dv_major %d, dv_minor %d", size, ptr[0], ptr[1]);
280         return;
281     }
282 
283     const uint8_t profile = ptr[2] >> 1;
284     const uint8_t level = ((ptr[2] & 0x1) << 5) | ((ptr[3] >> 3) & 0x1f);
285     const uint8_t rpu_present_flag = (ptr[3] >> 2) & 0x01;
286     const uint8_t el_present_flag = (ptr[3] >> 1) & 0x01;
287     const uint8_t bl_present_flag = (ptr[3] & 0x01);
288     const int32_t bl_compatibility_id = (int32_t)(ptr[4] >> 4);
289 
290     ALOGV("profile-level-compatibility value in dv(c|v)c box %d-%d-%d",
291           profile, level, bl_compatibility_id);
292 
293     // All Dolby Profiles will have profile and level info in MediaFormat
294     // Profile 8 and 9 will have bl_compatibility_id too.
295     const ALookup<uint8_t, int32_t> &profiles = getDolbyVisionProfileTable();
296     const ALookup<uint8_t, int32_t> &levels = getDolbyVisionLevelsTable();
297 
298     // set rpuAssoc
299     if (rpu_present_flag && el_present_flag && !bl_present_flag) {
300         format->setInt32("rpuAssoc", 1);
301     }
302     // set profile & level if they are recognized
303     int32_t codecProfile;
304     int32_t codecLevel;
305     if (profiles.map(profile, &codecProfile)) {
306         format->setInt32("profile", codecProfile);
307         if (codecProfile == DolbyVisionProfileDvheSt ||
308             codecProfile == DolbyVisionProfileDvavSe) {
309             format->setInt32("bl_compatibility_id", bl_compatibility_id);
310         }
311         if (levels.map(level, &codecLevel)) {
312             format->setInt32("level", codecLevel);
313         }
314     }
315 }
316 
parseH263ProfileLevelFromD263(const uint8_t * ptr,size_t size,sp<AMessage> & format)317 static void parseH263ProfileLevelFromD263(const uint8_t *ptr, size_t size, sp<AMessage> &format) {
318     if (size < 7) {
319         return;
320     }
321 
322     const uint8_t profile = ptr[6];
323     const uint8_t level = ptr[5];
324 
325     const static ALookup<uint8_t, int32_t> profiles {
326         { 0, H263ProfileBaseline },
327         { 1, H263ProfileH320Coding },
328         { 2, H263ProfileBackwardCompatible },
329         { 3, H263ProfileISWV2 },
330         { 4, H263ProfileISWV3 },
331         { 5, H263ProfileHighCompression },
332         { 6, H263ProfileInternet },
333         { 7, H263ProfileInterlace },
334         { 8, H263ProfileHighLatency },
335     };
336 
337     const static ALookup<uint8_t, int32_t> levels {
338         { 10, H263Level10 },
339         { 20, H263Level20 },
340         { 30, H263Level30 },
341         { 40, H263Level40 },
342         { 45, H263Level45 },
343         { 50, H263Level50 },
344         { 60, H263Level60 },
345         { 70, H263Level70 },
346     };
347 
348     // set profile & level if they are recognized
349     int32_t codecProfile;
350     int32_t codecLevel;
351     if (profiles.map(profile, &codecProfile)) {
352         format->setInt32("profile", codecProfile);
353         if (levels.map(level, &codecLevel)) {
354             format->setInt32("level", codecLevel);
355         }
356     }
357 }
358 
parseHevcProfileLevelFromHvcc(const uint8_t * ptr,size_t size,sp<AMessage> & format)359 static void parseHevcProfileLevelFromHvcc(const uint8_t *ptr, size_t size, sp<AMessage> &format) {
360     if (size < 13 || ptr[0] != 1) {  // configurationVersion == 1
361         return;
362     }
363 
364     const uint8_t profile = ptr[1] & 0x1F;
365     const uint8_t tier = (ptr[1] & 0x20) >> 5;
366     const uint8_t level = ptr[12];
367 
368     const static ALookup<std::pair<uint8_t, uint8_t>, int32_t> levels {
369         { { 0, 30  }, HEVCMainTierLevel1  },
370         { { 0, 60  }, HEVCMainTierLevel2  },
371         { { 0, 63  }, HEVCMainTierLevel21 },
372         { { 0, 90  }, HEVCMainTierLevel3  },
373         { { 0, 93  }, HEVCMainTierLevel31 },
374         { { 0, 120 }, HEVCMainTierLevel4  },
375         { { 0, 123 }, HEVCMainTierLevel41 },
376         { { 0, 150 }, HEVCMainTierLevel5  },
377         { { 0, 153 }, HEVCMainTierLevel51 },
378         { { 0, 156 }, HEVCMainTierLevel52 },
379         { { 0, 180 }, HEVCMainTierLevel6  },
380         { { 0, 183 }, HEVCMainTierLevel61 },
381         { { 0, 186 }, HEVCMainTierLevel62 },
382         { { 1, 30  }, HEVCHighTierLevel1  },
383         { { 1, 60  }, HEVCHighTierLevel2  },
384         { { 1, 63  }, HEVCHighTierLevel21 },
385         { { 1, 90  }, HEVCHighTierLevel3  },
386         { { 1, 93  }, HEVCHighTierLevel31 },
387         { { 1, 120 }, HEVCHighTierLevel4  },
388         { { 1, 123 }, HEVCHighTierLevel41 },
389         { { 1, 150 }, HEVCHighTierLevel5  },
390         { { 1, 153 }, HEVCHighTierLevel51 },
391         { { 1, 156 }, HEVCHighTierLevel52 },
392         { { 1, 180 }, HEVCHighTierLevel6  },
393         { { 1, 183 }, HEVCHighTierLevel61 },
394         { { 1, 186 }, HEVCHighTierLevel62 },
395     };
396 
397     const static ALookup<uint8_t, int32_t> profiles {
398         { 1, HEVCProfileMain   },
399         { 2, HEVCProfileMain10 },
400         // use Main for Main Still Picture decoding
401         { 3, HEVCProfileMain },
402     };
403 
404     // set profile & level if they are recognized
405     int32_t codecProfile;
406     int32_t codecLevel;
407     if (!profiles.map(profile, &codecProfile)) {
408         if (ptr[2] & 0x40 /* general compatibility flag 1 */) {
409             // Note that this case covers Main Still Picture too
410             codecProfile = HEVCProfileMain;
411         } else if (ptr[2] & 0x20 /* general compatibility flag 2 */) {
412             codecProfile = HEVCProfileMain10;
413         } else {
414             return;
415         }
416     }
417 
418     // bump to HDR profile
419     if (isHdr10or10Plus(format) && codecProfile == HEVCProfileMain10) {
420         if (format->contains("hdr10-plus-info")) {
421             codecProfile = HEVCProfileMain10HDR10Plus;
422         } else {
423             codecProfile = HEVCProfileMain10HDR10;
424         }
425     }
426 
427     format->setInt32("profile", codecProfile);
428     if (levels.map(std::make_pair(tier, level), &codecLevel)) {
429         format->setInt32("level", codecLevel);
430     }
431 }
432 
parseMpeg2ProfileLevelFromHeader(const uint8_t * data,size_t size,sp<AMessage> & format)433 static void parseMpeg2ProfileLevelFromHeader(
434         const uint8_t *data, size_t size, sp<AMessage> &format) {
435     // find sequence extension
436     const uint8_t *seq = (const uint8_t*)memmem(data, size, "\x00\x00\x01\xB5", 4);
437     if (seq != NULL && seq + 5 < data + size) {
438         const uint8_t start_code = seq[4] >> 4;
439         if (start_code != 1 /* sequence extension ID */) {
440             return;
441         }
442         const uint8_t indication = ((seq[4] & 0xF) << 4) | ((seq[5] & 0xF0) >> 4);
443 
444         const static ALookup<uint8_t, int32_t> profiles {
445             { 0x50, MPEG2ProfileSimple  },
446             { 0x40, MPEG2ProfileMain    },
447             { 0x30, MPEG2ProfileSNR     },
448             { 0x20, MPEG2ProfileSpatial },
449             { 0x10, MPEG2ProfileHigh    },
450         };
451 
452         const static ALookup<uint8_t, int32_t> levels {
453             { 0x0A, MPEG2LevelLL  },
454             { 0x08, MPEG2LevelML  },
455             { 0x06, MPEG2LevelH14 },
456             { 0x04, MPEG2LevelHL  },
457             { 0x02, MPEG2LevelHP  },
458         };
459 
460         const static ALookup<uint8_t,
461                 std::pair<int32_t, int32_t>> escapes {
462             /* unsupported
463             { 0x8E, { XXX_MPEG2ProfileMultiView, MPEG2LevelLL  } },
464             { 0x8D, { XXX_MPEG2ProfileMultiView, MPEG2LevelML  } },
465             { 0x8B, { XXX_MPEG2ProfileMultiView, MPEG2LevelH14 } },
466             { 0x8A, { XXX_MPEG2ProfileMultiView, MPEG2LevelHL  } }, */
467             { 0x85, { MPEG2Profile422, MPEG2LevelML  } },
468             { 0x82, { MPEG2Profile422, MPEG2LevelHL  } },
469         };
470 
471         int32_t profile;
472         int32_t level;
473         std::pair<int32_t, int32_t> profileLevel;
474         if (escapes.map(indication, &profileLevel)) {
475             format->setInt32("profile", profileLevel.first);
476             format->setInt32("level", profileLevel.second);
477         } else if (profiles.map(indication & 0x70, &profile)) {
478             format->setInt32("profile", profile);
479             if (levels.map(indication & 0xF, &level)) {
480                 format->setInt32("level", level);
481             }
482         }
483     }
484 }
485 
parseMpeg2ProfileLevelFromEsds(ESDS & esds,sp<AMessage> & format)486 static void parseMpeg2ProfileLevelFromEsds(ESDS &esds, sp<AMessage> &format) {
487     // esds seems to only contain the profile for MPEG-2
488     uint8_t objType;
489     if (esds.getObjectTypeIndication(&objType) == OK) {
490         const static ALookup<uint8_t, int32_t> profiles{
491             { 0x60, MPEG2ProfileSimple  },
492             { 0x61, MPEG2ProfileMain    },
493             { 0x62, MPEG2ProfileSNR     },
494             { 0x63, MPEG2ProfileSpatial },
495             { 0x64, MPEG2ProfileHigh    },
496             { 0x65, MPEG2Profile422     },
497         };
498 
499         int32_t profile;
500         if (profiles.map(objType, &profile)) {
501             format->setInt32("profile", profile);
502         }
503     }
504 }
505 
parseMpeg4ProfileLevelFromCsd(const sp<ABuffer> & csd,sp<AMessage> & format)506 static void parseMpeg4ProfileLevelFromCsd(const sp<ABuffer> &csd, sp<AMessage> &format) {
507     const uint8_t *data = csd->data();
508     // find visual object sequence
509     const uint8_t *seq = (const uint8_t*)memmem(data, csd->size(), "\x00\x00\x01\xB0", 4);
510     if (seq != NULL && seq + 4 < data + csd->size()) {
511         const uint8_t indication = seq[4];
512 
513         const static ALookup<uint8_t,
514                 std::pair<int32_t, int32_t>> table {
515             { 0b00000001, { MPEG4ProfileSimple,            MPEG4Level1  } },
516             { 0b00000010, { MPEG4ProfileSimple,            MPEG4Level2  } },
517             { 0b00000011, { MPEG4ProfileSimple,            MPEG4Level3  } },
518             { 0b00000100, { MPEG4ProfileSimple,            MPEG4Level4a } },
519             { 0b00000101, { MPEG4ProfileSimple,            MPEG4Level5  } },
520             { 0b00000110, { MPEG4ProfileSimple,            MPEG4Level6  } },
521             { 0b00001000, { MPEG4ProfileSimple,            MPEG4Level0  } },
522             { 0b00001001, { MPEG4ProfileSimple,            MPEG4Level0b } },
523             { 0b00010000, { MPEG4ProfileSimpleScalable,    MPEG4Level0  } },
524             { 0b00010001, { MPEG4ProfileSimpleScalable,    MPEG4Level1  } },
525             { 0b00010010, { MPEG4ProfileSimpleScalable,    MPEG4Level2  } },
526             /* unsupported
527             { 0b00011101, { XXX_MPEG4ProfileSimpleScalableER,        MPEG4Level0  } },
528             { 0b00011110, { XXX_MPEG4ProfileSimpleScalableER,        MPEG4Level1  } },
529             { 0b00011111, { XXX_MPEG4ProfileSimpleScalableER,        MPEG4Level2  } }, */
530             { 0b00100001, { MPEG4ProfileCore,              MPEG4Level1  } },
531             { 0b00100010, { MPEG4ProfileCore,              MPEG4Level2  } },
532             { 0b00110010, { MPEG4ProfileMain,              MPEG4Level2  } },
533             { 0b00110011, { MPEG4ProfileMain,              MPEG4Level3  } },
534             { 0b00110100, { MPEG4ProfileMain,              MPEG4Level4  } },
535             /* deprecated
536             { 0b01000010, { MPEG4ProfileNbit,              MPEG4Level2  } }, */
537             { 0b01010001, { MPEG4ProfileScalableTexture,   MPEG4Level1  } },
538             { 0b01100001, { MPEG4ProfileSimpleFace,        MPEG4Level1  } },
539             { 0b01100010, { MPEG4ProfileSimpleFace,        MPEG4Level2  } },
540             { 0b01100011, { MPEG4ProfileSimpleFBA,         MPEG4Level1  } },
541             { 0b01100100, { MPEG4ProfileSimpleFBA,         MPEG4Level2  } },
542             { 0b01110001, { MPEG4ProfileBasicAnimated,     MPEG4Level1  } },
543             { 0b01110010, { MPEG4ProfileBasicAnimated,     MPEG4Level2  } },
544             { 0b10000001, { MPEG4ProfileHybrid,            MPEG4Level1  } },
545             { 0b10000010, { MPEG4ProfileHybrid,            MPEG4Level2  } },
546             { 0b10010001, { MPEG4ProfileAdvancedRealTime,  MPEG4Level1  } },
547             { 0b10010010, { MPEG4ProfileAdvancedRealTime,  MPEG4Level2  } },
548             { 0b10010011, { MPEG4ProfileAdvancedRealTime,  MPEG4Level3  } },
549             { 0b10010100, { MPEG4ProfileAdvancedRealTime,  MPEG4Level4  } },
550             { 0b10100001, { MPEG4ProfileCoreScalable,      MPEG4Level1  } },
551             { 0b10100010, { MPEG4ProfileCoreScalable,      MPEG4Level2  } },
552             { 0b10100011, { MPEG4ProfileCoreScalable,      MPEG4Level3  } },
553             { 0b10110001, { MPEG4ProfileAdvancedCoding,    MPEG4Level1  } },
554             { 0b10110010, { MPEG4ProfileAdvancedCoding,    MPEG4Level2  } },
555             { 0b10110011, { MPEG4ProfileAdvancedCoding,    MPEG4Level3  } },
556             { 0b10110100, { MPEG4ProfileAdvancedCoding,    MPEG4Level4  } },
557             { 0b11000001, { MPEG4ProfileAdvancedCore,      MPEG4Level1  } },
558             { 0b11000010, { MPEG4ProfileAdvancedCore,      MPEG4Level2  } },
559             { 0b11010001, { MPEG4ProfileAdvancedScalable,  MPEG4Level1  } },
560             { 0b11010010, { MPEG4ProfileAdvancedScalable,  MPEG4Level2  } },
561             { 0b11010011, { MPEG4ProfileAdvancedScalable,  MPEG4Level3  } },
562             /* unsupported
563             { 0b11100001, { XXX_MPEG4ProfileSimpleStudio,            MPEG4Level1  } },
564             { 0b11100010, { XXX_MPEG4ProfileSimpleStudio,            MPEG4Level2  } },
565             { 0b11100011, { XXX_MPEG4ProfileSimpleStudio,            MPEG4Level3  } },
566             { 0b11100100, { XXX_MPEG4ProfileSimpleStudio,            MPEG4Level4  } },
567             { 0b11100101, { XXX_MPEG4ProfileCoreStudio,              MPEG4Level1  } },
568             { 0b11100110, { XXX_MPEG4ProfileCoreStudio,              MPEG4Level2  } },
569             { 0b11100111, { XXX_MPEG4ProfileCoreStudio,              MPEG4Level3  } },
570             { 0b11101000, { XXX_MPEG4ProfileCoreStudio,              MPEG4Level4  } },
571             { 0b11101011, { XXX_MPEG4ProfileSimpleStudio,            MPEG4Level5  } },
572             { 0b11101100, { XXX_MPEG4ProfileSimpleStudio,            MPEG4Level6  } }, */
573             { 0b11110000, { MPEG4ProfileAdvancedSimple,    MPEG4Level0  } },
574             { 0b11110001, { MPEG4ProfileAdvancedSimple,    MPEG4Level1  } },
575             { 0b11110010, { MPEG4ProfileAdvancedSimple,    MPEG4Level2  } },
576             { 0b11110011, { MPEG4ProfileAdvancedSimple,    MPEG4Level3  } },
577             { 0b11110100, { MPEG4ProfileAdvancedSimple,    MPEG4Level4  } },
578             { 0b11110101, { MPEG4ProfileAdvancedSimple,    MPEG4Level5  } },
579             { 0b11110111, { MPEG4ProfileAdvancedSimple,    MPEG4Level3b } },
580             /* deprecated
581             { 0b11111000, { XXX_MPEG4ProfileFineGranularityScalable, MPEG4Level0  } },
582             { 0b11111001, { XXX_MPEG4ProfileFineGranularityScalable, MPEG4Level1  } },
583             { 0b11111010, { XXX_MPEG4ProfileFineGranularityScalable, MPEG4Level2  } },
584             { 0b11111011, { XXX_MPEG4ProfileFineGranularityScalable, MPEG4Level3  } },
585             { 0b11111100, { XXX_MPEG4ProfileFineGranularityScalable, MPEG4Level4  } },
586             { 0b11111101, { XXX_MPEG4ProfileFineGranularityScalable, MPEG4Level5  } }, */
587         };
588 
589         std::pair<int32_t, int32_t> profileLevel;
590         if (table.map(indication, &profileLevel)) {
591             format->setInt32("profile", profileLevel.first);
592             format->setInt32("level", profileLevel.second);
593         }
594     }
595 }
596 
parseVp9ProfileLevelFromCsd(const sp<ABuffer> & csd,sp<AMessage> & format)597 static void parseVp9ProfileLevelFromCsd(const sp<ABuffer> &csd, sp<AMessage> &format) {
598     const uint8_t *data = csd->data();
599     size_t remaining = csd->size();
600 
601     while (remaining >= 2) {
602         const uint8_t id = data[0];
603         const uint8_t length = data[1];
604         remaining -= 2;
605         data += 2;
606         if (length > remaining) {
607             break;
608         }
609         switch (id) {
610             case 1 /* profileId */:
611                 if (length >= 1) {
612                     const static ALookup<uint8_t, int32_t> profiles {
613                         { 0, VP9Profile0 },
614                         { 1, VP9Profile1 },
615                         { 2, VP9Profile2 },
616                         { 3, VP9Profile3 },
617                     };
618 
619                     const static ALookup<int32_t, int32_t> toHdr10 {
620                         { VP9Profile2, VP9Profile2HDR },
621                         { VP9Profile3, VP9Profile3HDR },
622                     };
623 
624                     const static ALookup<int32_t, int32_t> toHdr10Plus {
625                         { VP9Profile2, VP9Profile2HDR10Plus },
626                         { VP9Profile3, VP9Profile3HDR10Plus },
627                     };
628 
629                     int32_t profile;
630                     if (profiles.map(data[0], &profile)) {
631                         // convert to HDR profile
632                         if (isHdr10or10Plus(format)) {
633                             if (format->contains("hdr10-plus-info")) {
634                                 toHdr10Plus.lookup(profile, &profile);
635                             } else {
636                                 toHdr10.lookup(profile, &profile);
637                             }
638                         }
639 
640                         format->setInt32("profile", profile);
641                     }
642                 }
643                 break;
644             case 2 /* levelId */:
645                 if (length >= 1) {
646                     const static ALookup<uint8_t, int32_t> levels {
647                         { 10, VP9Level1  },
648                         { 11, VP9Level11 },
649                         { 20, VP9Level2  },
650                         { 21, VP9Level21 },
651                         { 30, VP9Level3  },
652                         { 31, VP9Level31 },
653                         { 40, VP9Level4  },
654                         { 41, VP9Level41 },
655                         { 50, VP9Level5  },
656                         { 51, VP9Level51 },
657                         { 52, VP9Level52 },
658                         { 60, VP9Level6  },
659                         { 61, VP9Level61 },
660                         { 62, VP9Level62 },
661                     };
662 
663                     int32_t level;
664                     if (levels.map(data[0], &level)) {
665                         format->setInt32("level", level);
666                     }
667                 }
668                 break;
669             default:
670                 break;
671         }
672         remaining -= length;
673         data += length;
674     }
675 }
676 
parseAV1ProfileLevelFromCsd(const sp<ABuffer> & csd,sp<AMessage> & format)677 static void parseAV1ProfileLevelFromCsd(const sp<ABuffer> &csd, sp<AMessage> &format) {
678     // Parse CSD structure to extract profile level information
679     // https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox
680     const uint8_t *data = csd->data();
681     size_t remaining = csd->size();
682     if (remaining < 4 || data[0] != 0x81) {  // configurationVersion == 1
683         return;
684     }
685     uint8_t profileData = (data[1] & 0xE0) >> 5;
686     uint8_t levelData = data[1] & 0x1F;
687     uint8_t highBitDepth = (data[2] & 0x40) >> 6;
688 
689     const static ALookup<std::pair<uint8_t, uint8_t>, int32_t> profiles {
690         { { 0, 0 }, AV1ProfileMain8 },
691         { { 1, 0 }, AV1ProfileMain10 },
692     };
693 
694     int32_t profile;
695     if (profiles.map(std::make_pair(highBitDepth, profileData), &profile)) {
696         // bump to HDR profile
697         if (isHdr10or10Plus(format) && profile == AV1ProfileMain10) {
698             if (format->contains("hdr10-plus-info")) {
699                 profile = AV1ProfileMain10HDR10Plus;
700             } else {
701                 profile = AV1ProfileMain10HDR10;
702             }
703         }
704         format->setInt32("profile", profile);
705     }
706     const static ALookup<uint8_t, int32_t> levels {
707         { 0, AV1Level2   },
708         { 1, AV1Level21  },
709         { 2, AV1Level22  },
710         { 3, AV1Level23  },
711         { 4, AV1Level3   },
712         { 5, AV1Level31  },
713         { 6, AV1Level32  },
714         { 7, AV1Level33  },
715         { 8, AV1Level4   },
716         { 9, AV1Level41  },
717         { 10, AV1Level42  },
718         { 11, AV1Level43  },
719         { 12, AV1Level5   },
720         { 13, AV1Level51  },
721         { 14, AV1Level52  },
722         { 15, AV1Level53  },
723         { 16, AV1Level6   },
724         { 17, AV1Level61  },
725         { 18, AV1Level62  },
726         { 19, AV1Level63  },
727         { 20, AV1Level7   },
728         { 21, AV1Level71  },
729         { 22, AV1Level72  },
730         { 23, AV1Level73  },
731     };
732 
733     int32_t level;
734     if (levels.map(levelData, &level)) {
735         format->setInt32("level", level);
736     }
737 }
738 
739 
740 static std::vector<std::pair<const char *, uint32_t>> stringMappings {
741     {
742         { "album", kKeyAlbum },
743         { "albumartist", kKeyAlbumArtist },
744         { "artist", kKeyArtist },
745         { "author", kKeyAuthor },
746         { "cdtracknum", kKeyCDTrackNumber },
747         { "compilation", kKeyCompilation },
748         { "composer", kKeyComposer },
749         { "date", kKeyDate },
750         { "discnum", kKeyDiscNumber },
751         { "genre", kKeyGenre },
752         { "location", kKeyLocation },
753         { "lyricist", kKeyWriter },
754         { "manufacturer", kKeyManufacturer },
755         { "title", kKeyTitle },
756         { "year", kKeyYear },
757     }
758 };
759 
760 static std::vector<std::pair<const char *, uint32_t>> floatMappings {
761     {
762         { "capture-rate", kKeyCaptureFramerate },
763     }
764 };
765 
766 static std::vector<std::pair<const char*, uint32_t>> int64Mappings {
767     {
768         { "exif-offset", kKeyExifOffset},
769         { "exif-size", kKeyExifSize},
770         { "xmp-offset", kKeyXmpOffset},
771         { "xmp-size", kKeyXmpSize},
772         { "target-time", kKeyTargetTime},
773         { "thumbnail-time", kKeyThumbnailTime},
774         { "timeUs", kKeyTime},
775         { "durationUs", kKeyDuration},
776         { "sample-file-offset", kKeySampleFileOffset},
777         { "last-sample-index-in-chunk", kKeyLastSampleIndexInChunk},
778         { "sample-time-before-append", kKeySampleTimeBeforeAppend},
779     }
780 };
781 
782 static std::vector<std::pair<const char *, uint32_t>> int32Mappings {
783     {
784         { "loop", kKeyAutoLoop },
785         { "time-scale", kKeyTimeScale },
786         { "crypto-mode", kKeyCryptoMode },
787         { "crypto-default-iv-size", kKeyCryptoDefaultIVSize },
788         { "crypto-encrypted-byte-block", kKeyEncryptedByteBlock },
789         { "crypto-skip-byte-block", kKeySkipByteBlock },
790         { "frame-count", kKeyFrameCount },
791         { "max-bitrate", kKeyMaxBitRate },
792         { "pcm-big-endian", kKeyPcmBigEndian },
793         { "temporal-layer-count", kKeyTemporalLayerCount },
794         { "temporal-layer-id", kKeyTemporalLayerId },
795         { "thumbnail-width", kKeyThumbnailWidth },
796         { "thumbnail-height", kKeyThumbnailHeight },
797         { "track-id", kKeyTrackID },
798         { "valid-samples", kKeyValidSamples },
799         { "dvb-component-tag", kKeyDvbComponentTag},
800         { "dvb-audio-description", kKeyDvbAudioDescription},
801         { "dvb-teletext-magazine-number", kKeyDvbTeletextMagazineNumber},
802         { "dvb-teletext-page-number", kKeyDvbTeletextPageNumber},
803         { "profile", kKeyAudioProfile },
804         { "level", kKeyAudioLevel },
805     }
806 };
807 
808 static std::vector<std::pair<const char *, uint32_t>> bufferMappings {
809     {
810         { "albumart", kKeyAlbumArt },
811         { "audio-presentation-info", kKeyAudioPresentationInfo },
812         { "pssh", kKeyPssh },
813         { "crypto-iv", kKeyCryptoIV },
814         { "crypto-key", kKeyCryptoKey },
815         { "crypto-encrypted-sizes", kKeyEncryptedSizes },
816         { "crypto-plain-sizes", kKeyPlainSizes },
817         { "icc-profile", kKeyIccProfile },
818         { "sei", kKeySEI },
819         { "text-format-data", kKeyTextFormatData },
820         { "thumbnail-csd-hevc", kKeyThumbnailHVCC },
821         { "slow-motion-markers", kKeySlowMotionMarkers },
822         { "thumbnail-csd-av1c", kKeyThumbnailAV1C },
823     }
824 };
825 
826 static std::vector<std::pair<const char *, uint32_t>> CSDMappings {
827     {
828         { "csd-0", kKeyOpaqueCSD0 },
829         { "csd-1", kKeyOpaqueCSD1 },
830         { "csd-2", kKeyOpaqueCSD2 },
831     }
832 };
833 
convertMessageToMetaDataFromMappings(const sp<AMessage> & msg,sp<MetaData> & meta)834 void convertMessageToMetaDataFromMappings(const sp<AMessage> &msg, sp<MetaData> &meta) {
835     for (auto elem : stringMappings) {
836         AString value;
837         if (msg->findString(elem.first, &value)) {
838             meta->setCString(elem.second, value.c_str());
839         }
840     }
841 
842     for (auto elem : floatMappings) {
843         float value;
844         if (msg->findFloat(elem.first, &value)) {
845             meta->setFloat(elem.second, value);
846         }
847     }
848 
849     for (auto elem : int64Mappings) {
850         int64_t value;
851         if (msg->findInt64(elem.first, &value)) {
852             meta->setInt64(elem.second, value);
853         }
854     }
855 
856     for (auto elem : int32Mappings) {
857         int32_t value;
858         if (msg->findInt32(elem.first, &value)) {
859             meta->setInt32(elem.second, value);
860         }
861     }
862 
863     for (auto elem : bufferMappings) {
864         sp<ABuffer> value;
865         if (msg->findBuffer(elem.first, &value)) {
866             meta->setData(elem.second,
867                     MetaDataBase::Type::TYPE_NONE, value->data(), value->size());
868         }
869     }
870 
871     for (auto elem : CSDMappings) {
872         sp<ABuffer> value;
873         if (msg->findBuffer(elem.first, &value)) {
874             meta->setData(elem.second,
875                     MetaDataBase::Type::TYPE_NONE, value->data(), value->size());
876         }
877     }
878 }
879 
convertMetaDataToMessageFromMappings(const MetaDataBase * meta,sp<AMessage> format)880 void convertMetaDataToMessageFromMappings(const MetaDataBase *meta, sp<AMessage> format) {
881     for (auto elem : stringMappings) {
882         const char *value;
883         if (meta->findCString(elem.second, &value)) {
884             format->setString(elem.first, value, strlen(value));
885         }
886     }
887 
888     for (auto elem : floatMappings) {
889         float value;
890         if (meta->findFloat(elem.second, &value)) {
891             format->setFloat(elem.first, value);
892         }
893     }
894 
895     for (auto elem : int64Mappings) {
896         int64_t value;
897         if (meta->findInt64(elem.second, &value)) {
898             format->setInt64(elem.first, value);
899         }
900     }
901 
902     for (auto elem : int32Mappings) {
903         int32_t value;
904         if (meta->findInt32(elem.second, &value)) {
905             format->setInt32(elem.first, value);
906         }
907     }
908 
909     for (auto elem : bufferMappings) {
910         uint32_t type;
911         const void* data;
912         size_t size;
913         if (meta->findData(elem.second, &type, &data, &size)) {
914             sp<ABuffer> buf = ABuffer::CreateAsCopy(data, size);
915             format->setBuffer(elem.first, buf);
916         }
917     }
918 
919     for (auto elem : CSDMappings) {
920         uint32_t type;
921         const void* data;
922         size_t size;
923         if (meta->findData(elem.second, &type, &data, &size)) {
924             sp<ABuffer> buf = ABuffer::CreateAsCopy(data, size);
925             buf->meta()->setInt32("csd", true);
926             buf->meta()->setInt64("timeUs", 0);
927             format->setBuffer(elem.first, buf);
928         }
929     }
930 }
931 
convertMetaDataToMessage(const sp<MetaData> & meta,sp<AMessage> * format)932 status_t convertMetaDataToMessage(
933         const sp<MetaData> &meta, sp<AMessage> *format) {
934     return convertMetaDataToMessage(meta.get(), format);
935 }
936 
convertMetaDataToMessage(const MetaDataBase * meta,sp<AMessage> * format)937 status_t convertMetaDataToMessage(
938         const MetaDataBase *meta, sp<AMessage> *format) {
939 
940     format->clear();
941 
942     if (meta == NULL) {
943         ALOGE("convertMetaDataToMessage: NULL input");
944         return BAD_VALUE;
945     }
946 
947     const char *mime;
948     if (!meta->findCString(kKeyMIMEType, &mime)) {
949         return BAD_VALUE;
950     }
951 
952     sp<AMessage> msg = new AMessage;
953     msg->setString("mime", mime);
954 
955     convertMetaDataToMessageFromMappings(meta, msg);
956 
957     uint32_t type;
958     const void *data;
959     size_t size;
960     if (meta->findData(kKeyCASessionID, &type, &data, &size)) {
961         sp<ABuffer> buffer = new (std::nothrow) ABuffer(size);
962         if (buffer.get() == NULL || buffer->base() == NULL) {
963             return NO_MEMORY;
964         }
965 
966         msg->setBuffer("ca-session-id", buffer);
967         memcpy(buffer->data(), data, size);
968     }
969 
970     if (meta->findData(kKeyCAPrivateData, &type, &data, &size)) {
971         sp<ABuffer> buffer = new (std::nothrow) ABuffer(size);
972         if (buffer.get() == NULL || buffer->base() == NULL) {
973             return NO_MEMORY;
974         }
975 
976         msg->setBuffer("ca-private-data", buffer);
977         memcpy(buffer->data(), data, size);
978     }
979 
980     int32_t systemId;
981     if (meta->findInt32(kKeyCASystemID, &systemId)) {
982         msg->setInt32("ca-system-id", systemId);
983     }
984 
985     if (!strncasecmp("video/scrambled", mime, 15)
986             || !strncasecmp("audio/scrambled", mime, 15)) {
987 
988         *format = msg;
989         return OK;
990     }
991 
992     int64_t durationUs;
993     if (meta->findInt64(kKeyDuration, &durationUs)) {
994         msg->setInt64("durationUs", durationUs);
995     }
996 
997     int32_t avgBitRate = 0;
998     if (meta->findInt32(kKeyBitRate, &avgBitRate) && avgBitRate > 0) {
999         msg->setInt32("bitrate", avgBitRate);
1000     }
1001 
1002     int32_t maxBitRate;
1003     if (meta->findInt32(kKeyMaxBitRate, &maxBitRate)
1004             && maxBitRate > 0 && maxBitRate >= avgBitRate) {
1005         msg->setInt32("max-bitrate", maxBitRate);
1006     }
1007 
1008     int32_t isSync;
1009     if (meta->findInt32(kKeyIsSyncFrame, &isSync) && isSync != 0) {
1010         msg->setInt32("is-sync-frame", 1);
1011     }
1012 
1013     int32_t dvbComponentTag = 0;
1014     if (meta->findInt32(kKeyDvbComponentTag, &dvbComponentTag)) {
1015         msg->setInt32("dvb-component-tag", dvbComponentTag);
1016     }
1017 
1018     int32_t dvbAudioDescription = 0;
1019     if (meta->findInt32(kKeyDvbAudioDescription, &dvbAudioDescription)) {
1020         msg->setInt32("dvb-audio-description", dvbAudioDescription);
1021     }
1022 
1023     int32_t dvbTeletextMagazineNumber = 0;
1024     if (meta->findInt32(kKeyDvbTeletextMagazineNumber, &dvbTeletextMagazineNumber)) {
1025         msg->setInt32("dvb-teletext-magazine-number", dvbTeletextMagazineNumber);
1026     }
1027 
1028     int32_t dvbTeletextPageNumber = 0;
1029     if (meta->findInt32(kKeyDvbTeletextPageNumber, &dvbTeletextPageNumber)) {
1030         msg->setInt32("dvb-teletext-page-number", dvbTeletextPageNumber);
1031     }
1032 
1033     const char *lang;
1034     if (meta->findCString(kKeyMediaLanguage, &lang)) {
1035         msg->setString("language", lang);
1036     }
1037 
1038     if (!strncasecmp("video/", mime, 6) ||
1039             !strncasecmp("image/", mime, 6)) {
1040         int32_t width, height;
1041         if (!meta->findInt32(kKeyWidth, &width)
1042                 || !meta->findInt32(kKeyHeight, &height)) {
1043             return BAD_VALUE;
1044         }
1045 
1046         msg->setInt32("width", width);
1047         msg->setInt32("height", height);
1048 
1049         int32_t displayWidth, displayHeight;
1050         if (meta->findInt32(kKeyDisplayWidth, &displayWidth)
1051                 && meta->findInt32(kKeyDisplayHeight, &displayHeight)) {
1052             msg->setInt32("display-width", displayWidth);
1053             msg->setInt32("display-height", displayHeight);
1054         }
1055 
1056         int32_t sarWidth, sarHeight;
1057         if (meta->findInt32(kKeySARWidth, &sarWidth)
1058                 && meta->findInt32(kKeySARHeight, &sarHeight)) {
1059             msg->setInt32("sar-width", sarWidth);
1060             msg->setInt32("sar-height", sarHeight);
1061         }
1062 
1063         if (!strncasecmp("image/", mime, 6)) {
1064             int32_t tileWidth, tileHeight, gridRows, gridCols;
1065             if (meta->findInt32(kKeyTileWidth, &tileWidth)
1066                     && meta->findInt32(kKeyTileHeight, &tileHeight)
1067                     && meta->findInt32(kKeyGridRows, &gridRows)
1068                     && meta->findInt32(kKeyGridCols, &gridCols)) {
1069                 msg->setInt32("tile-width", tileWidth);
1070                 msg->setInt32("tile-height", tileHeight);
1071                 msg->setInt32("grid-rows", gridRows);
1072                 msg->setInt32("grid-cols", gridCols);
1073             }
1074             int32_t isPrimary;
1075             if (meta->findInt32(kKeyTrackIsDefault, &isPrimary) && isPrimary) {
1076                 msg->setInt32("is-default", 1);
1077             }
1078         }
1079 
1080         int32_t colorFormat;
1081         if (meta->findInt32(kKeyColorFormat, &colorFormat)) {
1082             msg->setInt32("color-format", colorFormat);
1083         }
1084 
1085         int32_t cropLeft, cropTop, cropRight, cropBottom;
1086         if (meta->findRect(kKeyCropRect,
1087                            &cropLeft,
1088                            &cropTop,
1089                            &cropRight,
1090                            &cropBottom)) {
1091             msg->setRect("crop", cropLeft, cropTop, cropRight, cropBottom);
1092         }
1093 
1094         int32_t rotationDegrees;
1095         if (meta->findInt32(kKeyRotation, &rotationDegrees)) {
1096             msg->setInt32("rotation-degrees", rotationDegrees);
1097         }
1098 
1099         uint32_t type;
1100         const void *data;
1101         size_t size;
1102         if (meta->findData(kKeyHdrStaticInfo, &type, &data, &size)
1103                 && type == 'hdrS' && size == sizeof(HDRStaticInfo)) {
1104             ColorUtils::setHDRStaticInfoIntoFormat(*(HDRStaticInfo*)data, msg);
1105         }
1106 
1107         if (meta->findData(kKeyHdr10PlusInfo, &type, &data, &size)
1108                 && size > 0) {
1109             sp<ABuffer> buffer = new (std::nothrow) ABuffer(size);
1110             if (buffer.get() == NULL || buffer->base() == NULL) {
1111                 return NO_MEMORY;
1112             }
1113             memcpy(buffer->data(), data, size);
1114             msg->setBuffer("hdr10-plus-info", buffer);
1115         }
1116 
1117         convertMetaDataToMessageColorAspects(meta, msg);
1118     } else if (!strncasecmp("audio/", mime, 6)) {
1119         int32_t numChannels, sampleRate;
1120         if (!meta->findInt32(kKeyChannelCount, &numChannels)
1121                 || !meta->findInt32(kKeySampleRate, &sampleRate)) {
1122             return BAD_VALUE;
1123         }
1124 
1125         msg->setInt32("channel-count", numChannels);
1126         msg->setInt32("sample-rate", sampleRate);
1127 
1128         int32_t bitsPerSample;
1129         if (meta->findInt32(kKeyBitsPerSample, &bitsPerSample)) {
1130             msg->setInt32("bits-per-sample", bitsPerSample);
1131         }
1132 
1133         int32_t channelMask;
1134         if (meta->findInt32(kKeyChannelMask, &channelMask)) {
1135             msg->setInt32("channel-mask", channelMask);
1136         }
1137 
1138         int32_t delay = 0;
1139         if (meta->findInt32(kKeyEncoderDelay, &delay)) {
1140             msg->setInt32("encoder-delay", delay);
1141         }
1142         int32_t padding = 0;
1143         if (meta->findInt32(kKeyEncoderPadding, &padding)) {
1144             msg->setInt32("encoder-padding", padding);
1145         }
1146 
1147         int32_t isADTS;
1148         if (meta->findInt32(kKeyIsADTS, &isADTS)) {
1149             msg->setInt32("is-adts", isADTS);
1150         }
1151 
1152         int32_t mpeghProfileLevelIndication;
1153         if (meta->findInt32(kKeyMpeghProfileLevelIndication, &mpeghProfileLevelIndication)) {
1154             msg->setInt32(AMEDIAFORMAT_KEY_MPEGH_PROFILE_LEVEL_INDICATION,
1155                     mpeghProfileLevelIndication);
1156         }
1157         int32_t mpeghReferenceChannelLayout;
1158         if (meta->findInt32(kKeyMpeghReferenceChannelLayout, &mpeghReferenceChannelLayout)) {
1159             msg->setInt32(AMEDIAFORMAT_KEY_MPEGH_REFERENCE_CHANNEL_LAYOUT,
1160                     mpeghReferenceChannelLayout);
1161         }
1162         if (meta->findData(kKeyMpeghCompatibleSets, &type, &data, &size)) {
1163             sp<ABuffer> buffer = new (std::nothrow) ABuffer(size);
1164             if (buffer.get() == NULL || buffer->base() == NULL) {
1165                 return NO_MEMORY;
1166             }
1167             msg->setBuffer(AMEDIAFORMAT_KEY_MPEGH_COMPATIBLE_SETS, buffer);
1168             memcpy(buffer->data(), data, size);
1169         }
1170 
1171         int32_t aacProfile = -1;
1172         if (meta->findInt32(kKeyAACAOT, &aacProfile)) {
1173             msg->setInt32("aac-profile", aacProfile);
1174         }
1175 
1176         int32_t pcmEncoding;
1177         if (meta->findInt32(kKeyPcmEncoding, &pcmEncoding)) {
1178             msg->setInt32("pcm-encoding", pcmEncoding);
1179         }
1180 
1181         int32_t hapticChannelCount;
1182         if (meta->findInt32(kKeyHapticChannelCount, &hapticChannelCount)) {
1183             msg->setInt32("haptic-channel-count", hapticChannelCount);
1184         }
1185     }
1186 
1187     int32_t maxInputSize;
1188     if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
1189         msg->setInt32("max-input-size", maxInputSize);
1190     }
1191 
1192     int32_t maxWidth;
1193     if (meta->findInt32(kKeyMaxWidth, &maxWidth)) {
1194         msg->setInt32("max-width", maxWidth);
1195     }
1196 
1197     int32_t maxHeight;
1198     if (meta->findInt32(kKeyMaxHeight, &maxHeight)) {
1199         msg->setInt32("max-height", maxHeight);
1200     }
1201 
1202     int32_t rotationDegrees;
1203     if (meta->findInt32(kKeyRotation, &rotationDegrees)) {
1204         msg->setInt32("rotation-degrees", rotationDegrees);
1205     }
1206 
1207     int32_t fps;
1208     if (meta->findInt32(kKeyFrameRate, &fps) && fps > 0) {
1209         msg->setInt32("frame-rate", fps);
1210     }
1211 
1212     if (meta->findData(kKeyAVCC, &type, &data, &size)) {
1213         // Parse the AVCDecoderConfigurationRecord
1214 
1215         const uint8_t *ptr = (const uint8_t *)data;
1216 
1217         if (size < 7 || ptr[0] != 1) {  // configurationVersion == 1
1218             ALOGE("b/23680780");
1219             return BAD_VALUE;
1220         }
1221 
1222         parseAvcProfileLevelFromAvcc(ptr, size, msg);
1223 
1224         // There is decodable content out there that fails the following
1225         // assertion, let's be lenient for now...
1226         // CHECK((ptr[4] >> 2) == 0x3f);  // reserved
1227 
1228         // we can get lengthSize value from 1 + (ptr[4] & 3)
1229 
1230         // commented out check below as H264_QVGA_500_NO_AUDIO.3gp
1231         // violates it...
1232         // CHECK((ptr[5] >> 5) == 7);  // reserved
1233 
1234         size_t numSeqParameterSets = ptr[5] & 31;
1235 
1236         ptr += 6;
1237         size -= 6;
1238 
1239         sp<ABuffer> buffer = new (std::nothrow) ABuffer(1024);
1240         if (buffer.get() == NULL || buffer->base() == NULL) {
1241             return NO_MEMORY;
1242         }
1243         buffer->setRange(0, 0);
1244 
1245         for (size_t i = 0; i < numSeqParameterSets; ++i) {
1246             if (size < 2) {
1247                 ALOGE("b/23680780");
1248                 return BAD_VALUE;
1249             }
1250             size_t length = U16_AT(ptr);
1251 
1252             ptr += 2;
1253             size -= 2;
1254 
1255             if (size < length) {
1256                 return BAD_VALUE;
1257             }
1258             status_t err = copyNALUToABuffer(&buffer, ptr, length);
1259             if (err != OK) {
1260                 return err;
1261             }
1262 
1263             ptr += length;
1264             size -= length;
1265         }
1266 
1267         buffer->meta()->setInt32("csd", true);
1268         buffer->meta()->setInt64("timeUs", 0);
1269 
1270         msg->setBuffer("csd-0", buffer);
1271 
1272         buffer = new (std::nothrow) ABuffer(1024);
1273         if (buffer.get() == NULL || buffer->base() == NULL) {
1274             return NO_MEMORY;
1275         }
1276         buffer->setRange(0, 0);
1277 
1278         if (size < 1) {
1279             ALOGE("b/23680780");
1280             return BAD_VALUE;
1281         }
1282         size_t numPictureParameterSets = *ptr;
1283         ++ptr;
1284         --size;
1285 
1286         for (size_t i = 0; i < numPictureParameterSets; ++i) {
1287             if (size < 2) {
1288                 ALOGE("b/23680780");
1289                 return BAD_VALUE;
1290             }
1291             size_t length = U16_AT(ptr);
1292 
1293             ptr += 2;
1294             size -= 2;
1295 
1296             if (size < length) {
1297                 return BAD_VALUE;
1298             }
1299             status_t err = copyNALUToABuffer(&buffer, ptr, length);
1300             if (err != OK) {
1301                 return err;
1302             }
1303 
1304             ptr += length;
1305             size -= length;
1306         }
1307 
1308         buffer->meta()->setInt32("csd", true);
1309         buffer->meta()->setInt64("timeUs", 0);
1310         msg->setBuffer("csd-1", buffer);
1311     } else if (meta->findData(kKeyHVCC, &type, &data, &size)) {
1312         const uint8_t *ptr = (const uint8_t *)data;
1313 
1314         if (size < 23 || (ptr[0] != 1 && ptr[0] != 0)) {
1315             // configurationVersion == 1 or 0
1316             // 1 is what the standard dictates, but some old muxers may have used 0.
1317             ALOGE("b/23680780");
1318             return BAD_VALUE;
1319         }
1320 
1321         const size_t dataSize = size; // save for later
1322         ptr += 22;
1323         size -= 22;
1324 
1325         size_t numofArrays = (char)ptr[0];
1326         ptr += 1;
1327         size -= 1;
1328         size_t j = 0, i = 0;
1329 
1330         sp<ABuffer> buffer = new (std::nothrow) ABuffer(1024);
1331         if (buffer.get() == NULL || buffer->base() == NULL) {
1332             return NO_MEMORY;
1333         }
1334         buffer->setRange(0, 0);
1335 
1336         HevcParameterSets hvcc;
1337 
1338         for (i = 0; i < numofArrays; i++) {
1339             if (size < 3) {
1340                 ALOGE("b/23680780");
1341                 return BAD_VALUE;
1342             }
1343             ptr += 1;
1344             size -= 1;
1345 
1346             //Num of nals
1347             size_t numofNals = U16_AT(ptr);
1348 
1349             ptr += 2;
1350             size -= 2;
1351 
1352             for (j = 0; j < numofNals; j++) {
1353                 if (size < 2) {
1354                     ALOGE("b/23680780");
1355                     return BAD_VALUE;
1356                 }
1357                 size_t length = U16_AT(ptr);
1358 
1359                 ptr += 2;
1360                 size -= 2;
1361 
1362                 if (size < length) {
1363                     return BAD_VALUE;
1364                 }
1365                 status_t err = copyNALUToABuffer(&buffer, ptr, length);
1366                 if (err != OK) {
1367                     return err;
1368                 }
1369                 (void)hvcc.addNalUnit(ptr, length);
1370 
1371                 ptr += length;
1372                 size -= length;
1373             }
1374         }
1375         buffer->meta()->setInt32("csd", true);
1376         buffer->meta()->setInt64("timeUs", 0);
1377         msg->setBuffer("csd-0", buffer);
1378 
1379         // if we saw VUI color information we know whether this is HDR because VUI trumps other
1380         // format parameters for HEVC.
1381         HevcParameterSets::Info info = hvcc.getInfo();
1382         if (info & hvcc.kInfoHasColorDescription) {
1383             msg->setInt32("android._is-hdr", (info & hvcc.kInfoIsHdr) != 0);
1384         }
1385 
1386         uint32_t isoPrimaries, isoTransfer, isoMatrix, isoRange;
1387         if (hvcc.findParam32(kColourPrimaries, &isoPrimaries)
1388                 && hvcc.findParam32(kTransferCharacteristics, &isoTransfer)
1389                 && hvcc.findParam32(kMatrixCoeffs, &isoMatrix)
1390                 && hvcc.findParam32(kVideoFullRangeFlag, &isoRange)) {
1391             ALOGV("found iso color aspects : primaris=%d, transfer=%d, matrix=%d, range=%d",
1392                     isoPrimaries, isoTransfer, isoMatrix, isoRange);
1393 
1394             ColorAspects aspects;
1395             ColorUtils::convertIsoColorAspectsToCodecAspects(
1396                     isoPrimaries, isoTransfer, isoMatrix, isoRange, aspects);
1397 
1398             if (aspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1399                 int32_t primaries;
1400                 if (meta->findInt32(kKeyColorPrimaries, &primaries)) {
1401                     ALOGV("unspecified primaries found, replaced to %d", primaries);
1402                     aspects.mPrimaries = static_cast<ColorAspects::Primaries>(primaries);
1403                 }
1404             }
1405             if (aspects.mTransfer == ColorAspects::TransferUnspecified) {
1406                 int32_t transferFunction;
1407                 if (meta->findInt32(kKeyTransferFunction, &transferFunction)) {
1408                     ALOGV("unspecified transfer found, replaced to %d", transferFunction);
1409                     aspects.mTransfer = static_cast<ColorAspects::Transfer>(transferFunction);
1410                 }
1411             }
1412             if (aspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1413                 int32_t colorMatrix;
1414                 if (meta->findInt32(kKeyColorMatrix, &colorMatrix)) {
1415                     ALOGV("unspecified matrix found, replaced to %d", colorMatrix);
1416                     aspects.mMatrixCoeffs = static_cast<ColorAspects::MatrixCoeffs>(colorMatrix);
1417                 }
1418             }
1419             if (aspects.mRange == ColorAspects::RangeUnspecified) {
1420                 int32_t range;
1421                 if (meta->findInt32(kKeyColorRange, &range)) {
1422                     ALOGV("unspecified range found, replaced to %d", range);
1423                     aspects.mRange = static_cast<ColorAspects::Range>(range);
1424                 }
1425             }
1426 
1427             int32_t standard, transfer, range;
1428             if (ColorUtils::convertCodecColorAspectsToPlatformAspects(
1429                     aspects, &range, &standard, &transfer) == OK) {
1430                 msg->setInt32("color-standard", standard);
1431                 msg->setInt32("color-transfer", transfer);
1432                 msg->setInt32("color-range", range);
1433             }
1434         }
1435 
1436         parseHevcProfileLevelFromHvcc((const uint8_t *)data, dataSize, msg);
1437     } else if (meta->findData(kKeyAV1C, &type, &data, &size)) {
1438         sp<ABuffer> buffer = new (std::nothrow) ABuffer(size);
1439         if (buffer.get() == NULL || buffer->base() == NULL) {
1440             return NO_MEMORY;
1441         }
1442         memcpy(buffer->data(), data, size);
1443 
1444         buffer->meta()->setInt32("csd", true);
1445         buffer->meta()->setInt64("timeUs", 0);
1446         msg->setBuffer("csd-0", buffer);
1447         parseAV1ProfileLevelFromCsd(buffer, msg);
1448     } else if (com::android::media::extractor::flags::extractor_mp4_enable_apv() &&
1449                meta->findData(kKeyAPVC, &type, &data, &size)) {
1450         sp<ABuffer> buffer = new (std::nothrow) ABuffer(size);
1451         if (buffer.get() == NULL || buffer->base() == NULL) {
1452             return NO_MEMORY;
1453         }
1454         memcpy(buffer->data(), data, size);
1455 
1456         buffer->meta()->setInt32("csd", true);
1457         buffer->meta()->setInt64("timeUs", 0);
1458         msg->setBuffer("csd-0", buffer);
1459     } else if (meta->findData(kKeyESDS, &type, &data, &size)) {
1460         ESDS esds((const char *)data, size);
1461         if (esds.InitCheck() != (status_t)OK) {
1462             return BAD_VALUE;
1463         }
1464 
1465         const void *codec_specific_data;
1466         size_t codec_specific_data_size;
1467         esds.getCodecSpecificInfo(
1468                 &codec_specific_data, &codec_specific_data_size);
1469 
1470         sp<ABuffer> buffer = new (std::nothrow) ABuffer(codec_specific_data_size);
1471         if (buffer.get() == NULL || buffer->base() == NULL) {
1472             return NO_MEMORY;
1473         }
1474 
1475         memcpy(buffer->data(), codec_specific_data,
1476                codec_specific_data_size);
1477 
1478         buffer->meta()->setInt32("csd", true);
1479         buffer->meta()->setInt64("timeUs", 0);
1480         msg->setBuffer("csd-0", buffer);
1481 
1482         if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG4)) {
1483             parseMpeg4ProfileLevelFromCsd(buffer, msg);
1484         } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG2)) {
1485             parseMpeg2ProfileLevelFromEsds(esds, msg);
1486             if (meta->findData(kKeyStreamHeader, &type, &data, &size)) {
1487                 parseMpeg2ProfileLevelFromHeader((uint8_t*)data, size, msg);
1488             }
1489         } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC)) {
1490             parseAacProfileFromCsd(buffer, msg);
1491         }
1492 
1493         uint32_t maxBitrate, avgBitrate;
1494         if (esds.getBitRate(&maxBitrate, &avgBitrate) == OK) {
1495             if (!meta->hasData(kKeyBitRate)
1496                     && avgBitrate > 0 && avgBitrate <= INT32_MAX) {
1497                 msg->setInt32("bitrate", (int32_t)avgBitrate);
1498             } else {
1499                 (void)msg->findInt32("bitrate", (int32_t*)&avgBitrate);
1500             }
1501             if (!meta->hasData(kKeyMaxBitRate)
1502                     && maxBitrate > 0 && maxBitrate <= INT32_MAX && maxBitrate >= avgBitrate) {
1503                 msg->setInt32("max-bitrate", (int32_t)maxBitrate);
1504             }
1505         }
1506     } else if (meta->findData(kKeyD263, &type, &data, &size)) {
1507         const uint8_t *ptr = (const uint8_t *)data;
1508         parseH263ProfileLevelFromD263(ptr, size, msg);
1509     } else if (meta->findData(kKeyOpusHeader, &type, &data, &size)) {
1510         sp<ABuffer> buffer = new (std::nothrow) ABuffer(size);
1511         if (buffer.get() == NULL || buffer->base() == NULL) {
1512             return NO_MEMORY;
1513         }
1514         memcpy(buffer->data(), data, size);
1515 
1516         buffer->meta()->setInt32("csd", true);
1517         buffer->meta()->setInt64("timeUs", 0);
1518         msg->setBuffer("csd-0", buffer);
1519 
1520         if (!meta->findData(kKeyOpusCodecDelay, &type, &data, &size)) {
1521             return -EINVAL;
1522         }
1523 
1524         buffer = new (std::nothrow) ABuffer(size);
1525         if (buffer.get() == NULL || buffer->base() == NULL) {
1526             return NO_MEMORY;
1527         }
1528         memcpy(buffer->data(), data, size);
1529 
1530         buffer->meta()->setInt32("csd", true);
1531         buffer->meta()->setInt64("timeUs", 0);
1532         msg->setBuffer("csd-1", buffer);
1533 
1534         if (!meta->findData(kKeyOpusSeekPreRoll, &type, &data, &size)) {
1535             return -EINVAL;
1536         }
1537 
1538         buffer = new (std::nothrow) ABuffer(size);
1539         if (buffer.get() == NULL || buffer->base() == NULL) {
1540             return NO_MEMORY;
1541         }
1542         memcpy(buffer->data(), data, size);
1543 
1544         buffer->meta()->setInt32("csd", true);
1545         buffer->meta()->setInt64("timeUs", 0);
1546         msg->setBuffer("csd-2", buffer);
1547     } else if (meta->findData(kKeyVp9CodecPrivate, &type, &data, &size)) {
1548         sp<ABuffer> buffer = new (std::nothrow) ABuffer(size);
1549         if (buffer.get() == NULL || buffer->base() == NULL) {
1550             return NO_MEMORY;
1551         }
1552         memcpy(buffer->data(), data, size);
1553 
1554         buffer->meta()->setInt32("csd", true);
1555         buffer->meta()->setInt64("timeUs", 0);
1556         msg->setBuffer("csd-0", buffer);
1557 
1558         parseVp9ProfileLevelFromCsd(buffer, msg);
1559     } else if (meta->findData(kKeyAlacMagicCookie, &type, &data, &size)) {
1560         ALOGV("convertMetaDataToMessage found kKeyAlacMagicCookie of size %zu\n", size);
1561         sp<ABuffer> buffer = new (std::nothrow) ABuffer(size);
1562         if (buffer.get() == NULL || buffer->base() == NULL) {
1563             return NO_MEMORY;
1564         }
1565         memcpy(buffer->data(), data, size);
1566 
1567         buffer->meta()->setInt32("csd", true);
1568         buffer->meta()->setInt64("timeUs", 0);
1569         msg->setBuffer("csd-0", buffer);
1570     }
1571 
1572     if (meta->findData(kKeyDVCC, &type, &data, &size)
1573             || meta->findData(kKeyDVVC, &type, &data, &size)
1574             || meta->findData(kKeyDVWC, &type, &data, &size)) {
1575         const uint8_t *ptr = (const uint8_t *)data;
1576         ALOGV("DV: calling parseDolbyVisionProfileLevelFromDvcc with data size %zu", size);
1577         parseDolbyVisionProfileLevelFromDvcc(ptr, size, msg);
1578         sp<ABuffer> buffer = new (std::nothrow) ABuffer(size);
1579         if (buffer.get() == nullptr || buffer->base() == nullptr) {
1580             return NO_MEMORY;
1581         }
1582         memcpy(buffer->data(), data, size);
1583 
1584         buffer->meta()->setInt32("csd", true);
1585         buffer->meta()->setInt64("timeUs", 0);
1586         msg->setBuffer("csd-2", buffer);
1587     }
1588 
1589     *format = msg;
1590 
1591     return OK;
1592 }
1593 
findNextNalStartCode(const uint8_t * data,size_t length)1594 const uint8_t *findNextNalStartCode(const uint8_t *data, size_t length) {
1595     uint8_t *res = NULL;
1596     if (length > 4) {
1597         // minus 1 as to not match NAL start code at end
1598         res = (uint8_t *)memmem(data, length - 1, "\x00\x00\x00\x01", 4);
1599     }
1600     return res != NULL && res < data + length - 4 ? res : &data[length];
1601 }
1602 
reassembleAVCC(const sp<ABuffer> & csd0,const sp<ABuffer> & csd1,char * avcc)1603 static size_t reassembleAVCC(const sp<ABuffer> &csd0, const sp<ABuffer> &csd1, char *avcc) {
1604     avcc[0] = 1;        // version
1605     avcc[1] = 0x64;     // profile (default to high)
1606     avcc[2] = 0;        // constraints (default to none)
1607     avcc[3] = 0xd;      // level (default to 1.3)
1608     avcc[4] = 0xff;     // reserved+size
1609 
1610     size_t i = 0;
1611     int numparams = 0;
1612     int lastparamoffset = 0;
1613     int avccidx = 6;
1614     do {
1615         i = findNextNalStartCode(csd0->data() + i, csd0->size() - i) - csd0->data();
1616         ALOGV("block at %zu, last was %d", i, lastparamoffset);
1617         if (lastparamoffset > 0) {
1618             const uint8_t *lastparam = csd0->data() + lastparamoffset;
1619             int size = i - lastparamoffset;
1620             if (size > 3) {
1621                 if (numparams && memcmp(avcc + 1, lastparam + 1, 3)) {
1622                     ALOGW("Inconsisted profile/level found in SPS: %x,%x,%x vs %x,%x,%x",
1623                             avcc[1], avcc[2], avcc[3], lastparam[1], lastparam[2], lastparam[3]);
1624                 } else if (!numparams) {
1625                     // fill in profile, constraints and level
1626                     memcpy(avcc + 1, lastparam + 1, 3);
1627                 }
1628             }
1629             avcc[avccidx++] = size >> 8;
1630             avcc[avccidx++] = size & 0xff;
1631             memcpy(avcc+avccidx, lastparam, size);
1632             avccidx += size;
1633             numparams++;
1634         }
1635         i += 4;
1636         lastparamoffset = i;
1637     } while(i < csd0->size());
1638     ALOGV("csd0 contains %d params", numparams);
1639 
1640     avcc[5] = 0xe0 | numparams;
1641     //and now csd-1
1642     i = 0;
1643     numparams = 0;
1644     lastparamoffset = 0;
1645     int numpicparamsoffset = avccidx;
1646     avccidx++;
1647     do {
1648         i = findNextNalStartCode(csd1->data() + i, csd1->size() - i) - csd1->data();
1649         ALOGV("block at %zu, last was %d", i, lastparamoffset);
1650         if (lastparamoffset > 0) {
1651             int size = i - lastparamoffset;
1652             avcc[avccidx++] = size >> 8;
1653             avcc[avccidx++] = size & 0xff;
1654             memcpy(avcc+avccidx, csd1->data() + lastparamoffset, size);
1655             avccidx += size;
1656             numparams++;
1657         }
1658         i += 4;
1659         lastparamoffset = i;
1660     } while(i < csd1->size());
1661     avcc[numpicparamsoffset] = numparams;
1662     return avccidx;
1663 }
1664 
reassembleESDS(const sp<ABuffer> & csd0,char * esds)1665 static void reassembleESDS(const sp<ABuffer> &csd0, char *esds) {
1666     int csd0size = csd0->size();
1667     esds[0] = 3; // kTag_ESDescriptor;
1668     int esdescriptorsize = 26 + csd0size;
1669     CHECK(esdescriptorsize < 268435456); // 7 bits per byte, so max is 2^28-1
1670     esds[1] = 0x80 | (esdescriptorsize >> 21);
1671     esds[2] = 0x80 | ((esdescriptorsize >> 14) & 0x7f);
1672     esds[3] = 0x80 | ((esdescriptorsize >> 7) & 0x7f);
1673     esds[4] = (esdescriptorsize & 0x7f);
1674     esds[5] = esds[6] = 0; // es id
1675     esds[7] = 0; // flags
1676     esds[8] = 4; // kTag_DecoderConfigDescriptor
1677     int configdescriptorsize = 18 + csd0size;
1678     esds[9] = 0x80 | (configdescriptorsize >> 21);
1679     esds[10] = 0x80 | ((configdescriptorsize >> 14) & 0x7f);
1680     esds[11] = 0x80 | ((configdescriptorsize >> 7) & 0x7f);
1681     esds[12] = (configdescriptorsize & 0x7f);
1682     esds[13] = 0x40; // objectTypeIndication
1683     // bytes 14-25 are examples from a real file. they are unused/overwritten by muxers.
1684     esds[14] = 0x15; // streamType(5), upStream(0),
1685     esds[15] = 0x00; // 15-17: bufferSizeDB (6KB)
1686     esds[16] = 0x18;
1687     esds[17] = 0x00;
1688     esds[18] = 0x00; // 18-21: maxBitrate (64kbps)
1689     esds[19] = 0x00;
1690     esds[20] = 0xfa;
1691     esds[21] = 0x00;
1692     esds[22] = 0x00; // 22-25: avgBitrate (64kbps)
1693     esds[23] = 0x00;
1694     esds[24] = 0xfa;
1695     esds[25] = 0x00;
1696     esds[26] = 5; // kTag_DecoderSpecificInfo;
1697     esds[27] = 0x80 | (csd0size >> 21);
1698     esds[28] = 0x80 | ((csd0size >> 14) & 0x7f);
1699     esds[29] = 0x80 | ((csd0size >> 7) & 0x7f);
1700     esds[30] = (csd0size & 0x7f);
1701     memcpy((void*)&esds[31], csd0->data(), csd0size);
1702     // data following this is ignored, so don't bother appending it
1703 }
1704 
reassembleHVCC(const sp<ABuffer> & csd0,uint8_t * hvcc,size_t hvccSize,size_t nalSizeLength)1705 static size_t reassembleHVCC(const sp<ABuffer> &csd0, uint8_t *hvcc, size_t hvccSize, size_t nalSizeLength) {
1706     HevcParameterSets paramSets;
1707     uint8_t* data = csd0->data();
1708     if (csd0->size() < 4) {
1709         ALOGE("csd0 too small");
1710         return 0;
1711     }
1712     if (memcmp(data, "\x00\x00\x00\x01", 4) != 0) {
1713         ALOGE("csd0 doesn't start with a start code");
1714         return 0;
1715     }
1716     size_t prevNalOffset = 4;
1717     status_t err = OK;
1718     for (size_t i = 1; i < csd0->size() - 4; ++i) {
1719         if (memcmp(&data[i], "\x00\x00\x00\x01", 4) != 0) {
1720             continue;
1721         }
1722         err = paramSets.addNalUnit(&data[prevNalOffset], i - prevNalOffset);
1723         if (err != OK) {
1724             return 0;
1725         }
1726         prevNalOffset = i + 4;
1727     }
1728     err = paramSets.addNalUnit(&data[prevNalOffset], csd0->size() - prevNalOffset);
1729     if (err != OK) {
1730         return 0;
1731     }
1732     size_t size = hvccSize;
1733     err = paramSets.makeHvcc(hvcc, &size, nalSizeLength);
1734     if (err != OK) {
1735         return 0;
1736     }
1737     return size;
1738 }
1739 
1740 #if 0
1741 static void convertMessageToMetaDataInt32(
1742         const sp<AMessage> &msg, sp<MetaData> &meta, uint32_t key, const char *name) {
1743     int32_t value;
1744     if (msg->findInt32(name, &value)) {
1745         meta->setInt32(key, value);
1746     }
1747 }
1748 #endif
1749 
convertMessageToMetaDataColorAspects(const sp<AMessage> & msg,sp<MetaData> & meta)1750 static void convertMessageToMetaDataColorAspects(const sp<AMessage> &msg, sp<MetaData> &meta) {
1751     // 0 values are unspecified
1752     int32_t range = 0, standard = 0, transfer = 0;
1753     (void)msg->findInt32("color-range", &range);
1754     (void)msg->findInt32("color-standard", &standard);
1755     (void)msg->findInt32("color-transfer", &transfer);
1756 
1757     ColorAspects colorAspects;
1758     memset(&colorAspects, 0, sizeof(colorAspects));
1759     if (CodecBase::convertPlatformColorAspectsToCodecAspects(
1760             range, standard, transfer, colorAspects) != OK) {
1761         return;
1762     }
1763 
1764     // save specified values to meta
1765     if (colorAspects.mRange != 0) {
1766         meta->setInt32(kKeyColorRange, colorAspects.mRange);
1767     }
1768     if (colorAspects.mPrimaries != 0) {
1769         meta->setInt32(kKeyColorPrimaries, colorAspects.mPrimaries);
1770     }
1771     if (colorAspects.mTransfer != 0) {
1772         meta->setInt32(kKeyTransferFunction, colorAspects.mTransfer);
1773     }
1774     if (colorAspects.mMatrixCoeffs != 0) {
1775         meta->setInt32(kKeyColorMatrix, colorAspects.mMatrixCoeffs);
1776     }
1777 }
1778 /* Converts key and value pairs in AMessage format to MetaData format.
1779  * Also checks for the presence of required keys.
1780  */
convertMessageToMetaData(const sp<AMessage> & msg,sp<MetaData> & meta)1781 status_t convertMessageToMetaData(const sp<AMessage> &msg, sp<MetaData> &meta) {
1782     AString mime;
1783     if (msg->findString("mime", &mime)) {
1784         meta->setCString(kKeyMIMEType, mime.c_str());
1785     } else {
1786         ALOGV("did not find mime type");
1787         return BAD_VALUE;
1788     }
1789 
1790     convertMessageToMetaDataFromMappings(msg, meta);
1791 
1792     int32_t systemId;
1793     if (msg->findInt32("ca-system-id", &systemId)) {
1794         meta->setInt32(kKeyCASystemID, systemId);
1795 
1796         sp<ABuffer> caSessionId, caPvtData;
1797         if (msg->findBuffer("ca-session-id", &caSessionId)) {
1798             meta->setData(kKeyCASessionID, 0, caSessionId->data(), caSessionId->size());
1799         }
1800         if (msg->findBuffer("ca-private-data", &caPvtData)) {
1801             meta->setData(kKeyCAPrivateData, 0, caPvtData->data(), caPvtData->size());
1802         }
1803     }
1804 
1805     int64_t durationUs;
1806     if (msg->findInt64("durationUs", &durationUs)) {
1807         meta->setInt64(kKeyDuration, durationUs);
1808     }
1809 
1810     int32_t isSync;
1811     if (msg->findInt32("is-sync-frame", &isSync) && isSync != 0) {
1812         meta->setInt32(kKeyIsSyncFrame, 1);
1813     }
1814 
1815     // Mode for media transcoding.
1816     int32_t isBackgroundMode;
1817     if (msg->findInt32("android._background-mode", &isBackgroundMode) && isBackgroundMode != 0) {
1818         meta->setInt32(isBackgroundMode, 1);
1819     }
1820 
1821     int32_t avgBitrate = 0;
1822     int32_t maxBitrate;
1823     if (msg->findInt32("bitrate", &avgBitrate) && avgBitrate > 0) {
1824         meta->setInt32(kKeyBitRate, avgBitrate);
1825     }
1826     if (msg->findInt32("max-bitrate", &maxBitrate) && maxBitrate > 0 && maxBitrate >= avgBitrate) {
1827         meta->setInt32(kKeyMaxBitRate, maxBitrate);
1828     }
1829 
1830     int32_t dvbComponentTag = 0;
1831     if (msg->findInt32("dvb-component-tag", &dvbComponentTag) && dvbComponentTag > 0) {
1832         meta->setInt32(kKeyDvbComponentTag, dvbComponentTag);
1833     }
1834 
1835     int32_t dvbAudioDescription = 0;
1836     if (msg->findInt32("dvb-audio-description", &dvbAudioDescription)) {
1837         meta->setInt32(kKeyDvbAudioDescription, dvbAudioDescription);
1838     }
1839 
1840     int32_t dvbTeletextMagazineNumber = 0;
1841     if (msg->findInt32("dvb-teletext-magazine-number", &dvbTeletextMagazineNumber)) {
1842         meta->setInt32(kKeyDvbTeletextMagazineNumber, dvbTeletextMagazineNumber);
1843     }
1844 
1845     int32_t dvbTeletextPageNumber = 0;
1846     if (msg->findInt32("dvb-teletext-page-number", &dvbTeletextPageNumber)) {
1847         meta->setInt32(kKeyDvbTeletextPageNumber, dvbTeletextPageNumber);
1848     }
1849 
1850     AString lang;
1851     if (msg->findString("language", &lang)) {
1852         meta->setCString(kKeyMediaLanguage, lang.c_str());
1853     }
1854 
1855     if (mime.startsWith("video/") || mime.startsWith("image/")) {
1856         int32_t width;
1857         int32_t height;
1858         if (!msg->findInt32("width", &width) || !msg->findInt32("height", &height)) {
1859             ALOGV("did not find width and/or height");
1860             return BAD_VALUE;
1861         }
1862         if (width <= 0 || height <= 0) {
1863             ALOGE("Invalid value of width: %d and/or height: %d", width, height);
1864             return BAD_VALUE;
1865         }
1866         meta->setInt32(kKeyWidth, width);
1867         meta->setInt32(kKeyHeight, height);
1868 
1869         int32_t sarWidth = -1, sarHeight = -1;
1870         bool foundWidth, foundHeight;
1871         foundWidth = msg->findInt32("sar-width", &sarWidth);
1872         foundHeight = msg->findInt32("sar-height", &sarHeight);
1873         if (foundWidth || foundHeight) {
1874             if (sarWidth <= 0 || sarHeight <= 0) {
1875                 ALOGE("Invalid value of sarWidth: %d and/or sarHeight: %d", sarWidth, sarHeight);
1876                 return BAD_VALUE;
1877             }
1878             meta->setInt32(kKeySARWidth, sarWidth);
1879             meta->setInt32(kKeySARHeight, sarHeight);
1880         }
1881 
1882         int32_t displayWidth = -1, displayHeight = -1;
1883         foundWidth = msg->findInt32("display-width", &displayWidth);
1884         foundHeight = msg->findInt32("display-height", &displayHeight);
1885         if (foundWidth || foundHeight) {
1886             if (displayWidth <= 0 || displayHeight <= 0) {
1887                 ALOGE("Invalid value of displayWidth: %d and/or displayHeight: %d",
1888                         displayWidth, displayHeight);
1889                 return BAD_VALUE;
1890             }
1891             meta->setInt32(kKeyDisplayWidth, displayWidth);
1892             meta->setInt32(kKeyDisplayHeight, displayHeight);
1893         }
1894 
1895         if (mime.startsWith("image/")){
1896             int32_t isPrimary;
1897             if (msg->findInt32("is-default", &isPrimary) && isPrimary) {
1898                 meta->setInt32(kKeyTrackIsDefault, 1);
1899             }
1900             int32_t tileWidth = -1, tileHeight = -1;
1901             foundWidth = msg->findInt32("tile-width", &tileWidth);
1902             foundHeight = msg->findInt32("tile-height", &tileHeight);
1903             if (foundWidth || foundHeight) {
1904                 if (tileWidth <= 0 || tileHeight <= 0) {
1905                     ALOGE("Invalid value of tileWidth: %d and/or tileHeight: %d",
1906                             tileWidth, tileHeight);
1907                     return BAD_VALUE;
1908                 }
1909                 meta->setInt32(kKeyTileWidth, tileWidth);
1910                 meta->setInt32(kKeyTileHeight, tileHeight);
1911             }
1912             int32_t gridRows = -1, gridCols = -1;
1913             bool foundRows, foundCols;
1914             foundRows = msg->findInt32("grid-rows", &gridRows);
1915             foundCols = msg->findInt32("grid-cols", &gridCols);
1916             if (foundRows || foundCols) {
1917                 if (gridRows <= 0 || gridCols <= 0) {
1918                     ALOGE("Invalid value of gridRows: %d and/or gridCols: %d",
1919                             gridRows, gridCols);
1920                     return BAD_VALUE;
1921                 }
1922                 meta->setInt32(kKeyGridRows, gridRows);
1923                 meta->setInt32(kKeyGridCols, gridCols);
1924             }
1925         }
1926 
1927         int32_t colorFormat;
1928         if (msg->findInt32("color-format", &colorFormat)) {
1929             meta->setInt32(kKeyColorFormat, colorFormat);
1930         }
1931 
1932         int32_t cropLeft, cropTop, cropRight, cropBottom;
1933         if (msg->findRect("crop",
1934                           &cropLeft,
1935                           &cropTop,
1936                           &cropRight,
1937                           &cropBottom)) {
1938             if (cropLeft < 0 || cropLeft > cropRight || cropRight >= width) {
1939                 ALOGE("Invalid value of cropLeft: %d and/or cropRight: %d", cropLeft, cropRight);
1940                 return BAD_VALUE;
1941             }
1942             if (cropTop < 0 || cropTop > cropBottom || cropBottom >= height) {
1943                 ALOGE("Invalid value of cropTop: %d and/or cropBottom: %d", cropTop, cropBottom);
1944                 return BAD_VALUE;
1945             }
1946             meta->setRect(kKeyCropRect, cropLeft, cropTop, cropRight, cropBottom);
1947         }
1948 
1949         int32_t rotationDegrees;
1950         if (msg->findInt32("rotation-degrees", &rotationDegrees)) {
1951             meta->setInt32(kKeyRotation, rotationDegrees);
1952         }
1953 
1954         if (msg->contains("hdr-static-info")) {
1955             HDRStaticInfo info;
1956             if (ColorUtils::getHDRStaticInfoFromFormat(msg, &info)) {
1957                 meta->setData(kKeyHdrStaticInfo, 'hdrS', &info, sizeof(info));
1958             }
1959         }
1960 
1961         sp<ABuffer> hdr10PlusInfo;
1962         if (msg->findBuffer("hdr10-plus-info", &hdr10PlusInfo)) {
1963             meta->setData(kKeyHdr10PlusInfo, 0,
1964                     hdr10PlusInfo->data(), hdr10PlusInfo->size());
1965         }
1966 
1967         convertMessageToMetaDataColorAspects(msg, meta);
1968 
1969         AString tsSchema;
1970         if (msg->findString("ts-schema", &tsSchema)) {
1971             unsigned int numLayers = 0;
1972             unsigned int numBLayers = 0;
1973             char placeholder;
1974             int tags = sscanf(tsSchema.c_str(), "android.generic.%u%c%u%c",
1975                     &numLayers, &placeholder, &numBLayers, &placeholder);
1976             if ((tags == 1 || (tags == 3 && placeholder == '+'))
1977                     && numLayers > 0 && numLayers < UINT32_MAX - numBLayers
1978                     && numLayers + numBLayers <= INT32_MAX) {
1979                 meta->setInt32(kKeyTemporalLayerCount, numLayers + numBLayers);
1980             }
1981         }
1982     } else if (mime.startsWith("audio/")) {
1983         int32_t numChannels, sampleRate;
1984         if (!msg->findInt32("channel-count", &numChannels) ||
1985                 !msg->findInt32("sample-rate", &sampleRate)) {
1986             ALOGV("did not find channel-count and/or sample-rate");
1987             return BAD_VALUE;
1988         }
1989         // channel count can be zero in some cases like mpeg h
1990         if (sampleRate <= 0 || numChannels < 0) {
1991             ALOGE("Invalid value of channel-count: %d and/or sample-rate: %d",
1992                    numChannels, sampleRate);
1993             return BAD_VALUE;
1994         }
1995         meta->setInt32(kKeyChannelCount, numChannels);
1996         meta->setInt32(kKeySampleRate, sampleRate);
1997         int32_t bitsPerSample;
1998         // TODO:(b/204430952) add appropriate bound check for bitsPerSample
1999         if (msg->findInt32("bits-per-sample", &bitsPerSample)) {
2000             meta->setInt32(kKeyBitsPerSample, bitsPerSample);
2001         }
2002         int32_t channelMask;
2003         if (msg->findInt32("channel-mask", &channelMask)) {
2004             meta->setInt32(kKeyChannelMask, channelMask);
2005         }
2006         int32_t delay = 0;
2007         if (msg->findInt32("encoder-delay", &delay)) {
2008             meta->setInt32(kKeyEncoderDelay, delay);
2009         }
2010         int32_t padding = 0;
2011         if (msg->findInt32("encoder-padding", &padding)) {
2012             meta->setInt32(kKeyEncoderPadding, padding);
2013         }
2014 
2015         int32_t isADTS;
2016         if (msg->findInt32("is-adts", &isADTS)) {
2017             meta->setInt32(kKeyIsADTS, isADTS);
2018         }
2019 
2020         int32_t mpeghProfileLevelIndication = -1;
2021         if (msg->findInt32(AMEDIAFORMAT_KEY_MPEGH_PROFILE_LEVEL_INDICATION,
2022                 &mpeghProfileLevelIndication)) {
2023             meta->setInt32(kKeyMpeghProfileLevelIndication, mpeghProfileLevelIndication);
2024         }
2025         int32_t mpeghReferenceChannelLayout = -1;
2026         if (msg->findInt32(AMEDIAFORMAT_KEY_MPEGH_REFERENCE_CHANNEL_LAYOUT,
2027                 &mpeghReferenceChannelLayout)) {
2028             meta->setInt32(kKeyMpeghReferenceChannelLayout, mpeghReferenceChannelLayout);
2029         }
2030         sp<ABuffer> mpeghCompatibleSets;
2031         if (msg->findBuffer(AMEDIAFORMAT_KEY_MPEGH_COMPATIBLE_SETS,
2032                 &mpeghCompatibleSets)) {
2033             meta->setData(kKeyMpeghCompatibleSets, kTypeHCOS,
2034                     mpeghCompatibleSets->data(), mpeghCompatibleSets->size());
2035         }
2036 
2037         int32_t aacProfile = -1;
2038         if (msg->findInt32("aac-profile", &aacProfile)) {
2039             meta->setInt32(kKeyAACAOT, aacProfile);
2040         }
2041 
2042         int32_t pcmEncoding;
2043         if (msg->findInt32("pcm-encoding", &pcmEncoding)) {
2044             meta->setInt32(kKeyPcmEncoding, pcmEncoding);
2045         }
2046 
2047         int32_t hapticChannelCount;
2048         if (msg->findInt32("haptic-channel-count", &hapticChannelCount)) {
2049             meta->setInt32(kKeyHapticChannelCount, hapticChannelCount);
2050         }
2051     }
2052 
2053     int32_t maxInputSize;
2054     if (msg->findInt32("max-input-size", &maxInputSize)) {
2055         meta->setInt32(kKeyMaxInputSize, maxInputSize);
2056     }
2057 
2058     int32_t maxWidth;
2059     if (msg->findInt32("max-width", &maxWidth)) {
2060         meta->setInt32(kKeyMaxWidth, maxWidth);
2061     }
2062 
2063     int32_t maxHeight;
2064     if (msg->findInt32("max-height", &maxHeight)) {
2065         meta->setInt32(kKeyMaxHeight, maxHeight);
2066     }
2067 
2068     int32_t gainmap;
2069     if (msg->findInt32("gainmap", &gainmap)) {
2070         meta->setInt32(kKeyGainmap, gainmap);
2071     }
2072 
2073     int32_t fps;
2074     float fpsFloat;
2075     if (msg->findInt32("frame-rate", &fps) && fps > 0) {
2076         meta->setInt32(kKeyFrameRate, fps);
2077     } else if (msg->findFloat("frame-rate", &fpsFloat)
2078             && fpsFloat >= 1 && fpsFloat <= (float)INT32_MAX) {
2079         // truncate values to distinguish between e.g. 24 vs 23.976 fps
2080         meta->setInt32(kKeyFrameRate, (int32_t)fpsFloat);
2081     }
2082 
2083     // reassemble the csd data into its original form
2084     sp<ABuffer> csd0, csd1, csd2;
2085     if (msg->findBuffer("csd-0", &csd0)) {
2086         int csd0size = csd0->size();
2087         if (mime == MEDIA_MIMETYPE_VIDEO_AVC) {
2088             sp<ABuffer> csd1;
2089             if (msg->findBuffer("csd-1", &csd1)) {
2090                 std::vector<char> avcc(csd0size + csd1->size() + 1024);
2091                 size_t outsize = reassembleAVCC(csd0, csd1, avcc.data());
2092                 meta->setData(kKeyAVCC, kTypeAVCC, avcc.data(), outsize);
2093             }
2094         } else if (mime == MEDIA_MIMETYPE_AUDIO_AAC ||
2095                 mime == MEDIA_MIMETYPE_VIDEO_MPEG4 ||
2096                 mime == MEDIA_MIMETYPE_AUDIO_WMA ||
2097                 mime == MEDIA_MIMETYPE_AUDIO_MS_ADPCM ||
2098                 mime == MEDIA_MIMETYPE_AUDIO_DVI_IMA_ADPCM) {
2099             std::vector<char> esds(csd0size + 31);
2100             // The written ESDS is actually for an audio stream, but it's enough
2101             // for transporting the CSD to muxers.
2102             reassembleESDS(csd0, esds.data());
2103             meta->setData(kKeyESDS, kTypeESDS, esds.data(), esds.size());
2104         } else if (mime == MEDIA_MIMETYPE_VIDEO_HEVC ||
2105                    mime == MEDIA_MIMETYPE_IMAGE_ANDROID_HEIC) {
2106             std::vector<uint8_t> hvcc(csd0size + 1024);
2107             size_t outsize = reassembleHVCC(csd0, hvcc.data(), hvcc.size(), 4);
2108             meta->setData(kKeyHVCC, kTypeHVCC, hvcc.data(), outsize);
2109         } else if (mime == MEDIA_MIMETYPE_VIDEO_AV1 ||
2110                    mime == MEDIA_MIMETYPE_IMAGE_AVIF) {
2111             meta->setData(kKeyAV1C, 0, csd0->data(), csd0->size());
2112         } else if (com::android::media::extractor::flags::extractor_mp4_enable_apv() &&
2113                    mime == MEDIA_MIMETYPE_VIDEO_APV) {
2114             meta->setData(kKeyAPVC, 0, csd0->data(), csd0->size());
2115         } else if (mime == MEDIA_MIMETYPE_VIDEO_DOLBY_VISION) {
2116             int32_t profile = -1;
2117             uint8_t blCompatibilityId = -1;
2118             int32_t level = 0;
2119             uint8_t profileVal = -1;
2120             uint8_t profileVal1 = -1;
2121             uint8_t profileVal2 = -1;
2122             constexpr size_t dvccSize = 24;
2123 
2124             const ALookup<uint8_t, int32_t> &profiles =
2125                 getDolbyVisionProfileTable();
2126             const ALookup<uint8_t, int32_t> &levels =
2127                 getDolbyVisionLevelsTable();
2128 
2129             if (!msg->findBuffer("csd-2", &csd2)) {
2130                 // MP4 extractors are expected to generate csd buffer
2131                 // some encoders might not be generating it, in which
2132                 // case we populate the track metadata dv (cc|vc|wc)
2133                 // from the 'profile' and 'level' info.
2134                 // This is done according to Dolby Vision ISOBMFF spec
2135 
2136                 if (!msg->findInt32("profile", &profile)) {
2137                     ALOGE("Dolby Vision profile not found");
2138                     return BAD_VALUE;
2139                 }
2140                 msg->findInt32("level", &level);
2141 
2142                 if (profile == DolbyVisionProfileDvheSt) {
2143                     if (!profiles.rlookup(DolbyVisionProfileDvheSt, &profileVal)) { // dvhe.08
2144                         ALOGE("Dolby Vision profile lookup error");
2145                         return BAD_VALUE;
2146                     }
2147                     blCompatibilityId = 4;
2148                 } else if (profile == DolbyVisionProfileDvavSe) {
2149                     if (!profiles.rlookup(DolbyVisionProfileDvavSe, &profileVal)) { // dvav.09
2150                         ALOGE("Dolby Vision profile lookup error");
2151                         return BAD_VALUE;
2152                     }
2153                     blCompatibilityId = 2;
2154                 } else {
2155                     ALOGE("Dolby Vision profile look up error");
2156                     return BAD_VALUE;
2157                 }
2158 
2159                 profile = (int32_t) profileVal;
2160 
2161                 uint8_t level_val = 0;
2162                 if (!levels.map(level, &level_val)) {
2163                     ALOGE("Dolby Vision level lookup error");
2164                     return BAD_VALUE;
2165                 }
2166 
2167                 std::vector<uint8_t> dvcc(dvccSize);
2168 
2169                 dvcc[0] = 1; // major version
2170                 dvcc[1] = 0; // minor version
2171                 dvcc[2] = (uint8_t)((profile & 0x7f) << 1); // dolby vision profile
2172                 dvcc[2] = (uint8_t)((dvcc[2] | (uint8_t)((level_val >> 5) & 0x1)) & 0xff);
2173                 dvcc[3] = (uint8_t)((level_val & 0x1f) << 3); // dolby vision level
2174                 dvcc[3] = (uint8_t)(dvcc[3] | (1 << 2)); // rpu_present_flag
2175                 dvcc[3] = (uint8_t)(dvcc[3] | (1)); // bl_present_flag
2176                 dvcc[4] = (uint8_t)(blCompatibilityId << 4); // bl_compatibility id
2177 
2178                 profiles.rlookup(DolbyVisionProfileDvav110, &profileVal);
2179                 profiles.rlookup(DolbyVisionProfileDvheDtb, &profileVal1);
2180                 if (profile > (int32_t) profileVal) {
2181                     meta->setData(kKeyDVWC, kTypeDVWC, dvcc.data(), dvccSize);
2182                 } else if (profile > (int32_t) profileVal1) {
2183                     meta->setData(kKeyDVVC, kTypeDVVC, dvcc.data(), dvccSize);
2184                 } else {
2185                     meta->setData(kKeyDVCC, kTypeDVCC, dvcc.data(), dvccSize);
2186                 }
2187 
2188             } else {
2189                 // we have csd-2, just use that to populate dvcc
2190                 if (csd2->size() == dvccSize) {
2191                     uint8_t *dvcc = csd2->data();
2192                     profile = dvcc[2] >> 1;
2193 
2194                     profiles.rlookup(DolbyVisionProfileDvav110, &profileVal);
2195                     profiles.rlookup(DolbyVisionProfileDvheDtb, &profileVal1);
2196                     if (profile > (int32_t) profileVal) {
2197                         meta->setData(kKeyDVWC, kTypeDVWC, csd2->data(), csd2->size());
2198                     } else if (profile > (int32_t) profileVal1) {
2199                         meta->setData(kKeyDVVC, kTypeDVVC, csd2->data(), csd2->size());
2200                     } else {
2201                          meta->setData(kKeyDVCC, kTypeDVCC, csd2->data(), csd2->size());
2202                     }
2203 
2204                 } else {
2205                     ALOGE("Convert MessageToMetadata csd-2 is present but not valid");
2206                     return BAD_VALUE;
2207                 }
2208             }
2209             profiles.rlookup(DolbyVisionProfileDvavPen, &profileVal);
2210             profiles.rlookup(DolbyVisionProfileDvavSe, &profileVal1);
2211             profiles.rlookup(DolbyVisionProfileDvav110, &profileVal2);
2212             if ((profile > (int32_t) profileVal) && (profile < (int32_t) profileVal1)) {
2213                 std::vector<uint8_t> hvcc(csd0size + 1024);
2214                 size_t outsize = reassembleHVCC(csd0, hvcc.data(), hvcc.size(), 4);
2215                 meta->setData(kKeyHVCC, kTypeHVCC, hvcc.data(), outsize);
2216             } else if (profile == (int32_t) profileVal2) {
2217                 meta->setData(kKeyAV1C, 0, csd0->data(), csd0->size());
2218             } else {
2219                 sp<ABuffer> csd1;
2220                 if (msg->findBuffer("csd-1", &csd1)) {
2221                     std::vector<char> avcc(csd0size + csd1->size() + 1024);
2222                     size_t outsize = reassembleAVCC(csd0, csd1, avcc.data());
2223                     meta->setData(kKeyAVCC, kTypeAVCC, avcc.data(), outsize);
2224                 }
2225                 else {
2226                     // for dolby vision avc, csd0 also holds csd1
2227                     size_t i = 0;
2228                     int csd0realsize = 0;
2229                     do {
2230                         i = findNextNalStartCode(csd0->data() + i,
2231                                         csd0->size() - i) - csd0->data();
2232                         if (i > 0) {
2233                             csd0realsize = i;
2234                             break;
2235                         }
2236                         i += 4;
2237                     } while(i < csd0->size());
2238                     // buffer0 -> csd0
2239                     sp<ABuffer> buffer0 = new (std::nothrow) ABuffer(csd0realsize);
2240                     if (buffer0.get() == NULL || buffer0->base() == NULL) {
2241                         return NO_MEMORY;
2242                     }
2243                     memcpy(buffer0->data(), csd0->data(), csd0realsize);
2244                     // buffer1 -> csd1
2245                     sp<ABuffer> buffer1 = new (std::nothrow)
2246                             ABuffer(csd0->size() - csd0realsize);
2247                     if (buffer1.get() == NULL || buffer1->base() == NULL) {
2248                         return NO_MEMORY;
2249                     }
2250                     memcpy(buffer1->data(), csd0->data()+csd0realsize,
2251                                 csd0->size() - csd0realsize);
2252 
2253                     std::vector<char> avcc(csd0->size() + 1024);
2254                     size_t outsize = reassembleAVCC(buffer0, buffer1, avcc.data());
2255                     meta->setData(kKeyAVCC, kTypeAVCC, avcc.data(), outsize);
2256                 }
2257             }
2258         } else if (mime == MEDIA_MIMETYPE_VIDEO_VP9) {
2259             meta->setData(kKeyVp9CodecPrivate, 0, csd0->data(), csd0->size());
2260         } else if (mime == MEDIA_MIMETYPE_AUDIO_OPUS) {
2261             size_t opusHeadSize = csd0->size();
2262             size_t codecDelayBufSize = 0;
2263             size_t seekPreRollBufSize = 0;
2264             void *opusHeadBuf = csd0->data();
2265             void *codecDelayBuf = NULL;
2266             void *seekPreRollBuf = NULL;
2267             if (msg->findBuffer("csd-1", &csd1)) {
2268                 codecDelayBufSize = csd1->size();
2269                 codecDelayBuf = csd1->data();
2270             }
2271             if (msg->findBuffer("csd-2", &csd2)) {
2272                 seekPreRollBufSize = csd2->size();
2273                 seekPreRollBuf = csd2->data();
2274             }
2275             /* Extract codec delay and seek pre roll from csd-0,
2276              * if csd-1 and csd-2 are not present */
2277             if (!codecDelayBuf && !seekPreRollBuf) {
2278                 GetOpusHeaderBuffers(csd0->data(), csd0->size(), &opusHeadBuf,
2279                                     &opusHeadSize, &codecDelayBuf,
2280                                     &codecDelayBufSize, &seekPreRollBuf,
2281                                     &seekPreRollBufSize);
2282             }
2283             meta->setData(kKeyOpusHeader, 0, opusHeadBuf, opusHeadSize);
2284             if (codecDelayBuf) {
2285                 meta->setData(kKeyOpusCodecDelay, 0, codecDelayBuf, codecDelayBufSize);
2286             }
2287             if (seekPreRollBuf) {
2288                 meta->setData(kKeyOpusSeekPreRoll, 0, seekPreRollBuf, seekPreRollBufSize);
2289             }
2290         } else if (mime == MEDIA_MIMETYPE_AUDIO_ALAC) {
2291             meta->setData(kKeyAlacMagicCookie, 0, csd0->data(), csd0->size());
2292         }
2293     } else if (mime == MEDIA_MIMETYPE_VIDEO_AVC && msg->findBuffer("csd-avc", &csd0)) {
2294         meta->setData(kKeyAVCC, kTypeAVCC, csd0->data(), csd0->size());
2295     } else if ((mime == MEDIA_MIMETYPE_VIDEO_HEVC || mime == MEDIA_MIMETYPE_IMAGE_ANDROID_HEIC)
2296             && msg->findBuffer("csd-hevc", &csd0)) {
2297         meta->setData(kKeyHVCC, kTypeHVCC, csd0->data(), csd0->size());
2298     } else if (msg->findBuffer("esds", &csd0)) {
2299         meta->setData(kKeyESDS, kTypeESDS, csd0->data(), csd0->size());
2300     } else if (msg->findBuffer("mpeg2-stream-header", &csd0)) {
2301         meta->setData(kKeyStreamHeader, 'mdat', csd0->data(), csd0->size());
2302     } else if (msg->findBuffer("d263", &csd0)) {
2303         meta->setData(kKeyD263, kTypeD263, csd0->data(), csd0->size());
2304     } else if (mime == MEDIA_MIMETYPE_VIDEO_DOLBY_VISION && msg->findBuffer("csd-2", &csd2)) {
2305         meta->setData(kKeyDVCC, kTypeDVCC, csd2->data(), csd2->size());
2306 
2307         // Remove CSD-2 from the data here to avoid duplicate data in meta
2308         meta->remove(kKeyOpaqueCSD2);
2309 
2310         if (msg->findBuffer("csd-avc", &csd0)) {
2311             meta->setData(kKeyAVCC, kTypeAVCC, csd0->data(), csd0->size());
2312         } else if (msg->findBuffer("csd-hevc", &csd0)) {
2313             meta->setData(kKeyHVCC, kTypeHVCC, csd0->data(), csd0->size());
2314         }
2315     }
2316     // XXX TODO add whatever other keys there are
2317 
2318 #if 0
2319     ALOGI("converted %s to:", msg->debugString(0).c_str());
2320     meta->dumpToLog();
2321 #endif
2322     return OK;
2323 }
2324 
sendMetaDataToHal(sp<MediaPlayerBase::AudioSink> & sink,const sp<MetaData> & meta)2325 status_t sendMetaDataToHal(sp<MediaPlayerBase::AudioSink>& sink,
2326                            const sp<MetaData>& meta)
2327 {
2328     int32_t sampleRate = 0;
2329     int32_t bitRate = 0;
2330     int32_t channelMask = 0;
2331     int32_t delaySamples = 0;
2332     int32_t paddingSamples = 0;
2333 
2334     AudioParameter param = AudioParameter();
2335 
2336     if (meta->findInt32(kKeySampleRate, &sampleRate)) {
2337         param.addInt(String8(AUDIO_OFFLOAD_CODEC_SAMPLE_RATE), sampleRate);
2338     }
2339     if (meta->findInt32(kKeyChannelMask, &channelMask)) {
2340         param.addInt(String8(AUDIO_OFFLOAD_CODEC_NUM_CHANNEL), channelMask);
2341     }
2342     if (meta->findInt32(kKeyBitRate, &bitRate)) {
2343         param.addInt(String8(AUDIO_OFFLOAD_CODEC_AVG_BIT_RATE), bitRate);
2344     }
2345     if (meta->findInt32(kKeyEncoderDelay, &delaySamples)) {
2346         param.addInt(String8(AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES), delaySamples);
2347     }
2348     if (meta->findInt32(kKeyEncoderPadding, &paddingSamples)) {
2349         param.addInt(String8(AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES), paddingSamples);
2350     }
2351 
2352     ALOGV("sendMetaDataToHal: bitRate %d, sampleRate %d, chanMask %d,"
2353           "delaySample %d, paddingSample %d", bitRate, sampleRate,
2354           channelMask, delaySamples, paddingSamples);
2355 
2356     sink->setParameters(param.toString());
2357     return OK;
2358 }
2359 
2360 struct mime_conv_t {
2361     const char* mime;
2362     audio_format_t format;
2363 };
2364 
2365 static const struct mime_conv_t mimeLookup[] = {
2366     { MEDIA_MIMETYPE_AUDIO_MPEG,        AUDIO_FORMAT_MP3 },
2367     { MEDIA_MIMETYPE_AUDIO_RAW,         AUDIO_FORMAT_PCM_16_BIT },
2368     { MEDIA_MIMETYPE_AUDIO_AMR_NB,      AUDIO_FORMAT_AMR_NB },
2369     { MEDIA_MIMETYPE_AUDIO_AMR_WB,      AUDIO_FORMAT_AMR_WB },
2370     { MEDIA_MIMETYPE_AUDIO_AAC,         AUDIO_FORMAT_AAC },
2371     { MEDIA_MIMETYPE_AUDIO_VORBIS,      AUDIO_FORMAT_VORBIS },
2372     { MEDIA_MIMETYPE_AUDIO_OPUS,        AUDIO_FORMAT_OPUS},
2373     { MEDIA_MIMETYPE_AUDIO_AC3,         AUDIO_FORMAT_AC3},
2374     { MEDIA_MIMETYPE_AUDIO_EAC3,        AUDIO_FORMAT_E_AC3},
2375     { MEDIA_MIMETYPE_AUDIO_EAC3_JOC,    AUDIO_FORMAT_E_AC3_JOC},
2376     { MEDIA_MIMETYPE_AUDIO_AC4,         AUDIO_FORMAT_AC4},
2377     { MEDIA_MIMETYPE_AUDIO_FLAC,        AUDIO_FORMAT_FLAC},
2378     { MEDIA_MIMETYPE_AUDIO_ALAC,        AUDIO_FORMAT_ALAC },
2379     { 0, AUDIO_FORMAT_INVALID }
2380 };
2381 
mapMimeToAudioFormat(audio_format_t & format,const char * mime)2382 status_t mapMimeToAudioFormat( audio_format_t& format, const char* mime )
2383 {
2384 const struct mime_conv_t* p = &mimeLookup[0];
2385     while (p->mime != NULL) {
2386         if (0 == strcasecmp(mime, p->mime)) {
2387             format = p->format;
2388             return OK;
2389         }
2390         ++p;
2391     }
2392 
2393     return BAD_VALUE;
2394 }
2395 
2396 struct aac_format_conv_t {
2397     int32_t eAacProfileType;
2398     audio_format_t format;
2399 };
2400 
2401 static const struct aac_format_conv_t profileLookup[] = {
2402     { AACObjectMain,        AUDIO_FORMAT_AAC_MAIN},
2403     { AACObjectLC,          AUDIO_FORMAT_AAC_LC},
2404     { AACObjectSSR,         AUDIO_FORMAT_AAC_SSR},
2405     { AACObjectLTP,         AUDIO_FORMAT_AAC_LTP},
2406     { AACObjectHE,          AUDIO_FORMAT_AAC_HE_V1},
2407     { AACObjectScalable,    AUDIO_FORMAT_AAC_SCALABLE},
2408     { AACObjectERLC,        AUDIO_FORMAT_AAC_ERLC},
2409     { AACObjectLD,          AUDIO_FORMAT_AAC_LD},
2410     { AACObjectHE_PS,       AUDIO_FORMAT_AAC_HE_V2},
2411     { AACObjectELD,         AUDIO_FORMAT_AAC_ELD},
2412     { AACObjectXHE,         AUDIO_FORMAT_AAC_XHE},
2413     { AACObjectNull,        AUDIO_FORMAT_AAC},
2414 };
2415 
mapAACProfileToAudioFormat(audio_format_t & format,uint64_t eAacProfile)2416 void mapAACProfileToAudioFormat( audio_format_t& format, uint64_t eAacProfile)
2417 {
2418     const struct aac_format_conv_t* p = &profileLookup[0];
2419     while (p->eAacProfileType != AACObjectNull) {
2420         if (eAacProfile == p->eAacProfileType) {
2421             format = p->format;
2422             return;
2423         }
2424         ++p;
2425     }
2426     format = AUDIO_FORMAT_AAC;
2427     return;
2428 }
2429 
audioFormatFromEncoding(int32_t pcmEncoding)2430 audio_format_t audioFormatFromEncoding(int32_t pcmEncoding) {
2431     switch (pcmEncoding) {
2432     case kAudioEncodingPcmFloat:
2433         return AUDIO_FORMAT_PCM_FLOAT;
2434     case kAudioEncodingPcm32bit:
2435         return AUDIO_FORMAT_PCM_32_BIT;
2436     case kAudioEncodingPcm24bitPacked:
2437         return AUDIO_FORMAT_PCM_24_BIT_PACKED;
2438     case kAudioEncodingPcm16bit:
2439         return AUDIO_FORMAT_PCM_16_BIT;
2440     case kAudioEncodingPcm8bit:
2441         return AUDIO_FORMAT_PCM_8_BIT; // TODO: do we want to support this?
2442     default:
2443         ALOGE("%s: Invalid encoding: %d", __func__, pcmEncoding);
2444         return AUDIO_FORMAT_INVALID;
2445     }
2446 }
2447 
getAudioOffloadInfo(const sp<MetaData> & meta,bool hasVideo,bool isStreaming,audio_stream_type_t streamType,audio_offload_info_t * info)2448 status_t getAudioOffloadInfo(const sp<MetaData>& meta, bool hasVideo,
2449         bool isStreaming, audio_stream_type_t streamType, audio_offload_info_t *info)
2450 {
2451     const char *mime;
2452     if (meta == NULL) {
2453         return BAD_VALUE;
2454     }
2455     CHECK(meta->findCString(kKeyMIMEType, &mime));
2456 
2457     (*info) = AUDIO_INFO_INITIALIZER;
2458 
2459     info->format = AUDIO_FORMAT_INVALID;
2460     if (mapMimeToAudioFormat(info->format, mime) != OK) {
2461         ALOGE(" Couldn't map mime type \"%s\" to a valid AudioSystem::audio_format !", mime);
2462         return BAD_VALUE;
2463     } else {
2464         ALOGV("Mime type \"%s\" mapped to audio_format %d", mime, info->format);
2465     }
2466 
2467     int32_t pcmEncoding;
2468     if (meta->findInt32(kKeyPcmEncoding, &pcmEncoding)) {
2469         info->format = audioFormatFromEncoding(pcmEncoding);
2470         ALOGV("audio_format use kKeyPcmEncoding value %d first", info->format);
2471     }
2472 
2473     if (AUDIO_FORMAT_INVALID == info->format) {
2474         // can't offload if we don't know what the source format is
2475         ALOGE("mime type \"%s\" not a known audio format", mime);
2476         return BAD_VALUE;
2477     }
2478 
2479     // Redefine aac format according to its profile
2480     // Offloading depends on audio DSP capabilities.
2481     int32_t aacaot = -1;
2482     if (meta->findInt32(kKeyAACAOT, &aacaot)) {
2483         mapAACProfileToAudioFormat(info->format, aacaot);
2484     }
2485 
2486     int32_t srate = -1;
2487     if (!meta->findInt32(kKeySampleRate, &srate)) {
2488         ALOGV("track of type '%s' does not publish sample rate", mime);
2489     }
2490     info->sample_rate = srate;
2491 
2492     int32_t rawChannelMask;
2493     audio_channel_mask_t cmask = meta->findInt32(kKeyChannelMask, &rawChannelMask) ?
2494             static_cast<audio_channel_mask_t>(rawChannelMask) : CHANNEL_MASK_USE_CHANNEL_ORDER;
2495     if (cmask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
2496         ALOGV("track of type '%s' does not publish channel mask", mime);
2497 
2498         // Try a channel count instead
2499         int32_t channelCount;
2500         if (!meta->findInt32(kKeyChannelCount, &channelCount)) {
2501             ALOGV("track of type '%s' does not publish channel count", mime);
2502         } else {
2503             cmask = audio_channel_out_mask_from_count(channelCount);
2504         }
2505     }
2506     info->channel_mask = cmask;
2507 
2508     int64_t duration = 0;
2509     if (!meta->findInt64(kKeyDuration, &duration)) {
2510         ALOGV("track of type '%s' does not publish duration", mime);
2511     }
2512     info->duration_us = duration;
2513 
2514     int32_t brate = 0;
2515     if (!meta->findInt32(kKeyBitRate, &brate)) {
2516         ALOGV("track of type '%s' does not publish bitrate", mime);
2517     }
2518     info->bit_rate = brate;
2519 
2520 
2521     info->stream_type = streamType;
2522     info->has_video = hasVideo;
2523     info->is_streaming = isStreaming;
2524     return OK;
2525 }
2526 
canOffloadStream(const sp<MetaData> & meta,bool hasVideo,bool isStreaming,audio_stream_type_t streamType)2527 bool canOffloadStream(const sp<MetaData>& meta, bool hasVideo,
2528                       bool isStreaming, audio_stream_type_t streamType)
2529 {
2530     audio_offload_info_t info = AUDIO_INFO_INITIALIZER;
2531     const char *mime;
2532     if (meta != nullptr && meta->findCString(kKeyMIMEType, &mime)
2533         && strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_OPUS) == 0) {
2534         return false;
2535     }
2536     if (OK != getAudioOffloadInfo(meta, hasVideo, isStreaming, streamType, &info)) {
2537         return false;
2538     }
2539     // Check if offload is possible for given format, stream type, sample rate,
2540     // bit rate, duration, video and streaming
2541 #ifdef DISABLE_AUDIO_SYSTEM_OFFLOAD
2542     return false;
2543 #else
2544     return AudioSystem::getOffloadSupport(info) != AUDIO_OFFLOAD_NOT_SUPPORTED;
2545 #endif
2546 }
2547 
HLSTime(const sp<AMessage> & meta)2548 HLSTime::HLSTime(const sp<AMessage>& meta) :
2549     mSeq(-1),
2550     mTimeUs(-1LL),
2551     mMeta(meta) {
2552     if (meta != NULL) {
2553         CHECK(meta->findInt32("discontinuitySeq", &mSeq));
2554         CHECK(meta->findInt64("timeUs", &mTimeUs));
2555     }
2556 }
2557 
getSegmentTimeUs() const2558 int64_t HLSTime::getSegmentTimeUs() const {
2559     int64_t segmentStartTimeUs = -1LL;
2560     if (mMeta != NULL) {
2561         CHECK(mMeta->findInt64("segmentStartTimeUs", &segmentStartTimeUs));
2562 
2563         int64_t segmentFirstTimeUs;
2564         if (mMeta->findInt64("segmentFirstTimeUs", &segmentFirstTimeUs)) {
2565             segmentStartTimeUs += mTimeUs - segmentFirstTimeUs;
2566         }
2567 
2568         // adjust segment time by playlist age (for live streaming)
2569         int64_t playlistTimeUs;
2570         if (mMeta->findInt64("playlistTimeUs", &playlistTimeUs)) {
2571             int64_t playlistAgeUs = ALooper::GetNowUs() - playlistTimeUs;
2572 
2573             int64_t durationUs;
2574             CHECK(mMeta->findInt64("segmentDurationUs", &durationUs));
2575 
2576             // round to nearest whole segment
2577             playlistAgeUs = (playlistAgeUs + durationUs / 2)
2578                     / durationUs * durationUs;
2579 
2580             segmentStartTimeUs -= playlistAgeUs;
2581             if (segmentStartTimeUs < 0) {
2582                 segmentStartTimeUs = 0;
2583             }
2584         }
2585     }
2586     return segmentStartTimeUs;
2587 }
2588 
operator <(const HLSTime & t0,const HLSTime & t1)2589 bool operator <(const HLSTime &t0, const HLSTime &t1) {
2590     // we can only compare discontinuity sequence and timestamp.
2591     // (mSegmentTimeUs is not reliable in live streaming case, it's the
2592     // time starting from beginning of playlist but playlist could change.)
2593     return t0.mSeq < t1.mSeq
2594             || (t0.mSeq == t1.mSeq && t0.mTimeUs < t1.mTimeUs);
2595 }
2596 
writeToAMessage(const sp<AMessage> & msg,const AudioPlaybackRate & rate)2597 void writeToAMessage(const sp<AMessage> &msg, const AudioPlaybackRate &rate) {
2598     msg->setFloat("speed", rate.mSpeed);
2599     msg->setFloat("pitch", rate.mPitch);
2600     msg->setInt32("audio-fallback-mode", rate.mFallbackMode);
2601     msg->setInt32("audio-stretch-mode", rate.mStretchMode);
2602 }
2603 
readFromAMessage(const sp<AMessage> & msg,AudioPlaybackRate * rate)2604 void readFromAMessage(const sp<AMessage> &msg, AudioPlaybackRate *rate /* nonnull */) {
2605     *rate = AUDIO_PLAYBACK_RATE_DEFAULT;
2606     CHECK(msg->findFloat("speed", &rate->mSpeed));
2607     CHECK(msg->findFloat("pitch", &rate->mPitch));
2608     CHECK(msg->findInt32("audio-fallback-mode", (int32_t *)&rate->mFallbackMode));
2609     CHECK(msg->findInt32("audio-stretch-mode", (int32_t *)&rate->mStretchMode));
2610 }
2611 
writeToAMessage(const sp<AMessage> & msg,const AVSyncSettings & sync,float videoFpsHint)2612 void writeToAMessage(const sp<AMessage> &msg, const AVSyncSettings &sync, float videoFpsHint) {
2613     msg->setInt32("sync-source", sync.mSource);
2614     msg->setInt32("audio-adjust-mode", sync.mAudioAdjustMode);
2615     msg->setFloat("tolerance", sync.mTolerance);
2616     msg->setFloat("video-fps", videoFpsHint);
2617 }
2618 
readFromAMessage(const sp<AMessage> & msg,AVSyncSettings * sync,float * videoFps)2619 void readFromAMessage(
2620         const sp<AMessage> &msg,
2621         AVSyncSettings *sync /* nonnull */,
2622         float *videoFps /* nonnull */) {
2623     AVSyncSettings settings;
2624     CHECK(msg->findInt32("sync-source", (int32_t *)&settings.mSource));
2625     CHECK(msg->findInt32("audio-adjust-mode", (int32_t *)&settings.mAudioAdjustMode));
2626     CHECK(msg->findFloat("tolerance", &settings.mTolerance));
2627     CHECK(msg->findFloat("video-fps", videoFps));
2628     *sync = settings;
2629 }
2630 
writeToAMessage(const sp<AMessage> & msg,const BufferingSettings & buffering)2631 void writeToAMessage(const sp<AMessage> &msg, const BufferingSettings &buffering) {
2632     msg->setInt32("init-ms", buffering.mInitialMarkMs);
2633     msg->setInt32("resume-playback-ms", buffering.mResumePlaybackMarkMs);
2634 }
2635 
readFromAMessage(const sp<AMessage> & msg,BufferingSettings * buffering)2636 void readFromAMessage(const sp<AMessage> &msg, BufferingSettings *buffering /* nonnull */) {
2637     int32_t value;
2638     if (msg->findInt32("init-ms", &value)) {
2639         buffering->mInitialMarkMs = value;
2640     }
2641     if (msg->findInt32("resume-playback-ms", &value)) {
2642         buffering->mResumePlaybackMarkMs = value;
2643     }
2644 }
2645 
2646 }  // namespace android
2647