已关闭
自研MP4性能优化-插件-ROM优化 #9374
自研MP4性能优化-插件-ROM优化 #9374
已关闭
杨俊晖创建于 9 天前关闭于 2 天前
11 个文件变更+711-560
Mservices/media_engine/plugins/demuxer/common/converter.cpp+44-46
@@ -15,8 +15,8 @@
15 15 
16#define HST_LOG_TAG "Converter"16#define HST_LOG_TAG "Converter"
17 17 
18-#include <vector>
19#include <algorithm>18#include <algorithm>
19+#include <iterator>
20#include <limits>20#include <limits>
21#include <new>21#include <new>
22#include <iconv.h>22#include <iconv.h>
@@ -37,7 +37,7 @@ const uint32_t DOUBLE_BYTES = 2;
37 37 
38#ifdef USE_FF_DEMUXER38#ifdef USE_FF_DEMUXER
39// ffmpeg channel layout to histreamer channel layout39// ffmpeg channel layout to histreamer channel layout
40-const std::vector<std::pair<AudioChannelLayout, uint64_t>> g_toFFMPEGChannelLayout = {40+constexpr std::pair<AudioChannelLayout, uint64_t> g_toFFMPEGChannelLayout[] = {
41 {AudioChannelLayout::MONO, AV_CH_LAYOUT_MONO},41 {AudioChannelLayout::MONO, AV_CH_LAYOUT_MONO},
42 {AudioChannelLayout::STEREO, AV_CH_LAYOUT_STEREO},42 {AudioChannelLayout::STEREO, AV_CH_LAYOUT_STEREO},
43 {AudioChannelLayout::CH_2POINT1, AV_CH_LAYOUT_2POINT1},43 {AudioChannelLayout::CH_2POINT1, AV_CH_LAYOUT_2POINT1},
@@ -68,7 +68,7 @@ const std::vector<std::pair<AudioChannelLayout, uint64_t>> g_toFFMPEGChannelLayo
68 {AudioChannelLayout::STEREO_DOWNMIX, AV_CH_LAYOUT_STEREO_DOWNMIX},68 {AudioChannelLayout::STEREO_DOWNMIX, AV_CH_LAYOUT_STEREO_DOWNMIX},
69};69};
70 70 
71-const std::vector<std::pair<AudioChannelLayout, int>> g_audioVividChannelLayoutMap = {71+constexpr std::pair<AudioChannelLayout, int> g_audioVividChannelLayoutMap[] = {
72 {AudioChannelLayout::MONO, 1},72 {AudioChannelLayout::MONO, 1},
73 {AudioChannelLayout::STEREO, 2},73 {AudioChannelLayout::STEREO, 2},
74 {AudioChannelLayout::CH_4POINT0, 4},74 {AudioChannelLayout::CH_4POINT0, 4},
@@ -86,7 +86,7 @@ const std::vector<std::pair<AudioChannelLayout, int>> g_audioVividChannelLayoutM
86};86};
87#endif87#endif
88 88 
89-const std::vector<std::pair<int, AudioChannelLayout>> g_channelLayoutDefaultMap = {89+constexpr std::pair<int, AudioChannelLayout> g_channelLayoutDefaultMap[] = {
90 {2, AudioChannelLayout::STEREO}, // 2: STEREO90 {2, AudioChannelLayout::STEREO}, // 2: STEREO
91 {4, AudioChannelLayout::CH_4POINT0}, // 4: CH_4POINT091 {4, AudioChannelLayout::CH_4POINT0}, // 4: CH_4POINT0
92 {5, AudioChannelLayout::CH_5POINT0}, // 5: CH_5POINT092 {5, AudioChannelLayout::CH_5POINT0}, // 5: CH_5POINT0
@@ -102,7 +102,7 @@ const std::vector<std::pair<int, AudioChannelLayout>> g_channelLayoutDefaultMap
102};102};
103 103 
104#ifdef USE_FF_DEMUXER104#ifdef USE_FF_DEMUXER
105-const std::vector<std::pair<AVSampleFormat, AudioSampleFormat>> g_pFfSampleFmtMap = {105+constexpr std::pair<AVSampleFormat, AudioSampleFormat> g_pFfSampleFmtMap[] = {
106 {AVSampleFormat::AV_SAMPLE_FMT_U8, AudioSampleFormat::SAMPLE_U8},106 {AVSampleFormat::AV_SAMPLE_FMT_U8, AudioSampleFormat::SAMPLE_U8},
107 {AVSampleFormat::AV_SAMPLE_FMT_S16, AudioSampleFormat::SAMPLE_S16LE},107 {AVSampleFormat::AV_SAMPLE_FMT_S16, AudioSampleFormat::SAMPLE_S16LE},
108 {AVSampleFormat::AV_SAMPLE_FMT_S32, AudioSampleFormat::SAMPLE_S32LE},108 {AVSampleFormat::AV_SAMPLE_FMT_S32, AudioSampleFormat::SAMPLE_S32LE},
@@ -114,7 +114,7 @@ const std::vector<std::pair<AVSampleFormat, AudioSampleFormat>> g_pFfSampleFmtMa
114};114};
115 115 
116// align with player framework capability.116// align with player framework capability.
117-const std::vector<std::pair<AVCodecID, AudioSampleFormat>> g_pFfCodeIDToSampleFmtMap = {117+constexpr std::pair<AVCodecID, AudioSampleFormat> g_pFfCodeIDToSampleFmtMap[] = {
118 {AVCodecID::AV_CODEC_ID_PCM_U8, AudioSampleFormat::SAMPLE_U8},118 {AVCodecID::AV_CODEC_ID_PCM_U8, AudioSampleFormat::SAMPLE_U8},
119 {AVCodecID::AV_CODEC_ID_PCM_S16LE, AudioSampleFormat::SAMPLE_S16LE},119 {AVCodecID::AV_CODEC_ID_PCM_S16LE, AudioSampleFormat::SAMPLE_S16LE},
120 {AVCodecID::AV_CODEC_ID_PCM_S24LE, AudioSampleFormat::SAMPLE_S24LE},120 {AVCodecID::AV_CODEC_ID_PCM_S24LE, AudioSampleFormat::SAMPLE_S24LE},
@@ -140,7 +140,7 @@ const std::vector<std::pair<AVCodecID, AudioSampleFormat>> g_pFfCodeIDToSampleFm
140};140};
141#endif141#endif
142 142 
143-const std::vector<std::pair<AudioChannelLayout, std::string_view>> g_ChannelLayoutToString = {143+constexpr std::pair<AudioChannelLayout, std::string_view> g_ChannelLayoutToString[] = {
144 {AudioChannelLayout::UNKNOWN, "UNKNOW"},144 {AudioChannelLayout::UNKNOWN, "UNKNOW"},
145 {AudioChannelLayout::MONO, "MONO"},145 {AudioChannelLayout::MONO, "MONO"},
146 {AudioChannelLayout::STEREO, "STEREO"},146 {AudioChannelLayout::STEREO, "STEREO"},
@@ -193,7 +193,7 @@ const std::vector<std::pair<AudioChannelLayout, std::string_view>> g_ChannelLayo
193 {AudioChannelLayout::HOA_ORDER3_FUMA, "HOA_ORDER3_FUMA"},193 {AudioChannelLayout::HOA_ORDER3_FUMA, "HOA_ORDER3_FUMA"},
194};194};
195 195 
196-const std::vector<std::pair<int32_t, ColorPrimary>> g_pFfColorPrimariesMap = {196+constexpr std::pair<int32_t, ColorPrimary> g_pFfColorPrimariesMap[] = {
197 {1, ColorPrimary::BT709},197 {1, ColorPrimary::BT709},
198 {2, ColorPrimary::UNSPECIFIED},198 {2, ColorPrimary::UNSPECIFIED},
199 {4, ColorPrimary::BT470_M},199 {4, ColorPrimary::BT470_M},
@@ -207,7 +207,7 @@ const std::vector<std::pair<int32_t, ColorPrimary>> g_pFfColorPrimariesMap = {
207 {12, ColorPrimary::P3D65},207 {12, ColorPrimary::P3D65},
208};208};
209 209 
210-const std::vector<std::pair<int32_t, TransferCharacteristic>> g_pFfTransferCharacteristicMap = {210+constexpr std::pair<int32_t, TransferCharacteristic> g_pFfTransferCharacteristicMap[] = {
211 {1, TransferCharacteristic::BT709},211 {1, TransferCharacteristic::BT709},
212 {2, TransferCharacteristic::UNSPECIFIED},212 {2, TransferCharacteristic::UNSPECIFIED},
213 {4, TransferCharacteristic::GAMMA_2_2},213 {4, TransferCharacteristic::GAMMA_2_2},
@@ -227,7 +227,7 @@ const std::vector<std::pair<int32_t, TransferCharacteristic>> g_pFfTransferChara
227 {18, TransferCharacteristic::HLG},227 {18, TransferCharacteristic::HLG},
228};228};
229 229 
230-const std::vector<std::pair<int32_t, MatrixCoefficient>> g_pFfMatrixCoefficientMap = {230+constexpr std::pair<int32_t, MatrixCoefficient> g_pFfMatrixCoefficientMap[] = {
231 {0, MatrixCoefficient::IDENTITY},231 {0, MatrixCoefficient::IDENTITY},
232 {1, MatrixCoefficient::BT709},232 {1, MatrixCoefficient::BT709},
233 {2, MatrixCoefficient::UNSPECIFIED},233 {2, MatrixCoefficient::UNSPECIFIED},
@@ -244,12 +244,12 @@ const std::vector<std::pair<int32_t, MatrixCoefficient>> g_pFfMatrixCoefficientM
244 {14, MatrixCoefficient::ICTCP},244 {14, MatrixCoefficient::ICTCP},
245};245};
246 246 
247-const std::vector<std::pair<int32_t, int32_t>> g_pFfColorRangeMap = {247+constexpr std::pair<int32_t, int32_t> g_pFfColorRangeMap[] = {
248 {1, 0},248 {1, 0},
249 {2, 1},249 {2, 1},
250};250};
251 251 
252-const std::vector<std::pair<int32_t, ChromaLocation>> g_pFfChromaLocationMap = {252+constexpr std::pair<int32_t, ChromaLocation> g_pFfChromaLocationMap[] = {
253 {0, ChromaLocation::UNSPECIFIED},253 {0, ChromaLocation::UNSPECIFIED},
254 {1, ChromaLocation::LEFT},254 {1, ChromaLocation::LEFT},
255 {2, ChromaLocation::CENTER},255 {2, ChromaLocation::CENTER},
@@ -259,13 +259,13 @@ const std::vector<std::pair<int32_t, ChromaLocation>> g_pFfChromaLocationMap = {
259 {6, ChromaLocation::BOTTOM},259 {6, ChromaLocation::BOTTOM},
260};260};
261 261 
262-const std::vector<std::pair<int, HEVCProfile>> g_pFfHEVCProfileMap = {262+constexpr std::pair<int, HEVCProfile> g_pFfHEVCProfileMap[] = {
263 {1, HEVCProfile::HEVC_PROFILE_MAIN},263 {1, HEVCProfile::HEVC_PROFILE_MAIN},
264 {2, HEVCProfile::HEVC_PROFILE_MAIN_10},264 {2, HEVCProfile::HEVC_PROFILE_MAIN_10},
265 {3, HEVCProfile::HEVC_PROFILE_MAIN_STILL},265 {3, HEVCProfile::HEVC_PROFILE_MAIN_STILL},
266};266};
267 267 
268-const std::vector<std::pair<int, HEVCLevel>> g_pFfHEVCLevelMap = {268+constexpr std::pair<int, HEVCLevel> g_pFfHEVCLevelMap[] = {
269 {30, HEVCLevel::HEVC_LEVEL_1}, {60, HEVCLevel::HEVC_LEVEL_2}, {63, HEVCLevel::HEVC_LEVEL_21},269 {30, HEVCLevel::HEVC_LEVEL_1}, {60, HEVCLevel::HEVC_LEVEL_2}, {63, HEVCLevel::HEVC_LEVEL_21},
270 {90, HEVCLevel::HEVC_LEVEL_3}, {93, HEVCLevel::HEVC_LEVEL_31}, {120, HEVCLevel::HEVC_LEVEL_4},270 {90, HEVCLevel::HEVC_LEVEL_3}, {93, HEVCLevel::HEVC_LEVEL_31}, {120, HEVCLevel::HEVC_LEVEL_4},
271 {123, HEVCLevel::HEVC_LEVEL_41}, {150, HEVCLevel::HEVC_LEVEL_5}, {153, HEVCLevel::HEVC_LEVEL_51},271 {123, HEVCLevel::HEVC_LEVEL_41}, {150, HEVCLevel::HEVC_LEVEL_5}, {153, HEVCLevel::HEVC_LEVEL_51},
@@ -275,9 +275,9 @@ const std::vector<std::pair<int, HEVCLevel>> g_pFfHEVCLevelMap = {
275 275 
276HEVCLevel Converter::ConvertToOHHEVCLevel(int ffHEVCLevel)276HEVCLevel Converter::ConvertToOHHEVCLevel(int ffHEVCLevel)
277{277{
278- auto ite = std::find_if(g_pFfHEVCLevelMap.begin(), g_pFfHEVCLevelMap.end(),278+ auto ite = std::find_if(std::begin(g_pFfHEVCLevelMap), std::end(g_pFfHEVCLevelMap),
279 [&ffHEVCLevel](const auto &item) -> bool { return item.first == ffHEVCLevel; });279 [&ffHEVCLevel](const auto &item) -> bool { return item.first == ffHEVCLevel; });
280- if (ite == g_pFfHEVCLevelMap.end()) {280+ if (ite == std::end(g_pFfHEVCLevelMap)) {
281 MEDIA_LOG_W("Failed: " PUBLIC_LOG_D32, ffHEVCLevel);281 MEDIA_LOG_W("Failed: " PUBLIC_LOG_D32, ffHEVCLevel);
282 return HEVCLevel::HEVC_LEVEL_UNKNOW;282 return HEVCLevel::HEVC_LEVEL_UNKNOW;
283 }283 }
@@ -286,9 +286,9 @@ HEVCLevel Converter::ConvertToOHHEVCLevel(int ffHEVCLevel)
286 286 
287HEVCProfile Converter::ConvertToOHHEVCProfile(int ffHEVCProfile)287HEVCProfile Converter::ConvertToOHHEVCProfile(int ffHEVCProfile)
288{288{
289- auto ite = std::find_if(g_pFfHEVCProfileMap.begin(), g_pFfHEVCProfileMap.end(),289+ auto ite = std::find_if(std::begin(g_pFfHEVCProfileMap), std::end(g_pFfHEVCProfileMap),
290 [&ffHEVCProfile](const auto &item) -> bool { return item.first == ffHEVCProfile; });290 [&ffHEVCProfile](const auto &item) -> bool { return item.first == ffHEVCProfile; });
291- if (ite == g_pFfHEVCProfileMap.end()) {291+ if (ite == std::end(g_pFfHEVCProfileMap)) {
292 MEDIA_LOG_W("Failed: " PUBLIC_LOG_D32, ffHEVCProfile);292 MEDIA_LOG_W("Failed: " PUBLIC_LOG_D32, ffHEVCProfile);
293 return HEVCProfile::HEVC_PROFILE_UNKNOW;293 return HEVCProfile::HEVC_PROFILE_UNKNOW;
294 }294 }
@@ -297,36 +297,38 @@ HEVCProfile Converter::ConvertToOHHEVCProfile(int ffHEVCProfile)
297 297 
298ColorPrimary Converter::ConvertFFMpegToOHColorPrimaries(int32_t colorPrimaries)298ColorPrimary Converter::ConvertFFMpegToOHColorPrimaries(int32_t colorPrimaries)
299{299{
300- auto ite = std::find_if(g_pFfColorPrimariesMap.begin(), g_pFfColorPrimariesMap.end(),300+ auto ite = std::find_if(std::begin(g_pFfColorPrimariesMap), std::end(g_pFfColorPrimariesMap),
301 [colorPrimaries](const auto &item) -> bool { return item.first == colorPrimaries; });301 [colorPrimaries](const auto &item) -> bool { return item.first == colorPrimaries; });
302- CHECK_AND_RETURN_RET_LOGW(ite != g_pFfColorPrimariesMap.end(), ColorPrimary::UNSPECIFIED,302+ CHECK_AND_RETURN_RET_LOGW(ite != std::end(g_pFfColorPrimariesMap), ColorPrimary::UNSPECIFIED,
303 "Failed: " PUBLIC_LOG_D32, colorPrimaries);303 "Failed: " PUBLIC_LOG_D32, colorPrimaries);
304 return ite->second;304 return ite->second;
305}305}
306 306 
307TransferCharacteristic Converter::ConvertFFMpegToOHColorTrans(int32_t colorTransfer)307TransferCharacteristic Converter::ConvertFFMpegToOHColorTrans(int32_t colorTransfer)
308{308{
309- auto ite = std::find_if(g_pFfTransferCharacteristicMap.begin(), g_pFfTransferCharacteristicMap.end(),309+ auto ite = std::find_if(std::begin(g_pFfTransferCharacteristicMap),
310+ std::end(g_pFfTransferCharacteristicMap),
310 [colorTransfer](const auto &item) -> bool { return item.first == colorTransfer; });311 [colorTransfer](const auto &item) -> bool { return item.first == colorTransfer; });
311- CHECK_AND_RETURN_RET_LOGW(ite != g_pFfTransferCharacteristicMap.end(), TransferCharacteristic::UNSPECIFIED,312+ CHECK_AND_RETURN_RET_LOGW(ite != std::end(g_pFfTransferCharacteristicMap),
313+ TransferCharacteristic::UNSPECIFIED,
312 "Failed: " PUBLIC_LOG_D32, colorTransfer);314 "Failed: " PUBLIC_LOG_D32, colorTransfer);
313 return ite->second;315 return ite->second;
314}316}
315 317 
316MatrixCoefficient Converter::ConvertFFMpegToOHColorMatrix(int32_t colorSpace)318MatrixCoefficient Converter::ConvertFFMpegToOHColorMatrix(int32_t colorSpace)
317{319{
318- auto ite = std::find_if(g_pFfMatrixCoefficientMap.begin(), g_pFfMatrixCoefficientMap.end(),320+ auto ite = std::find_if(std::begin(g_pFfMatrixCoefficientMap), std::end(g_pFfMatrixCoefficientMap),
319 [colorSpace](const auto &item) -> bool { return item.first == colorSpace; });321 [colorSpace](const auto &item) -> bool { return item.first == colorSpace; });
320- CHECK_AND_RETURN_RET_LOGW(ite != g_pFfMatrixCoefficientMap.end(), MatrixCoefficient::UNSPECIFIED,322+ CHECK_AND_RETURN_RET_LOGW(ite != std::end(g_pFfMatrixCoefficientMap), MatrixCoefficient::UNSPECIFIED,
321 "Failed: " PUBLIC_LOG_D32, colorSpace);323 "Failed: " PUBLIC_LOG_D32, colorSpace);
322 return ite->second;324 return ite->second;
323}325}
324 326 
325int32_t Converter::ConvertFFMpegToOHColorRange(int32_t colorRange)327int32_t Converter::ConvertFFMpegToOHColorRange(int32_t colorRange)
326{328{
327- auto ite = std::find_if(g_pFfColorRangeMap.begin(), g_pFfColorRangeMap.end(),329+ auto ite = std::find_if(std::begin(g_pFfColorRangeMap), std::end(g_pFfColorRangeMap),
328 [colorRange](const auto &item) -> bool { return item.first == colorRange; });330 [colorRange](const auto &item) -> bool { return item.first == colorRange; });
329- if (ite == g_pFfColorRangeMap.end()) {331+ if (ite == std::end(g_pFfColorRangeMap)) {
330 MEDIA_LOG_W("Failed: " PUBLIC_LOG_D32, colorRange);332 MEDIA_LOG_W("Failed: " PUBLIC_LOG_D32, colorRange);
331 return 0;333 return 0;
332 }334 }
@@ -335,9 +337,9 @@ int32_t Converter::ConvertFFMpegToOHColorRange(int32_t colorRange)
335 337 
336ChromaLocation Converter::ConvertFFMpegToOHChromaLocation(int32_t chromaLocation)338ChromaLocation Converter::ConvertFFMpegToOHChromaLocation(int32_t chromaLocation)
337{339{
338- auto ite = std::find_if(g_pFfChromaLocationMap.begin(), g_pFfChromaLocationMap.end(),340+ auto ite = std::find_if(std::begin(g_pFfChromaLocationMap), std::end(g_pFfChromaLocationMap),
339 [chromaLocation](const auto &item) -> bool { return item.first == chromaLocation; });341 [chromaLocation](const auto &item) -> bool { return item.first == chromaLocation; });
340- CHECK_AND_RETURN_RET_LOGW(ite != g_pFfChromaLocationMap.end(), ChromaLocation::UNSPECIFIED,342+ CHECK_AND_RETURN_RET_LOGW(ite != std::end(g_pFfChromaLocationMap), ChromaLocation::UNSPECIFIED,
341 "Failed: " PUBLIC_LOG_D32, chromaLocation);343 "Failed: " PUBLIC_LOG_D32, chromaLocation);
342 return ite->second;344 return ite->second;
343}345}
@@ -345,9 +347,9 @@ ChromaLocation Converter::ConvertFFMpegToOHChromaLocation(int32_t chromaLocation
345#ifdef USE_FF_DEMUXER347#ifdef USE_FF_DEMUXER
346AudioSampleFormat Converter::ConvertFFMpegAVCodecIdToOHAudioFormat(AVCodecID codecId)348AudioSampleFormat Converter::ConvertFFMpegAVCodecIdToOHAudioFormat(AVCodecID codecId)
347{349{
348- auto ite = std::find_if(g_pFfCodeIDToSampleFmtMap.begin(), g_pFfCodeIDToSampleFmtMap.end(),350+ auto ite = std::find_if(std::begin(g_pFfCodeIDToSampleFmtMap), std::end(g_pFfCodeIDToSampleFmtMap),
349 [&codecId](const auto &item) -> bool { return item.first == codecId; });351 [&codecId](const auto &item) -> bool { return item.first == codecId; });
350- if (ite == g_pFfCodeIDToSampleFmtMap.end()) {352+ if (ite == std::end(g_pFfCodeIDToSampleFmtMap)) {
351 MEDIA_LOG_W("Failed: " PUBLIC_LOG_D32, static_cast<int32_t>(codecId));353 MEDIA_LOG_W("Failed: " PUBLIC_LOG_D32, static_cast<int32_t>(codecId));
352 return AudioSampleFormat::INVALID_WIDTH;354 return AudioSampleFormat::INVALID_WIDTH;
353 }355 }
@@ -356,9 +358,9 @@ AudioSampleFormat Converter::ConvertFFMpegAVCodecIdToOHAudioFormat(AVCodecID cod
356 358 
357AudioSampleFormat Converter::ConvertFFMpegToOHAudioFormat(AVSampleFormat ffSampleFormat)359AudioSampleFormat Converter::ConvertFFMpegToOHAudioFormat(AVSampleFormat ffSampleFormat)
358{360{
359- auto ite = std::find_if(g_pFfSampleFmtMap.begin(), g_pFfSampleFmtMap.end(),361+ auto ite = std::find_if(std::begin(g_pFfSampleFmtMap), std::end(g_pFfSampleFmtMap),
360 [&ffSampleFormat](const auto &item) -> bool { return item.first == ffSampleFormat; });362 [&ffSampleFormat](const auto &item) -> bool { return item.first == ffSampleFormat; });
361- if (ite == g_pFfSampleFmtMap.end()) {363+ if (ite == std::end(g_pFfSampleFmtMap)) {
362 MEDIA_LOG_W("Failed: " PUBLIC_LOG_D32, static_cast<int32_t>(ffSampleFormat));364 MEDIA_LOG_W("Failed: " PUBLIC_LOG_D32, static_cast<int32_t>(ffSampleFormat));
363 return AudioSampleFormat::INVALID_WIDTH;365 return AudioSampleFormat::INVALID_WIDTH;
364 }366 }
@@ -369,9 +371,9 @@ AudioSampleFormat Converter::ConvertFFMpegToOHAudioFormat(AVSampleFormat ffSampl
369AudioChannelLayout Converter::GetDefaultChannelLayout(int channels)371AudioChannelLayout Converter::GetDefaultChannelLayout(int channels)
370{372{
371 AudioChannelLayout layout = AudioChannelLayout::MONO;373 AudioChannelLayout layout = AudioChannelLayout::MONO;
372- auto ite = std::find_if(g_channelLayoutDefaultMap.begin(), g_channelLayoutDefaultMap.end(),374+ auto ite = std::find_if(std::begin(g_channelLayoutDefaultMap), std::end(g_channelLayoutDefaultMap),
373 [&channels](const auto &item) -> bool { return item.first == channels; });375 [&channels](const auto &item) -> bool { return item.first == channels; });
374- if (ite != g_channelLayoutDefaultMap.end()) {376+ if (ite != std::end(g_channelLayoutDefaultMap)) {
375 layout = ite->second;377 layout = ite->second;
376 }378 }
377 MEDIA_LOG_W("Default: " PUBLIC_LOG_S, ConvertOHAudioChannelLayoutToString(layout).data());379 MEDIA_LOG_W("Default: " PUBLIC_LOG_S, ConvertOHAudioChannelLayoutToString(layout).data());
@@ -381,9 +383,9 @@ AudioChannelLayout Converter::GetDefaultChannelLayout(int channels)
381#ifdef USE_FF_DEMUXER383#ifdef USE_FF_DEMUXER
382AudioChannelLayout Converter::ConvertFFToOHAudioChannelLayoutV2(uint64_t ffChannelLayout, int channels)384AudioChannelLayout Converter::ConvertFFToOHAudioChannelLayoutV2(uint64_t ffChannelLayout, int channels)
383{385{
384- auto ite = std::find_if(g_toFFMPEGChannelLayout.begin(), g_toFFMPEGChannelLayout.end(),386+ auto ite = std::find_if(std::begin(g_toFFMPEGChannelLayout), std::end(g_toFFMPEGChannelLayout),
385 [&ffChannelLayout](const auto &item) -> bool { return item.second == ffChannelLayout; });387 [&ffChannelLayout](const auto &item) -> bool { return item.second == ffChannelLayout; });
386- if (ite == g_toFFMPEGChannelLayout.end()) {388+ if (ite == std::end(g_toFFMPEGChannelLayout)) {
387 MEDIA_LOG_W("Failed: " PUBLIC_LOG_U64, ffChannelLayout);389 MEDIA_LOG_W("Failed: " PUBLIC_LOG_U64, ffChannelLayout);
388 return GetDefaultChannelLayout(channels);390 return GetDefaultChannelLayout(channels);
389 }391 }
@@ -393,9 +395,9 @@ AudioChannelLayout Converter::ConvertFFToOHAudioChannelLayoutV2(uint64_t ffChann
393 395 
394std::string_view Converter::ConvertOHAudioChannelLayoutToString(AudioChannelLayout layout)396std::string_view Converter::ConvertOHAudioChannelLayoutToString(AudioChannelLayout layout)
395{397{
396- auto ite = std::find_if(g_ChannelLayoutToString.begin(), g_ChannelLayoutToString.end(),398+ auto ite = std::find_if(std::begin(g_ChannelLayoutToString), std::end(g_ChannelLayoutToString),
397 [&layout](const auto &item) -> bool { return item.first == layout; });399 [&layout](const auto &item) -> bool { return item.first == layout; });
398- CHECK_AND_RETURN_RET_LOGW(ite != g_ChannelLayoutToString.end(), g_ChannelLayoutToString[0].second,400+ CHECK_AND_RETURN_RET_LOGW(ite != std::end(g_ChannelLayoutToString), g_ChannelLayoutToString[0].second,
399 "Failed: " PUBLIC_LOG_D32, static_cast<int32_t>(layout));401 "Failed: " PUBLIC_LOG_D32, static_cast<int32_t>(layout));
400 return ite->second;402 return ite->second;
401}403}
@@ -403,11 +405,11 @@ std::string_view Converter::ConvertOHAudioChannelLayoutToString(AudioChannelLayo
403#ifdef USE_FF_DEMUXER405#ifdef USE_FF_DEMUXER
404AudioChannelLayout Converter::ConvertAudioVividToOHAudioChannelLayout(uint64_t ffChannelLayout, int channels)406AudioChannelLayout Converter::ConvertAudioVividToOHAudioChannelLayout(uint64_t ffChannelLayout, int channels)
405{407{
406- auto ite = std::find_if(g_audioVividChannelLayoutMap.begin(), g_audioVividChannelLayoutMap.end(),408+ auto ite = std::find_if(std::begin(g_audioVividChannelLayoutMap), std::end(g_audioVividChannelLayoutMap),
407 [&ffChannelLayout](const auto &item) -> bool {409 [&ffChannelLayout](const auto &item) -> bool {
408 return static_cast<uint64_t>(item.first) == ffChannelLayout;410 return static_cast<uint64_t>(item.first) == ffChannelLayout;
409 });411 });
410- CHECK_AND_RETURN_RET_LOGW((ite != g_audioVividChannelLayoutMap.end()) && (ite -> second == channels),412+ CHECK_AND_RETURN_RET_LOGW((ite != std::end(g_audioVividChannelLayoutMap)) && (ite -> second == channels),
411 GetDefaultChannelLayout(channels), "Convert channel layout failed: " PUBLIC_LOG_U64,413 GetDefaultChannelLayout(channels), "Convert channel layout failed: " PUBLIC_LOG_U64,
412 ffChannelLayout);414 ffChannelLayout);
413 return ite->first;415 return ite->first;
@@ -550,12 +552,8 @@ std::string Converter::ConvertGBKToUTF8(const std::string &strGbk)
550 return "";552 return "";
551 }553 }
552 size_t outLen = inLen * maxUtf8BytesPerGbkChar;554 size_t outLen = inLen * maxUtf8BytesPerGbkChar;
553- char* inBuf = const_cast<char*>(strGbk.c_str());555+ std::string input = strGbk;
554- if (inBuf == nullptr) {556+ char* inBuf = input.data();
555- MEDIA_LOG_D("Get in buffer failed");
556- iconv_close(cd);
557- return "";
558- }
559 char* outBuf = new (std::nothrow) char[outLen];557 char* outBuf = new (std::nothrow) char[outLen];
560 if (outBuf == nullptr) {558 if (outBuf == nullptr) {
561 MEDIA_LOG_D("Get out buffer failed");559 MEDIA_LOG_D("Get out buffer failed");
Mservices/media_engine/plugins/demuxer/common/demuxer_log_compressor.cpp+46-19
@@ -15,8 +15,8 @@
15 15 
16#define HST_LOG_TAG "DemuxerLogCompressor"16#define HST_LOG_TAG "DemuxerLogCompressor"
17 17 
18-#include <unordered_map>18+#include <array>
19-#include <sstream>19+#include <string_view>
20#include "meta/meta_key.h"20#include "meta/meta_key.h"
21#include "meta/meta.h"21#include "meta/meta.h"
22#include "common/log.h"22#include "common/log.h"
@@ -29,7 +29,13 @@ constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_DOMAIN_DEMUXER, "D
29namespace OHOS {29namespace OHOS {
30namespace Media {30namespace Media {
31namespace Plugins {31namespace Plugins {
32-static std::unordered_map<TagType, std::string> g_formatToIndex = {32+namespace {
33+struct FormatTagMapping {
34+ std::string_view tag;
35+ std::string_view name;
36+};
37+ 
38+constexpr std::array<FormatTagMapping, 78> FORMAT_TO_INDEX = {{
33 {Tag::AUDIO_AAC_IS_ADTS, "adts"},39 {Tag::AUDIO_AAC_IS_ADTS, "adts"},
34 {Tag::AUDIO_BITS_PER_CODED_SAMPLE, "bitsPerCodedSmp"},40 {Tag::AUDIO_BITS_PER_CODED_SAMPLE, "bitsPerCodedSmp"},
35 {Tag::AUDIO_BITS_PER_RAW_SAMPLE, "bitsPerRawSmp"},41 {Tag::AUDIO_BITS_PER_RAW_SAMPLE, "bitsPerRawSmp"},
@@ -108,9 +114,9 @@ static std::unordered_map<TagType, std::string> g_formatToIndex = {
108 {Tag::MEDIA_ENCODER, "encoder"},114 {Tag::MEDIA_ENCODER, "encoder"},
109 {Tag::VIDEO_STATIC_METADATA_CTA861, "cta861"},115 {Tag::VIDEO_STATIC_METADATA_CTA861, "cta861"},
110 {Tag::VIDEO_STATIC_METADATA_SMPT2086, "smpt2086"},116 {Tag::VIDEO_STATIC_METADATA_SMPT2086, "smpt2086"},
111-};117+}};
112 118 
113-std::vector<TagType> g_supportSourceFormat = {119+constexpr std::array<std::string_view, 15> SUPPORT_SOURCE_FORMAT = {
114 Tag::MEDIA_TITLE,120 Tag::MEDIA_TITLE,
115 Tag::MEDIA_ARTIST,121 Tag::MEDIA_ARTIST,
116 Tag::MEDIA_ALBUM,122 Tag::MEDIA_ALBUM,
@@ -128,36 +134,56 @@ std::vector<TagType> g_supportSourceFormat = {
128 Tag::MEDIA_AIGC134 Tag::MEDIA_AIGC
129};135};
130 136 
137+std::string_view FindFormatIndex(const std::string& tag)
138+{
139+ for (const auto& mapping : FORMAT_TO_INDEX) {
140+ if (mapping.tag == tag) {
141+ return mapping.name;
142+ }
143+ }
144+ return {};
145+}
146+} // namespace
147+ 
131std::string DemuxerLogCompressor::FormatTagSerialize(Format& format)148std::string DemuxerLogCompressor::FormatTagSerialize(Format& format)
132{149{
133- std::stringstream dumpStr;150+ std::string dumpStr;
134 auto meta = format.GetMeta();151 auto meta = format.GetMeta();
135 FALSE_RETURN_V_MSG_E(meta != nullptr, "", "Meta is nullptr");152 FALSE_RETURN_V_MSG_E(meta != nullptr, "", "Meta is nullptr");
136 for (auto iter = meta->begin(); iter != meta->end(); ++iter) {153 for (auto iter = meta->begin(); iter != meta->end(); ++iter) {
137- if (g_formatToIndex.find(iter->first) == g_formatToIndex.end()) {154+ std::string_view tag = FindFormatIndex(iter->first);
155+ if (tag.empty()) {
138 continue;156 continue;
139 }157 }
158+ const auto appendValue = [&dumpStr, &tag](const std::string& value) {
159+ dumpStr.append(tag.data(), tag.size());
160+ dumpStr.push_back('=');
161+ dumpStr += value;
162+ dumpStr.push_back('|');
163+ };
140 switch (format.GetValueType(iter->first)) {164 switch (format.GetValueType(iter->first)) {
141 case FORMAT_TYPE_INT32:165 case FORMAT_TYPE_INT32:
142- dumpStr << g_formatToIndex[iter->first] << "=" << std::to_string(AnyCast<int32_t>(iter->second)) << "|";166+ appendValue(std::to_string(AnyCast<int32_t>(iter->second)));
143 break;167 break;
144 case FORMAT_TYPE_INT64:168 case FORMAT_TYPE_INT64:
145- dumpStr << g_formatToIndex[iter->first] << "=" << std::to_string(AnyCast<int64_t>(iter->second)) << "|";169+ appendValue(std::to_string(AnyCast<int64_t>(iter->second)));
146 break;170 break;
147 case FORMAT_TYPE_FLOAT:171 case FORMAT_TYPE_FLOAT:
148- dumpStr << g_formatToIndex[iter->first] << "=" << std::to_string(AnyCast<float>(iter->second)) << "|";172+ appendValue(std::to_string(AnyCast<float>(iter->second)));
149 break;173 break;
150 case FORMAT_TYPE_DOUBLE:174 case FORMAT_TYPE_DOUBLE:
151- dumpStr << g_formatToIndex[iter->first] << "=" << std::to_string(AnyCast<double>(iter->second)) << "|";175+ appendValue(std::to_string(AnyCast<double>(iter->second)));
152 break;176 break;
153 case FORMAT_TYPE_STRING:177 case FORMAT_TYPE_STRING:
154- dumpStr << g_formatToIndex[iter->first] << "=" << AnyCast<std::string>(iter->second) << "|";178+ appendValue(AnyCast<std::string>(iter->second));
155 break;179 break;
156 case FORMAT_TYPE_ADDR: {180 case FORMAT_TYPE_ADDR: {
157 Any *value = const_cast<Any *>(&(iter->second));181 Any *value = const_cast<Any *>(&(iter->second));
158 if (AnyCast<std::vector<uint8_t>>(value) != nullptr) {182 if (AnyCast<std::vector<uint8_t>>(value) != nullptr) {
159- dumpStr << g_formatToIndex[iter->first] << ", size="183+ dumpStr.append(tag.data(), tag.size());
160- << (AnyCast<std::vector<uint8_t>>(value))->size() << "|";184+ dumpStr += ", size=";
185+ dumpStr += std::to_string((AnyCast<std::vector<uint8_t>>(value))->size());
186+ dumpStr.push_back('|');
161 }187 }
162 break;188 break;
163 }189 }
@@ -165,15 +191,16 @@ std::string DemuxerLogCompressor::FormatTagSerialize(Format& format)
165 MEDIA_LOG_E("Stringify failed, Key " PUBLIC_LOG_S, iter->first.c_str());191 MEDIA_LOG_E("Stringify failed, Key " PUBLIC_LOG_S, iter->first.c_str());
166 }192 }
167 }193 }
168- return dumpStr.str();194+ return dumpStr;
169}195}
170 196 
171void DemuxerLogCompressor::StringifyMeta(Meta meta, int32_t trackIndex)197void DemuxerLogCompressor::StringifyMeta(Meta meta, int32_t trackIndex)
172{198{
173 OHOS::Media::Format format;199 OHOS::Media::Format format;
174- for (TagType key: g_supportSourceFormat) {200+ for (std::string_view key : SUPPORT_SOURCE_FORMAT) {
175- if (meta.Find(std::string(key)) != meta.end()) {201+ const std::string keyString(key);
176- meta.SetData(std::string(key), "*");202+ if (meta.Find(keyString) != meta.end()) {
203+ meta.SetData(keyString, "*");
177 }204 }
178 }205 }
179 if (meta.Find(std::string(Tag::MEDIA_CONTAINER_START_TIME)) != meta.end()) {206 if (meta.Find(std::string(Tag::MEDIA_CONTAINER_START_TIME)) != meta.end()) {
@@ -212,4 +239,4 @@ void DemuxerLogCompressor::StringifyMeta(Meta meta, int32_t trackIndex)
212}239}
213} // namespace Plugins240} // namespace Plugins
214} // namespace Media241} // namespace Media
215-} // namespace OHOS242+} // namespace OHOS
Mservices/media_engine/plugins/demuxer/mpeg4_demuxer/mpeg4_audio_parser.cpp+29-52
@@ -15,6 +15,7 @@
15 15 
16#define MEDIA_PLUGIN16#define MEDIA_PLUGIN
17#define HST_LOG_TAG "MPEG4AudioParser"17#define HST_LOG_TAG "MPEG4AudioParser"
18+#include <iterator>
18#include "common/log.h"19#include "common/log.h"
19#include "demuxer_data_reader.h"20#include "demuxer_data_reader.h"
20#include "mpeg4_audio_parser.h"21#include "mpeg4_audio_parser.h"
@@ -62,7 +63,7 @@ struct MpegAudioFrameInfo {
62 int32_t channels = 0;63 int32_t channels = 0;
63};64};
64 65 
65-const std::vector<std::pair<int32_t, AudioChannelLayout>> g_channelLayoutDefaultMap = {66+constexpr std::pair<int32_t, AudioChannelLayout> g_channelLayoutDefaultMap[] = {
66 {2, AudioChannelLayout::STEREO}, // 2: STEREO67 {2, AudioChannelLayout::STEREO}, // 2: STEREO
67 {4, AudioChannelLayout::CH_4POINT0}, // 4: CH_4POINT068 {4, AudioChannelLayout::CH_4POINT0}, // 4: CH_4POINT0
68 {6, AudioChannelLayout::CH_5POINT1}, // 6: CH_5POINT169 {6, AudioChannelLayout::CH_5POINT1}, // 6: CH_5POINT1
@@ -75,7 +76,7 @@ const std::vector<std::pair<int32_t, AudioChannelLayout>> g_channelLayoutDefault
75 {24, AudioChannelLayout::CH_22POINT2}, // 24: CH_22POINT276 {24, AudioChannelLayout::CH_22POINT2}, // 24: CH_22POINT2
76};77};
77 78 
78-const std::vector<AudioChannelLayout> g_supportChannelLayout = {79+constexpr AudioChannelLayout g_supportChannelLayout[] = {
79 AudioChannelLayout::UNKNOWN,80 AudioChannelLayout::UNKNOWN,
80 AudioChannelLayout::MONO,81 AudioChannelLayout::MONO,
81 AudioChannelLayout::STEREO,82 AudioChannelLayout::STEREO,
@@ -119,19 +120,6 @@ const std::vector<AudioChannelLayout> g_supportChannelLayout = {
119 AudioChannelLayout::CH_3POINT0POINT2120 AudioChannelLayout::CH_3POINT0POINT2
120};121};
121 122 
122-const std::vector<AudioChannelLayout> g_dtsAudioMode2DtsChannelLayout = {
123- AudioChannelLayout::MONO,
124- AudioChannelLayout::STEREO,
125- AudioChannelLayout::STEREO,
126- AudioChannelLayout::STEREO,
127- AudioChannelLayout::STEREO,
128- AudioChannelLayout::SURROUND,
129- AudioChannelLayout::CH_2_1,
130- AudioChannelLayout::CH_4POINT0,
131- AudioChannelLayout::CH_2_2,
132- AudioChannelLayout::CH_5POINT0,
133-};
134- 
135MpegAudioFrameInfo ParseMpegAudioFrameHeader(const uint8_t* data, uint32_t size)123MpegAudioFrameInfo ParseMpegAudioFrameHeader(const uint8_t* data, uint32_t size)
136{124{
137 MpegAudioFrameInfo info;125 MpegAudioFrameInfo info;
@@ -212,21 +200,11 @@ bool ParseAacRawDataBlockChannels(const uint8_t* data, uint32_t size, int32_t& c
212 return false;200 return false;
213}201}
214 202 
215-MPEG4AudioParser::MPEG4AudioParser()
216-{
217- MEDIA_LOG_D("In");
218-}
219- 
220-MPEG4AudioParser::~MPEG4AudioParser()
221-{
222- MEDIA_LOG_D("In");
223-}
224- 
225AudioChannelLayout MPEG4AudioParser::FindValidChannelLayout(uint64_t layoutMask)203AudioChannelLayout MPEG4AudioParser::FindValidChannelLayout(uint64_t layoutMask)
226{204{
227- auto it = std::find(g_supportChannelLayout.begin(), g_supportChannelLayout.end(),205+ auto it = std::find(std::begin(g_supportChannelLayout), std::end(g_supportChannelLayout),
228 static_cast<AudioChannelLayout>(layoutMask));206 static_cast<AudioChannelLayout>(layoutMask));
229- if (it != g_supportChannelLayout.end()) {207+ if (it != std::end(g_supportChannelLayout)) {
230 return *it;208 return *it;
231 }209 }
232 return AudioChannelLayout::UNKNOWN;210 return AudioChannelLayout::UNKNOWN;
@@ -235,69 +213,68 @@ AudioChannelLayout MPEG4AudioParser::FindValidChannelLayout(uint64_t layoutMask)
235AudioChannelLayout MPEG4AudioParser::GetDefaultChannelLayout(int32_t channels)213AudioChannelLayout MPEG4AudioParser::GetDefaultChannelLayout(int32_t channels)
236{214{
237 AudioChannelLayout layout = AudioChannelLayout::MONO;215 AudioChannelLayout layout = AudioChannelLayout::MONO;
238- auto ite = std::find_if(g_channelLayoutDefaultMap.begin(), g_channelLayoutDefaultMap.end(),216+ auto ite = std::find_if(std::begin(g_channelLayoutDefaultMap), std::end(g_channelLayoutDefaultMap),
239 [&channels](const auto &item) -> bool { return item.first == channels; });217 [&channels](const auto &item) -> bool { return item.first == channels; });
240- if (ite != g_channelLayoutDefaultMap.end()) {218+ if (ite != std::end(g_channelLayoutDefaultMap)) {
241 layout = ite->second;219 layout = ite->second;
242 }220 }
243 return layout;221 return layout;
244}222}
245 223 
246-Status MPEG4AudioParser::ParseAudioFrame(uint8_t* data, uint32_t size, std::string mime, uint32_t trackIndex,224+Status MPEG4AudioParser::ParseAudioFrame(const uint8_t* data, uint32_t size, const std::string& mime,
247- MediaInfo& mediaInfo)225+ uint32_t trackIndex, MediaInfo& mediaInfo)
248{226{
249 MEDIA_LOG_D("In");227 MEDIA_LOG_D("In");
250- audioData_ = data;
251- dataSize_ = size;
252- index_ = trackIndex;
253 auto ret = Status::OK;228 auto ret = Status::OK;
254 if (mime == MimeType::AUDIO_MPEG) {229 if (mime == MimeType::AUDIO_MPEG) {
255- ret = ParseMpegAudio(mediaInfo);230+ ret = ParseMpegAudio(data, size, trackIndex, mediaInfo);
256 } else if (mime == MimeType::AUDIO_AAC) {231 } else if (mime == MimeType::AUDIO_AAC) {
257- ret = ParseAacAudio(mediaInfo);232+ ret = ParseAacAudio(data, size, trackIndex, mediaInfo);
258 }233 }
259 234 
260 return ret;235 return ret;
261}236}
262 237 
263-Status MPEG4AudioParser::ParseMpegAudio(MediaInfo& mediaInfo)238+Status MPEG4AudioParser::ParseMpegAudio(const uint8_t* data, uint32_t size, uint32_t trackIndex,
239+ MediaInfo& mediaInfo)
264{240{
265 MEDIA_LOG_D("In");241 MEDIA_LOG_D("In");
266- MpegAudioFrameInfo frameInfo = ParseMpegAudioFrameHeader(audioData_, dataSize_);242+ MpegAudioFrameInfo frameInfo = ParseMpegAudioFrameHeader(data, size);
267 if (!frameInfo.valid) {243 if (!frameInfo.valid) {
268 MEDIA_LOG_W("Invalid MPEG audio frame header");244 MEDIA_LOG_W("Invalid MPEG audio frame header");
269- mediaInfo.tracks[index_].Set<Tag::AUDIO_SAMPLE_FORMAT>(AudioSampleFormat::SAMPLE_F32P);245+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_SAMPLE_FORMAT>(AudioSampleFormat::SAMPLE_F32P);
270 return Status::OK;246 return Status::OK;
271 }247 }
272 AudioChannelLayout layout = GetDefaultChannelLayout(frameInfo.channels);248 AudioChannelLayout layout = GetDefaultChannelLayout(frameInfo.channels);
273- mediaInfo.tracks[index_].Set<Tag::AUDIO_CHANNEL_COUNT>(frameInfo.channels);249+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_CHANNEL_COUNT>(frameInfo.channels);
274- mediaInfo.tracks[index_].Set<Tag::AUDIO_OUTPUT_CHANNELS>(frameInfo.channels);250+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_OUTPUT_CHANNELS>(frameInfo.channels);
275- mediaInfo.tracks[index_].Set<Tag::AUDIO_CHANNEL_LAYOUT>(layout);251+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_CHANNEL_LAYOUT>(layout);
276- mediaInfo.tracks[index_].Set<Tag::AUDIO_OUTPUT_CHANNEL_LAYOUT>(layout);252+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_OUTPUT_CHANNEL_LAYOUT>(layout);
277 if (frameInfo.samplesPerFrame > 0) {253 if (frameInfo.samplesPerFrame > 0) {
278- mediaInfo.tracks[index_].Set<Tag::AUDIO_SAMPLE_PER_FRAME>(frameInfo.samplesPerFrame);254+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_SAMPLE_PER_FRAME>(frameInfo.samplesPerFrame);
279 }255 }
280- mediaInfo.tracks[index_].Set<Tag::AUDIO_SAMPLE_FORMAT>(frameInfo.sampleFormat);256+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_SAMPLE_FORMAT>(frameInfo.sampleFormat);
281 return Status::OK;257 return Status::OK;
282}258}
283 259 
284-Status MPEG4AudioParser::ParseAacAudio(MediaInfo& mediaInfo)260+Status MPEG4AudioParser::ParseAacAudio(const uint8_t* data, uint32_t size, uint32_t trackIndex,
261+ MediaInfo& mediaInfo)
285{262{
286 MEDIA_LOG_D("In");263 MEDIA_LOG_D("In");
287 int32_t channels = 0;264 int32_t channels = 0;
288 AudioChannelLayout layout = AudioChannelLayout::UNKNOWN;265 AudioChannelLayout layout = AudioChannelLayout::UNKNOWN;
289- if (!ParseAacRawDataBlockChannels(audioData_, dataSize_, channels, layout)) {266+ if (!ParseAacRawDataBlockChannels(data, size, channels, layout)) {
290 return Status::OK;267 return Status::OK;
291 }268 }
292 int32_t parsedChannels = 0;269 int32_t parsedChannels = 0;
293- if (mediaInfo.tracks[index_].Get<Tag::AUDIO_CHANNEL_COUNT>(parsedChannels) && parsedChannels > 0 &&270+ if (mediaInfo.tracks[trackIndex].Get<Tag::AUDIO_CHANNEL_COUNT>(parsedChannels) && parsedChannels > 0 &&
294 channels <= parsedChannels) {271 channels <= parsedChannels) {
295 return Status::OK;272 return Status::OK;
296 }273 }
297- mediaInfo.tracks[index_].Set<Tag::AUDIO_CHANNEL_COUNT>(channels);274+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_CHANNEL_COUNT>(channels);
298- mediaInfo.tracks[index_].Set<Tag::AUDIO_OUTPUT_CHANNELS>(channels);275+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_OUTPUT_CHANNELS>(channels);
299- mediaInfo.tracks[index_].Set<Tag::AUDIO_CHANNEL_LAYOUT>(layout);276+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_CHANNEL_LAYOUT>(layout);
300- mediaInfo.tracks[index_].Set<Tag::AUDIO_OUTPUT_CHANNEL_LAYOUT>(layout);277+ mediaInfo.tracks[trackIndex].Set<Tag::AUDIO_OUTPUT_CHANNEL_LAYOUT>(layout);
301 return Status::OK;278 return Status::OK;
302}279}
303} // namespace MPEG4280} // namespace MPEG4
Mservices/media_engine/plugins/demuxer/mpeg4_demuxer/mpeg4_audio_parser.h+6-10
@@ -24,18 +24,14 @@ namespace Plugins {
24namespace MPEG4 {24namespace MPEG4 {
25class MPEG4AudioParser {25class MPEG4AudioParser {
26public:26public:
27- explicit MPEG4AudioParser();27+ static AudioChannelLayout FindValidChannelLayout(uint64_t layoutMask);
28- ~MPEG4AudioParser();28+ static AudioChannelLayout GetDefaultChannelLayout(int32_t channels);
29- AudioChannelLayout FindValidChannelLayout(uint64_t layoutMask);29+ static Status ParseAudioFrame(const uint8_t* data, uint32_t size, const std::string& mime, uint32_t trackIndex,
30- AudioChannelLayout GetDefaultChannelLayout(int32_t channels);30+ MediaInfo& mediaInfo);
31- Status ParseAudioFrame(uint8_t* data, uint32_t size, std::string mime, uint32_t trackIndex, MediaInfo& mediaInfo);
32 31 
33private:32private:
34- uint8_t* audioData_ = nullptr;33+ static Status ParseMpegAudio(const uint8_t* data, uint32_t size, uint32_t trackIndex, MediaInfo& mediaInfo);
35- uint32_t dataSize_ = 0;34+ static Status ParseAacAudio(const uint8_t* data, uint32_t size, uint32_t trackIndex, MediaInfo& mediaInfo);
36- uint32_t index_ = 0;
37- Status ParseMpegAudio(MediaInfo& mediaInfo);
38- Status ParseAacAudio(MediaInfo& mediaInfo);
39};35};
40} // namespace MPEG436} // namespace MPEG4
41} // namespace Plugins37} // namespace Plugins
Mservices/media_engine/plugins/demuxer/mpeg4_demuxer/mpeg4_box_parser.cpp+329-242
@@ -18,11 +18,8 @@
18#include <algorithm>18#include <algorithm>
19#include <string>19#include <string>
20#include <string_view>20#include <string_view>
21-#include <sstream>
22-#include <iomanip>
23#include <limits>21#include <limits>
24-#include <regex>22+#include <locale>
25-#include <set>
26#include <array>23#include <array>
27#include "avc_parser_impl.h"24#include "avc_parser_impl.h"
28#include "avcodec_trace.h"25#include "avcodec_trace.h"
@@ -180,8 +177,9 @@ constexpr uint32_t MAX_METADATA_KEYS_COUNT = 100000;
180// location info177// location info
181constexpr int32_t PRECISION = 4;178constexpr int32_t PRECISION = 4;
182constexpr int32_t ALTITUDE_PRECISION = 6;179constexpr int32_t ALTITUDE_PRECISION = 6;
183-constexpr int32_t LATITUDE_WIDTH = 8;180+constexpr size_t LATITUDE_WIDTH = 8;
184-constexpr int32_t LONGITUDE_WIDTH = 9;181+constexpr size_t LONGITUDE_WIDTH = 9;
182+constexpr size_t LOCATION_NUMBER_BUFFER_SIZE = 32;
185constexpr uint32_t FULLBOX_PREFIX_SIZE = 4;183constexpr uint32_t FULLBOX_PREFIX_SIZE = 4;
186 184 
187constexpr std::array<size_t, 4> MATRIX_2X2_INDICES = {0, 1, 3, 4}; // [0][0], [0][1], [1][0], [1][1]185constexpr std::array<size_t, 4> MATRIX_2X2_INDICES = {0, 1, 3, 4}; // [0][0], [0][1], [1][0], [1][1]
@@ -198,6 +196,27 @@ constexpr uint8_t OFFSET_7 = 7;
198constexpr uint8_t OFFSET_8 = 8;196constexpr uint8_t OFFSET_8 = 8;
199constexpr uint8_t OFFSET_9 = 9;197constexpr uint8_t OFFSET_9 = 9;
200 198 
199+constexpr uint8_t LATITUDE_OFFSET = 0;
200+constexpr uint8_t LONGITUDE_OFFSET = 1;
201+constexpr uint8_t ALTITUDE_OFFSET = 2;
202+ 
203+namespace {
204+bool AppendFixedFloat(std::string& output, float value, int precision, size_t width)
205+{
206+ char buffer[LOCATION_NUMBER_BUFFER_SIZE] = {};
207+ int written = snprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, "%+.*f",
208+ precision, static_cast<double>(value));
209+ FALSE_RETURN_V_NOLOG(written > 0, false);
210+ size_t writtenSize = static_cast<size_t>(written);
211+ FALSE_RETURN_V_NOLOG(writtenSize < sizeof(buffer), false);
212+ if (width > writtenSize) {
213+ output.append(width - writtenSize, '0');
214+ }
215+ output.append(buffer, writtenSize);
216+ return true;
217+}
218+} // namespace
219+ 
201void SetTrackMediaType(Meta &format, TrackType trackType)220void SetTrackMediaType(Meta &format, TrackType trackType)
202{221{
203 MediaType mediaType = GetMediaType(trackType);222 MediaType mediaType = GetMediaType(trackType);
@@ -272,7 +291,13 @@ int64_t GetMaxSampleDtsEnd(const std::shared_ptr<MPEG4SampleHelper>& sampleHelpe
272}291}
273// LCOV_EXCL_STOP292// LCOV_EXCL_STOP
274 293 
275-static const std::map<std::string, VideoOrientationType> matrixTypes = {294+struct MatrixTypeMapping {
295+ std::array<int32_t, MATRIX_SIZE> matrix;
296+ VideoOrientationType orientation;
297+};
298+ 
299+namespace {
300+constexpr std::array<MatrixTypeMapping, 7> MATRIX_TYPES = {{
276 /**301 /**
277 * display matrix302 * display matrix
278 * | a b u |303 * | a b u |
@@ -280,14 +305,15 @@ static const std::map<std::string, VideoOrientationType> matrixTypes = {
280 * | x y w |305 * | x y w |
281 * [a b c d] can confirm the orientation type306 * [a b c d] can confirm the orientation type
282 */307 */
283- {"0 -1 1 0", VideoOrientationType::ROTATE_90},308+ {{{0, -1, 1, 0}}, VideoOrientationType::ROTATE_90},
284- {"-1 0 0 -1", VideoOrientationType::ROTATE_180},309+ {{{-1, 0, 0, -1}}, VideoOrientationType::ROTATE_180},
285- {"0 1 -1 0", VideoOrientationType::ROTATE_270},310+ {{{0, 1, -1, 0}}, VideoOrientationType::ROTATE_270},
286- {"-1 0 0 1", VideoOrientationType::FLIP_H},311+ {{{-1, 0, 0, 1}}, VideoOrientationType::FLIP_H},
287- {"1 0 0 -1", VideoOrientationType::FLIP_V},312+ {{{1, 0, 0, -1}}, VideoOrientationType::FLIP_V},
288- {"0 1 1 0", VideoOrientationType::FLIP_H_ROT90},313+ {{{0, 1, 1, 0}}, VideoOrientationType::FLIP_H_ROT90},
289- {"0 -1 -1 0", VideoOrientationType::FLIP_V_ROT90},314+ {{{0, -1, -1, 0}}, VideoOrientationType::FLIP_V_ROT90},
290-};315+}};
316+} // namespace
291 317 
292static const AudioChannelLayout AAC_CHANNEL_LAYOUT_TABLE[14] = {318static const AudioChannelLayout AAC_CHANNEL_LAYOUT_TABLE[14] = {
293 AudioChannelLayout::UNKNOWN,319 AudioChannelLayout::UNKNOWN,
@@ -415,7 +441,6 @@ MPEG4AtomParser::MPEG4AtomParser()
415 userFormat_(std::make_shared<Meta>())441 userFormat_(std::make_shared<Meta>())
416{442{
417 MEDIA_LOG_D("In");443 MEDIA_LOG_D("In");
418- InitParseTable();
419 MEDIA_LOG_D("Out");444 MEDIA_LOG_D("Out");
420}445}
421 446 
@@ -426,7 +451,6 @@ MPEG4AtomParser::~MPEG4AtomParser()
426 lastTrack_.reset();451 lastTrack_.reset();
427 dataSource_.reset();452 dataSource_.reset();
428 dataReader_.reset();453 dataReader_.reset();
429- MPEG4ParseTable_.clear();
430 MEDIA_LOG_D("Out");454 MEDIA_LOG_D("Out");
431}455}
432 456 
@@ -597,34 +621,26 @@ Status MPEG4AtomParser::ParseDisplayMatrix(const uint8_t* data, int32_t matrix[3
597 return Status::OK;621 return Status::OK;
598}622}
599 623 
600-std::string ConvertArrayToString(const int32_t* array, size_t size)624+namespace {
625+VideoOrientationType GetMatrixType(const std::array<int32_t, MATRIX_SIZE>& value)
601{626{
602- std::string result;627+ for (const auto& mapping : MATRIX_TYPES) {
603- for (size_t i = 0; i < size; ++i) {628+ if (mapping.matrix == value) {
604- if (i > 0) {629+ return mapping.orientation;
605- result += ' ';
606 }630 }
607- result += std::to_string(array[i]);
608 }631 }
609- return result;632+ return VideoOrientationType::ROTATE_NONE;
610}633}
634+} // namespace
611 635 
612-VideoOrientationType GetMatrixType(const std::string& value)636+void MPEG4AtomParser::ParseOrientationFromMatrix(const std::shared_ptr<Track>& track)
613-{
614- auto it = matrixTypes.find(value);
615- return (it != matrixTypes.end()) ? it->second : VideoOrientationType::ROTATE_NONE;
616-}
617- 
618-void MPEG4AtomParser::ParseOrientationFromMatrix(std::shared_ptr<Track> track)
619{637{
620 VideoOrientationType orientationType = VideoOrientationType::ROTATE_NONE;638 VideoOrientationType orientationType = VideoOrientationType::ROTATE_NONE;
621 if (track && track->hasDisplayMatrix && track->displayMatrix) {639 if (track && track->hasDisplayMatrix && track->displayMatrix) {
622 PrintMatrixToLog(track->displayMatrix.get(), "displayMatrix");640 PrintMatrixToLog(track->displayMatrix.get(), "displayMatrix");
623 // 转换矩阵:提取前2x2部分并转换为整数641 // 转换矩阵:提取前2x2部分并转换为整数
624 auto convertedMatrix = Extract2x2Transform(track->displayMatrix.get());642 auto convertedMatrix = Extract2x2Transform(track->displayMatrix.get());
625- // 转换为字符串并查找方向类型643+ orientationType = GetMatrixType(convertedMatrix);
626- std::string matrixStr = ConvertArrayToString(convertedMatrix.data(), convertedMatrix.size());
627- orientationType = GetMatrixType(matrixStr);
628 } else {644 } else {
629 MEDIA_LOG_W("Parse orientation info from display matrix failed, set orientation as default 0");645 MEDIA_LOG_W("Parse orientation info from display matrix failed, set orientation as default 0");
630 }646 }
@@ -653,7 +669,7 @@ double CalculateDisplayRotation(const int32_t matrix[9])
653 return rotation;669 return rotation;
654}670}
655 671 
656-void MPEG4AtomParser::ParseRotationTypeFromMatrix(std::shared_ptr<Track> track)672+void MPEG4AtomParser::ParseRotationTypeFromMatrix(const std::shared_ptr<Track>& track)
657{673{
658 VideoRotation rotationType = VIDEO_ROTATION_0;674 VideoRotation rotationType = VIDEO_ROTATION_0;
659 constexpr int32_t VIDEO_ROTATION_360 = 360;675 constexpr int32_t VIDEO_ROTATION_360 = 360;
@@ -802,8 +818,10 @@ Status MPEG4AtomParser::ParseFtyp(MPEG4Atom currentAtom, int32_t depth, ParseCon
802 "Invalid ftypInfo pos number");818 "Invalid ftypInfo pos number");
803 // 解析和存储所有brands, 跳过 minor version,从第8字节开始819 // 解析和存储所有brands, 跳过 minor version,从第8字节开始
804 uint32_t compatibleBrand = GetU32Value(&ftypInfo[pos]);820 uint32_t compatibleBrand = GetU32Value(&ftypInfo[pos]);
805- std::string brandStr = FourccToString(compatibleBrand);821+ ctx->hasQtCompatibleBrand = ctx->hasQtCompatibleBrand ||
806- ctx->compatibleBrands.insert(compatibleBrand);822+ compatibleBrand == static_cast<uint32_t>(FourccType("qt "));
823+ ctx->hasGltfCompatibleBrand = ctx->hasGltfCompatibleBrand ||
824+ compatibleBrand == static_cast<uint32_t>(FourccType("glti"));
807 hasGltfBrand = hasGltfBrand || compatibleBrand == static_cast<uint32_t>(FourccType("glti"));825 hasGltfBrand = hasGltfBrand || compatibleBrand == static_cast<uint32_t>(FourccType("glti"));
808 }826 }
809 }827 }
@@ -979,7 +997,7 @@ Status MPEG4AtomParser::ParseMvhd(MPEG4Atom currentAtom, int32_t depth, ParseCon
979 return ParseMvhdDisplayMatrix(currentAtom, headerInfo.get(), ctx, currentAtom.dataSize);997 return ParseMvhdDisplayMatrix(currentAtom, headerInfo.get(), ctx, currentAtom.dataSize);
980}998}
981 999 
982-int64_t MPEG4AtomParser::GetElstDuration(std::shared_ptr<Track> track)1000+int64_t MPEG4AtomParser::GetElstDuration(const std::shared_ptr<Track>& track)
983{1001{
984 int32_t fileTimescale = movieTimeScale_;1002 int32_t fileTimescale = movieTimeScale_;
985 FALSE_RETURN_V_MSG_E(fileTimescale > 0, 0, "Invalid file time scale");1003 FALSE_RETURN_V_MSG_E(fileTimescale > 0, 0, "Invalid file time scale");
@@ -997,7 +1015,7 @@ int64_t MPEG4AtomParser::GetElstDuration(std::shared_ptr<Track> track)
997 return elstDuration;1015 return elstDuration;
998}1016}
999 1017 
1000-int64_t MPEG4AtomParser::GetTrackDuration(std::shared_ptr<Track> track, bool calculateBitrate)1018+int64_t MPEG4AtomParser::GetTrackDuration(const std::shared_ptr<Track>& track, bool calculateBitrate)
1001{1019{
1002 FALSE_RETURN_V_MSG_E(track && track->sampleHelper && IsValidTrackIndex(mediaInfo_, track->trackIndex), 0,1020 FALSE_RETURN_V_MSG_E(track && track->sampleHelper && IsValidTrackIndex(mediaInfo_, track->trackIndex), 0,
1003 "Invalid track for duration calculation");1021 "Invalid track for duration calculation");
@@ -1056,7 +1074,7 @@ int64_t GetEffectiveSampleCount(const std::shared_ptr<MPEG4SampleHelper>& sample
1056 return rawSampleCount > 0 ? rawSampleCount : static_cast<int64_t>(sampleHelper->GetSampleCount());1074 return rawSampleCount > 0 ? rawSampleCount : static_cast<int64_t>(sampleHelper->GetSampleCount());
1057}1075}
1058 1076 
1059-void MPEG4AtomParser::CalculateTrackBitrates(std::shared_ptr<Track> track)1077+void MPEG4AtomParser::CalculateTrackBitrates(const std::shared_ptr<Track>& track)
1060{1078{
1061 FALSE_RETURN_MSG(track != nullptr && track->sampleHelper != nullptr, "Invalid track or sample helper");1079 FALSE_RETURN_MSG(track != nullptr && track->sampleHelper != nullptr, "Invalid track or sample helper");
1062 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");1080 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");
@@ -1143,7 +1161,8 @@ int64_t MPEG4AtomParser::GetBitrateTotalSize(const std::shared_ptr<Track>& track
1143 return totalSize;1161 return totalSize;
1144}1162}
1145 1163 
1146-bool MPEG4AtomParser::GetBitrateDurationAndSize(std::shared_ptr<Track> track, int64_t& duration, int64_t& totalSize)1164+bool MPEG4AtomParser::GetBitrateDurationAndSize(
1165+ const std::shared_ptr<Track>& track, int64_t& duration, int64_t& totalSize)
1147{1166{
1148 FALSE_RETURN_V_MSG_E(track != nullptr && track->sampleHelper != nullptr, false, "Invalid track or sample helper");1167 FALSE_RETURN_V_MSG_E(track != nullptr && track->sampleHelper != nullptr, false, "Invalid track or sample helper");
1149 FALSE_RETURN_V_MSG_E(IsValidTrackIndex(mediaInfo_, track->trackIndex), false, "Invalid track index");1168 FALSE_RETURN_V_MSG_E(IsValidTrackIndex(mediaInfo_, track->trackIndex), false, "Invalid track index");
@@ -1162,7 +1181,7 @@ bool MPEG4AtomParser::GetBitrateDurationAndSize(std::shared_ptr<Track> track, in
1162 return true;1181 return true;
1163}1182}
1164 1183 
1165-void MPEG4AtomParser::CalculateVideoFrameRate(std::shared_ptr<Track> track)1184+void MPEG4AtomParser::CalculateVideoFrameRate(const std::shared_ptr<Track>& track)
1166{1185{
1167 FALSE_RETURN_MSG(track != nullptr && track->sampleHelper != nullptr, "Invalid track or sample helper");1186 FALSE_RETURN_MSG(track != nullptr && track->sampleHelper != nullptr, "Invalid track or sample helper");
1168 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");1187 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");
@@ -1195,7 +1214,7 @@ void MPEG4AtomParser::CalculateVideoFrameRate(std::shared_ptr<Track> track)
1195 }1214 }
1196}1215}
1197 1216 
1198-void MPEG4AtomParser::CalculateVideoDelay(std::shared_ptr<Track> track)1217+void MPEG4AtomParser::CalculateVideoDelay(const std::shared_ptr<Track>& track)
1199{1218{
1200 FALSE_RETURN_MSG(track != nullptr && track->sampleHelper != nullptr, "Invalid track or sample helper");1219 FALSE_RETURN_MSG(track != nullptr && track->sampleHelper != nullptr, "Invalid track or sample helper");
1201 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");1220 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");
@@ -1241,7 +1260,7 @@ AudioChannelLayout MPEG4AtomParser::GetAv3aChannelLayout(int32_t channelCount, i
1241}1260}
1242// LCOV_EXCL_STOP1261// LCOV_EXCL_STOP
1243 1262 
1244-void MPEG4AtomParser::NormalizeAudioAttributes(std::shared_ptr<Track> track)1263+void MPEG4AtomParser::NormalizeAudioAttributes(const std::shared_ptr<Track>& track)
1245{1264{
1246 FALSE_RETURN_MSG(track != nullptr, "Invalid track");1265 FALSE_RETURN_MSG(track != nullptr, "Invalid track");
1247 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");1266 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");
@@ -1284,7 +1303,7 @@ void MPEG4AtomParser::NormalizeAudioAttributes(std::shared_ptr<Track> track)
1284 }1303 }
1285}1304}
1286 1305 
1287-void MPEG4AtomParser::ParseImageTrackData(std::shared_ptr<Track> track)1306+void MPEG4AtomParser::ParseImageTrackData(const std::shared_ptr<Track>& track)
1288{1307{
1289 FALSE_RETURN_MSG(track != nullptr && track->sampleHelper != nullptr, "Invalid track");1308 FALSE_RETURN_MSG(track != nullptr && track->sampleHelper != nullptr, "Invalid track");
1290 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");1309 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");
@@ -1316,8 +1335,7 @@ void MPEG4AtomParser::ParseImageTrackData(std::shared_ptr<Track> track)
1316 mediaInfo_.tracks[track->trackIndex].Set<Tag::VIDEO_WIDTH>(videoWidth);1335 mediaInfo_.tracks[track->trackIndex].Set<Tag::VIDEO_WIDTH>(videoWidth);
1317 mediaInfo_.tracks[track->trackIndex].Set<Tag::VIDEO_HEIGHT>(videoHeight);1336 mediaInfo_.tracks[track->trackIndex].Set<Tag::VIDEO_HEIGHT>(videoHeight);
1318 1337 
1319- std::vector<uint8_t> cover(firstEntry.size);1338+ std::vector<uint8_t> cover(coverData.get(), coverData.get() + firstEntry.size);
1320- cover.assign(coverData.get(), coverData.get() + firstEntry.size);
1321 mediaInfo_.tracks[track->trackIndex].Set<Tag::MEDIA_COVER>(std::move(cover));1339 mediaInfo_.tracks[track->trackIndex].Set<Tag::MEDIA_COVER>(std::move(cover));
1322 MEDIA_LOG_D("Image track " PUBLIC_LOG_U32 " cover data size " PUBLIC_LOG_D32,1340 MEDIA_LOG_D("Image track " PUBLIC_LOG_U32 " cover data size " PUBLIC_LOG_D32,
1323 track->trackIndex, firstEntry.size);1341 track->trackIndex, firstEntry.size);
@@ -1372,12 +1390,12 @@ Status ConvertTrackTimeToUs(int64_t trackTime, int64_t trackTimeScale, int64_t*
1372 return Status::OK;1390 return Status::OK;
1373}1391}
1374 1392 
1375-void MPEG4AtomParser::SetCodecConfig(std::shared_ptr<Track> track)1393+void MPEG4AtomParser::SetCodecConfig(const std::shared_ptr<Track>& track)
1376{1394{
1377 FALSE_RETURN_MSG(track != nullptr, "track is null");1395 FALSE_RETURN_MSG(track != nullptr, "track is null");
1378 if (track->codecParms.extradataSize > 0 && track->codecParms.data != nullptr) {1396 if (track->codecParms.extradataSize > 0 && track->codecParms.data != nullptr) {
1379- std::vector<uint8_t> extra(track->codecParms.extradataSize);1397+ std::vector<uint8_t> extra(track->codecParms.data.get(),
1380- extra.assign(track->codecParms.data.get(), track->codecParms.data.get() + track->codecParms.extradataSize);1398+ track->codecParms.data.get() + track->codecParms.extradataSize);
1381 mediaInfo_.tracks[track->trackIndex].Set<Tag::MEDIA_CODEC_CONFIG>(extra);1399 mediaInfo_.tracks[track->trackIndex].Set<Tag::MEDIA_CODEC_CONFIG>(extra);
1382 } else {1400 } else {
1383 MEDIA_LOG_E("Set codec config failed");1401 MEDIA_LOG_E("Set codec config failed");
@@ -1467,7 +1485,7 @@ Status MPEG4AtomParser::ParseTrak(MPEG4Atom currentAtom, int32_t depth, ParseCon
1467 return Status::OK;1485 return Status::OK;
1468}1486}
1469 1487 
1470-void MPEG4AtomParser::AdapterFormat(std::shared_ptr<Track> track)1488+void MPEG4AtomParser::AdapterFormat(const std::shared_ptr<Track>& track)
1471{1489{
1472 if (!NeedParseMediaTrackInfo(track->codecParms.trackType)) {1490 if (!NeedParseMediaTrackInfo(track->codecParms.trackType)) {
1473 mediaInfo_.tracks[track->trackIndex].Remove(Tag::MEDIA_LANGUAGE);1491 mediaInfo_.tracks[track->trackIndex].Remove(Tag::MEDIA_LANGUAGE);
@@ -1492,7 +1510,8 @@ void MPEG4AtomParser::AdapterFormat(std::shared_ptr<Track> track)
1492 mediaInfo_.tracks[track->trackIndex].Remove(Tag::TIMED_METADATA_SRC_TRACK);1510 mediaInfo_.tracks[track->trackIndex].Remove(Tag::TIMED_METADATA_SRC_TRACK);
1493 }1511 }
1494}1512}
1495-void MPEG4AtomParser::CalculateSampleAspectRatio(std::shared_ptr<Track> track, uint32_t width, uint32_t height)1513+void MPEG4AtomParser::CalculateSampleAspectRatio(
1514+ const std::shared_ptr<Track>& track, uint32_t width, uint32_t height)
1496{1515{
1497 FALSE_RETURN_MSG(track != nullptr, "CalculateSampleAspectRatio: track is null");1516 FALSE_RETURN_MSG(track != nullptr, "CalculateSampleAspectRatio: track is null");
1498 FALSE_RETURN_MSG(track->hasDisplayMatrix && track->displayMatrix != nullptr, "Track has no valid display matrix");1517 FALSE_RETURN_MSG(track->hasDisplayMatrix && track->displayMatrix != nullptr, "Track has no valid display matrix");
@@ -1521,7 +1540,7 @@ void MPEG4AtomParser::CalculateSampleAspectRatio(std::shared_ptr<Track> track, u
1521 }1540 }
1522}1541}
1523 1542 
1524-void MPEG4AtomParser::CalculateSARFromTrackInfo(std::shared_ptr<Track> track)1543+void MPEG4AtomParser::CalculateSARFromTrackInfo(const std::shared_ptr<Track>& track)
1525{1544{
1526 FALSE_RETURN_MSG(track != nullptr, "CalculateSARFromTrackInfo: track is null");1545 FALSE_RETURN_MSG(track != nullptr, "CalculateSARFromTrackInfo: track is null");
1527 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");1546 FALSE_RETURN_MSG(IsValidTrackIndex(mediaInfo_, track->trackIndex), "Invalid track index");
@@ -1560,7 +1579,7 @@ void MPEG4AtomParser::CalculateSARFromTrackInfo(std::shared_ptr<Track> track)
1560 MEDIA_LOG_D("Track %{public}u SAR: no pasp and no width/height diff, skip", track->trackIndex);1579 MEDIA_LOG_D("Track %{public}u SAR: no pasp and no width/height diff, skip", track->trackIndex);
1561}1580}
1562 1581 
1563-void MPEG4AtomParser::SetTrackDisplayMatrix(std::shared_ptr<Track> track, const int32_t resultMatrix[3][3],1582+void MPEG4AtomParser::SetTrackDisplayMatrix(const std::shared_ptr<Track>& track, const int32_t resultMatrix[3][3],
1564 uint32_t width, uint32_t height, const size_t len)1583 uint32_t width, uint32_t height, const size_t len)
1565{1584{
1566 if (!IsDisplayMatrixIdentity(resultMatrix, len)) {1585 if (!IsDisplayMatrixIdentity(resultMatrix, len)) {
@@ -1594,8 +1613,8 @@ Status MPEG4AtomParser::ParseTkhd(MPEG4Atom currentAtom, int32_t depth, ParseCon
1594 * layer(2) + alternate_group(2) + volume(2) + reserved(2) + matrix(36) + width(4) + height(4)1613 * layer(2) + alternate_group(2) + volume(2) + reserved(2) + matrix(36) + width(4) + height(4)
1595 */1614 */
1596 constexpr uint32_t infoSize = 96;1615 constexpr uint32_t infoSize = 96;
1597- auto headerInfo = std::make_unique<uint8_t[]>(infoSize);1616+ std::array<uint8_t, infoSize> headerInfo = {};
1598- Status ret = dataReader_->ReadUintData(ctx->dataOffset, headerInfo.get(), infoSize);1617+ Status ret = dataReader_->ReadUintData(ctx->dataOffset, headerInfo.data(), infoSize);
1599 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "Read tkhd header info failed");1618 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "Read tkhd header info failed");
1600 uint8_t version = headerInfo[0];1619 uint8_t version = headerInfo[0];
1601 1620 
@@ -1784,16 +1803,16 @@ Status MPEG4AtomParser::ParseTref(MPEG4Atom currentAtom, int32_t depth, ParseCon
1784 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "Read tref atom id data failed");1803 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "Read tref atom id data failed");
1785 1804 
1786 std::vector<int32_t> referencedTrackIds;1805 std::vector<int32_t> referencedTrackIds;
1787- std::ostringstream referencedIdsStr;1806+ std::string referencedIdsStr;
1788 for (uint32_t i = 0; i < idCount; ++i) {1807 for (uint32_t i = 0; i < idCount; ++i) {
1789 int32_t trackId = static_cast<int32_t>(GetU32Value(&idData[i * sizeof(uint32_t)]));1808 int32_t trackId = static_cast<int32_t>(GetU32Value(&idData[i * sizeof(uint32_t)]));
1790 if (trackId > 0) {1809 if (trackId > 0) {
1791 int32_t adjustedTrackId = trackId - 1;1810 int32_t adjustedTrackId = trackId - 1;
1792 referencedTrackIds.emplace_back(adjustedTrackId);1811 referencedTrackIds.emplace_back(adjustedTrackId);
1793- if (!referencedTrackIds.empty() && referencedTrackIds.size() > 1) {1812+ if (referencedTrackIds.size() > 1) {
1794- referencedIdsStr << ",";1813+ referencedIdsStr.push_back(',');
1795 }1814 }
1796- referencedIdsStr << adjustedTrackId;1815+ referencedIdsStr += std::to_string(adjustedTrackId);
1797 }1816 }
1798 }1817 }
1799 1818 
@@ -1803,7 +1822,7 @@ Status MPEG4AtomParser::ParseTref(MPEG4Atom currentAtom, int32_t depth, ParseCon
1803 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::TIMED_METADATA_SRC_TRACK>(referencedTrackId);1822 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::TIMED_METADATA_SRC_TRACK>(referencedTrackId);
1804 }1823 }
1805 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::REFERENCE_TRACK_IDS>(referencedTrackIds);1824 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::REFERENCE_TRACK_IDS>(referencedTrackIds);
1806- MEDIA_LOG_D("ParseTref Referenced track IDs: " PUBLIC_LOG_S, referencedIdsStr.str().c_str());1825+ MEDIA_LOG_D("ParseTref Referenced track IDs: " PUBLIC_LOG_S, referencedIdsStr.c_str());
1807 }1826 }
1808 1827 
1809 ctx->offset += static_cast<int64_t>(currentAtom.size);1828 ctx->offset += static_cast<int64_t>(currentAtom.size);
@@ -2347,7 +2366,7 @@ Status MPEG4AtomParser::ParseAudioVersionInfo(MPEG4Atom currentAtom, AudioVersio
2347{2366{
2348 FALSE_RETURN_V_MSG_E(IsLastTrackValid(), Status::ERROR_INVALID_DATA, "Invalid current track");2367 FALSE_RETURN_V_MSG_E(IsLastTrackValid(), Status::ERROR_INVALID_DATA, "Invalid current track");
2349 ParseContext* ctx = context.ctx;2368 ParseContext* ctx = context.ctx;
2350- if (isIsom_ && (ctx->compatibleBrands.count(FourccType("qt "))) == 0 && context.version == 0) {2369+ if (isIsom_ && !ctx->hasQtCompatibleBrand && context.version == 0) {
2351 return Status::OK;2370 return Status::OK;
2352 }2371 }
2353 constexpr int32_t versionOneSkipSize = 16;2372 constexpr int32_t versionOneSkipSize = 16;
@@ -2355,8 +2374,8 @@ Status MPEG4AtomParser::ParseAudioVersionInfo(MPEG4Atom currentAtom, AudioVersio
2355 constexpr uint16_t sampleSizeOffset = 20;2374 constexpr uint16_t sampleSizeOffset = 20;
2356 constexpr uint16_t versionTwo = 2;2375 constexpr uint16_t versionTwo = 2;
2357 size_t entryInfoSize = (context.version == 1) ? versionOneSkipSize : versionTwoSkipSize;2376 size_t entryInfoSize = (context.version == 1) ? versionOneSkipSize : versionTwoSkipSize;
2358- auto entryInfo = std::make_unique<uint8_t[]>(entryInfoSize);2377+ std::array<uint8_t, versionTwoSkipSize> entryInfo = {};
2359- Status ret = dataReader_->ReadUintData(ctx->offset, entryInfo.get(), entryInfoSize);2378+ Status ret = dataReader_->ReadUintData(ctx->offset, entryInfo.data(), entryInfoSize);
2360 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "Read entry info failed");2379 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "Read entry info failed");
2361 if (context.version == 1) {2380 if (context.version == 1) {
2362 context.samplePerFrame = GetU32Value(&entryInfo[0]);2381 context.samplePerFrame = GetU32Value(&entryInfo[0]);
@@ -2600,18 +2619,17 @@ Status MPEG4AtomParser::ParseDecoderConfigDescriptor(const uint8_t* data, uint64
2600 return Status::OK;2619 return Status::OK;
2601}2620}
2602 2621 
2603-void GetAACConfigExtInfo(const std::shared_ptr<DemuxerBitReader> bitReader, uint8_t& audioObjectType)2622+void GetAACConfigExtInfo(DemuxerBitReader& bitReader, uint8_t& audioObjectType)
2604{2623{
2605- bitReader->SkipBits(0x04);2624+ bitReader.SkipBits(0x04);
2606- audioObjectType = bitReader->ReadBits(0x05);2625+ audioObjectType = bitReader.ReadBits(0x05);
2607 if (audioObjectType == 0x1F) {2626 if (audioObjectType == 0x1F) {
2608- audioObjectType = 0x20 + bitReader->ReadBits(0x06);2627+ audioObjectType = 0x20 + bitReader.ReadBits(0x06);
2609 }2628 }
2610}2629}
2611 2630 
2612// LCOV_EXCL_START2631// LCOV_EXCL_START
2613-bool DecodeChannelMap(uint8_t layoutMap[][3], uint8_t channelType, const std::shared_ptr<DemuxerBitReader> bitReader,2632+bool DecodeChannelMap(uint8_t layoutMap[][3], uint8_t channelType, DemuxerBitReader& bitReader, uint8_t num)
2614- uint8_t num)
2615{2633{
2616 uint8_t element;2634 uint8_t element;
2617 while (num--) {2635 while (num--) {
@@ -2619,7 +2637,7 @@ bool DecodeChannelMap(uint8_t layoutMap[][3], uint8_t channelType, const std::sh
2619 case 0x01:2637 case 0x01:
2620 case 0x02:2638 case 0x02:
2621 case 0x03: {2639 case 0x03: {
2622- element = bitReader->ReadBits(1);2640+ element = bitReader.ReadBits(1);
2623 break;2641 break;
2624 }2642 }
2625 case 0x04: {2643 case 0x04: {
@@ -2627,7 +2645,7 @@ bool DecodeChannelMap(uint8_t layoutMap[][3], uint8_t channelType, const std::sh
2627 break;2645 break;
2628 }2646 }
2629 case 0x05: {2647 case 0x05: {
2630- bitReader->SkipBits(1);2648+ bitReader.SkipBits(1);
2631 element = TYPE_CCE;2649 element = TYPE_CCE;
2632 break;2650 break;
2633 }2651 }
@@ -2635,7 +2653,7 @@ bool DecodeChannelMap(uint8_t layoutMap[][3], uint8_t channelType, const std::sh
2635 return false;2653 return false;
2636 }2654 }
2637 layoutMap[0][0] = element;2655 layoutMap[0][0] = element;
2638- layoutMap[0][1] = bitReader->ReadBits(0x04);2656+ layoutMap[0][1] = bitReader.ReadBits(0x04);
2639 layoutMap[0][0x02] = channelType;2657 layoutMap[0][0x02] = channelType;
2640 ++layoutMap;2658 ++layoutMap;
2641 }2659 }
@@ -2653,34 +2671,33 @@ uint8_t CountChannels(uint8_t (*layoutMap)[3], uint8_t tags)
2653 return sum;2671 return sum;
2654}2672}
2655 2673 
2656-bool ParseGeneralAACConfig(const std::shared_ptr<DemuxerBitReader> bitReader, uint8_t audioObjectType,2674+bool ParseGeneralAACConfig(DemuxerBitReader& bitReader, uint8_t audioObjectType, uint32_t& channels)
2657- uint32_t& channels)
2658{2675{
2659 uint8_t layoutMap[64][3];2676 uint8_t layoutMap[64][3];
2660- FALSE_RETURN_V(bitReader->HasBits(0x1A), false);2677+ FALSE_RETURN_V(bitReader.HasBits(0x1A), false);
2661- uint32_t flag = bitReader->ReadBits(1);2678+ uint32_t flag = bitReader.ReadBits(1);
2662 if (flag) {2679 if (flag) {
2663- bitReader->SkipBits(0x19);2680+ bitReader.SkipBits(0x19);
2664 } else {2681 } else {
2665- bitReader->SkipBits(0x0B);2682+ bitReader.SkipBits(0x0B);
2666 }2683 }
2667- FALSE_RETURN_V(bitReader->HasBits(0x23), false);2684+ FALSE_RETURN_V(bitReader.HasBits(0x23), false);
2668- uint8_t numFront = bitReader->ReadBits(0x04);2685+ uint8_t numFront = bitReader.ReadBits(0x04);
2669- uint8_t numSide = bitReader->ReadBits(0x04);2686+ uint8_t numSide = bitReader.ReadBits(0x04);
2670- uint8_t numBack = bitReader->ReadBits(0x04);2687+ uint8_t numBack = bitReader.ReadBits(0x04);
2671- uint8_t numLfe = bitReader->ReadBits(0x02);2688+ uint8_t numLfe = bitReader.ReadBits(0x02);
2672- uint8_t numAssociateData = bitReader->ReadBits(0x03);2689+ uint8_t numAssociateData = bitReader.ReadBits(0x03);
2673- uint8_t numCc = bitReader->ReadBits(0x04);2690+ uint8_t numCc = bitReader.ReadBits(0x04);
2674- if (bitReader->ReadBits(1)) {2691+ if (bitReader.ReadBits(1)) {
2675- bitReader->ReadBits(0x04);2692+ bitReader.ReadBits(0x04);
2676 }2693 }
2677- if (bitReader->ReadBits(1)) {2694+ if (bitReader.ReadBits(1)) {
2678- bitReader->ReadBits(0x04);2695+ bitReader.ReadBits(0x04);
2679 }2696 }
2680- if (bitReader->ReadBits(1)) {2697+ if (bitReader.ReadBits(1)) {
2681- bitReader->ReadBits(0x03);2698+ bitReader.ReadBits(0x03);
2682 }2699 }
2683- if (!(bitReader->HasBits(0x05 * (numFront + numSide + numBack + numCc) +2700+ if (!(bitReader.HasBits(0x05 * (numFront + numSide + numBack + numCc) +
2684 0x04 * (numLfe + numAssociateData + numCc)))) {2701 0x04 * (numLfe + numAssociateData + numCc)))) {
2685 return false;2702 return false;
2686 }2703 }
@@ -2693,7 +2710,7 @@ bool ParseGeneralAACConfig(const std::shared_ptr<DemuxerBitReader> bitReader, ui
2693 tags += numBack;2710 tags += numBack;
2694 FALSE_RETURN_V(DecodeChannelMap(layoutMap + tags, 0x04, bitReader, numLfe), false);2711 FALSE_RETURN_V(DecodeChannelMap(layoutMap + tags, 0x04, bitReader, numLfe), false);
2695 tags += numLfe;2712 tags += numLfe;
2696- bitReader->SkipBits(0x04 * numAssociateData);2713+ bitReader.SkipBits(0x04 * numAssociateData);
2697 FALSE_RETURN_V(DecodeChannelMap(layoutMap + tags, 0x05, bitReader, numCc), false);2714 FALSE_RETURN_V(DecodeChannelMap(layoutMap + tags, 0x05, bitReader, numCc), false);
2698 tags += numCc;2715 tags += numCc;
2699 2716 
@@ -2718,7 +2735,7 @@ bool CheckAACType(uint8_t audioObjectType)
2718 }2735 }
2719}2736}
2720 2737 
2721-bool GetAACLayoutConfig(uint8_t audioObjectType, const std::shared_ptr<DemuxerBitReader> bitReader, uint32_t size,2738+bool GetAACLayoutConfig(uint8_t audioObjectType, DemuxerBitReader& bitReader, uint32_t size,
2722 uint32_t& channels, AudioChannelLayout &layout)2739 uint32_t& channels, AudioChannelLayout &layout)
2723{2740{
2724 switch (audioObjectType) {2741 switch (audioObjectType) {
@@ -2744,24 +2761,25 @@ bool MPEG4AtomParser::ParseAACConfig(const uint8_t* data, uint32_t size, uint32_
2744 AudioChannelLayout &layout)2761 AudioChannelLayout &layout)
2745{2762{
2746 FALSE_RETURN_V_MSG_E(IsLastTrackValid(), false, "Invalid current track");2763 FALSE_RETURN_V_MSG_E(IsLastTrackValid(), false, "Invalid current track");
2747- auto bitReader = std::make_shared<DemuxerBitReader>(data, size);2764+ DemuxerBitReader bitReader(data, size);
2748- FALSE_RETURN_V_MSG_E(bitReader != nullptr, false, "Failed create bitReader");2765+ FALSE_RETURN_V(bitReader.HasBits(MIN_BOX_SIZE), false);
2749- FALSE_RETURN_V(bitReader->HasBits(MIN_BOX_SIZE), false);2766+ uint8_t audioObjectType = bitReader.ReadBits(0x05);
2750- uint8_t audioObjectType = bitReader->ReadBits(0x05);
2751 if (audioObjectType == 0x1F) {2767 if (audioObjectType == 0x1F) {
2752- FALSE_RETURN_V(bitReader->HasBits(0x11), false);2768+ FALSE_RETURN_V(bitReader.HasBits(0x11), false);
2753- audioObjectType = 0x20 + bitReader->ReadBits(0x06);2769+ audioObjectType = 0x20 + bitReader.ReadBits(0x06);
2754 }2770 }
2755- uint8_t samplingFreqIndex = bitReader->ReadBits(0x04);2771+ uint8_t samplingFreqIndex = bitReader.ReadBits(0x04);
2756 if (samplingFreqIndex == 0x0F) {2772 if (samplingFreqIndex == 0x0F) {
2757- FALSE_RETURN_V(bitReader->HasBits(0x1F), false);2773+ FALSE_RETURN_V(bitReader.HasBits(0x1F), false);
2758- sampleRate = bitReader->ReadBits(0x08) << 0x10 | bitReader->ReadBits(0x08) << 0x08 | bitReader->ReadBits(0x08);2774+ sampleRate = (static_cast<uint32_t>(bitReader.ReadBits(0x08)) << 0x10) |
2775+ (static_cast<uint32_t>(bitReader.ReadBits(0x08)) << 0x08) |
2776+ static_cast<uint32_t>(bitReader.ReadBits(0x08));
2759 } else {2777 } else {
2760 if (samplingFreqIndex < sizeof(AAC_SAMPLE_RATE_TABLE) / sizeof(AAC_SAMPLE_RATE_TABLE[0])) {2778 if (samplingFreqIndex < sizeof(AAC_SAMPLE_RATE_TABLE) / sizeof(AAC_SAMPLE_RATE_TABLE[0])) {
2761 sampleRate = AAC_SAMPLE_RATE_TABLE[samplingFreqIndex];2779 sampleRate = AAC_SAMPLE_RATE_TABLE[samplingFreqIndex];
2762 }2780 }
2763 }2781 }
2764- uint8_t channelConfig = bitReader->ReadBits(0x04);2782+ uint8_t channelConfig = bitReader.ReadBits(0x04);
2765 uint32_t frameLengthFlag = 0;2783 uint32_t frameLengthFlag = 0;
2766 static const uint8_t aacAudioChannels[14] = {0, 1, 2, 3, 4, 5, 6, 8, 0, 0, 0, 7, 8, 24};2784 static const uint8_t aacAudioChannels[14] = {0, 1, 2, 3, 4, 5, 6, 8, 0, 0, 0, 7, 8, 24};
2767 if (channelConfig < sizeof(aacAudioChannels) / sizeof(aacAudioChannels[0])) {2785 if (channelConfig < sizeof(aacAudioChannels) / sizeof(aacAudioChannels[0])) {
@@ -2772,11 +2790,11 @@ bool MPEG4AtomParser::ParseAACConfig(const uint8_t* data, uint32_t size, uint32_
2772 return false;2790 return false;
2773 }2791 }
2774 if (audioObjectType == AOT_SBR || (audioObjectType == AOT_PS &&2792 if (audioObjectType == AOT_SBR || (audioObjectType == AOT_PS &&
2775- (!(bitReader->ShowBits(0x03) & 0x03) && !(bitReader->ShowBits(0x09) & 0x0F)))) {2793+ (!(bitReader.ShowBits(0x03) & 0x03) && !(bitReader.ShowBits(0x09) & 0x0F)))) {
2776- FALSE_RETURN_V(bitReader->HasBits(0x09), false);2794+ FALSE_RETURN_V(bitReader.HasBits(0x09), false);
2777 GetAACConfigExtInfo(bitReader, audioObjectType);2795 GetAACConfigExtInfo(bitReader, audioObjectType);
2778 }2796 }
2779- frameLengthFlag = bitReader->ReadBits(1);2797+ frameLengthFlag = bitReader.ReadBits(1);
2780 if (channelConfig == 0) {2798 if (channelConfig == 0) {
2781 FALSE_RETURN_V_MSG_E(GetAACLayoutConfig(audioObjectType, bitReader, size, channels, layout), false,2799 FALSE_RETURN_V_MSG_E(GetAACLayoutConfig(audioObjectType, bitReader, size, channels, layout), false,
2782 "Get AAC layout config failed");2800 "Get AAC layout config failed");
@@ -2805,12 +2823,10 @@ bool MPEG4AtomParser::ParseAACSpecificConfig(const uint8_t* data, uint32_t size)
2805 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::AUDIO_SAMPLE_RATE>(static_cast<int32_t>(sampleRate));2823 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::AUDIO_SAMPLE_RATE>(static_cast<int32_t>(sampleRate));
2806 if (layout == AudioChannelLayout::UNKNOWN) {2824 if (layout == AudioChannelLayout::UNKNOWN) {
2807 int32_t channelCount = 0;2825 int32_t channelCount = 0;
2808- auto audioParser = std::make_shared<MPEG4AudioParser>();
2809- FALSE_RETURN_V_MSG_E(audioParser != nullptr, false, "Failed create audioParser");
2810 FALSE_RETURN_V_MSG_E(2826 FALSE_RETURN_V_MSG_E(
2811 mediaInfo_.tracks[lastTrack_->trackIndex].Get<Tag::AUDIO_CHANNEL_COUNT>(channelCount),2827 mediaInfo_.tracks[lastTrack_->trackIndex].Get<Tag::AUDIO_CHANNEL_COUNT>(channelCount),
2812 false, "Channel count missed");2828 false, "Channel count missed");
2813- layout = audioParser->GetDefaultChannelLayout(channelCount);2829+ layout = MPEG4AudioParser::GetDefaultChannelLayout(channelCount);
2814 }2830 }
2815 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::AUDIO_CHANNEL_LAYOUT>(layout);2831 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::AUDIO_CHANNEL_LAYOUT>(layout);
2816 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::AUDIO_OUTPUT_CHANNELS>(static_cast<int32_t>(channels));2832 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::AUDIO_OUTPUT_CHANNELS>(static_cast<int32_t>(channels));
@@ -3049,28 +3065,27 @@ Status MPEG4AtomParser::ParseDca3Entry(MPEG4Atom currentAtom, ParseContext* ctx)
3049 return Status::OK;3065 return Status::OK;
3050 }3066 }
3051 3067 
3052- auto bitReader = std::make_shared<DemuxerBitReader>(dca3Data.get(), dataSize);3068+ DemuxerBitReader bitReader(dca3Data.get(), dataSize);
3053- FALSE_RETURN_V_MSG_E(bitReader != nullptr, Status::ERROR_NO_MEMORY, "Failed create bitReader");
3054 // 16为av3a config data长度3069 // 16为av3a config data长度
3055- FALSE_RETURN_V_MSG_E(bitReader->HasBits(16), Status::ERROR_INVALID_DATA, "av3a config data too short");3070+ FALSE_RETURN_V_MSG_E(bitReader.HasBits(16), Status::ERROR_INVALID_DATA, "av3a config data too short");
3056 3071 
3057 // 解析基础头部信息3072 // 解析基础头部信息
3058- uint8_t audioCodecId = bitReader->ReadBits(4);3073+ uint8_t audioCodecId = bitReader.ReadBits(4);
3059 FALSE_RETURN_V_MSG_E(audioCodecId == AV3A_LOSSY_CODEC_ID, Status::ERROR_INVALID_DATA, "Unsupported codec id");3074 FALSE_RETURN_V_MSG_E(audioCodecId == AV3A_LOSSY_CODEC_ID, Status::ERROR_INVALID_DATA, "Unsupported codec id");
3060- uint8_t samplingFrequencyIndex = bitReader->ReadBits(4);3075+ uint8_t samplingFrequencyIndex = bitReader.ReadBits(4);
3061- uint8_t nnType = bitReader->ReadBits(3);3076+ uint8_t nnType = bitReader.ReadBits(3);
3062 FALSE_RETURN_V_MSG_E(nnType >= AV3A_BASELINE_NN_TYPE && nnType <= AV3A_LC_NN_TYPE,3077 FALSE_RETURN_V_MSG_E(nnType >= AV3A_BASELINE_NN_TYPE && nnType <= AV3A_LC_NN_TYPE,
3063 Status::ERROR_INVALID_DATA, "Unsupported av3a nn type");3078 Status::ERROR_INVALID_DATA, "Unsupported av3a nn type");
3064- FALSE_RETURN_V_MSG_E(bitReader->SkipBits(1), Status::ERROR_INVALID_DATA, "Skip reserved bit failed");3079+ FALSE_RETURN_V_MSG_E(bitReader.SkipBits(1), Status::ERROR_INVALID_DATA, "Skip reserved bit failed");
3065- uint8_t contentType = bitReader->ReadBits(4);3080+ uint8_t contentType = bitReader.ReadBits(4);
3066 3081 
3067 // 解析 ContentType 对应详情3082 // 解析 ContentType 对应详情
3068 Av3aConfigParams params;3083 Av3aConfigParams params;
3069- ret = ParseDca3ContentType(*bitReader, contentType, params);3084+ ret = ParseDca3ContentType(bitReader, contentType, params);
3070 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "ParseDca3ContentType failed");3085 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "ParseDca3ContentType failed");
3071 3086 
3072 // 更新元数据标签3087 // 更新元数据标签
3073- ret = UpdateDca3TrackMeta(*bitReader, params);3088+ ret = UpdateDca3TrackMeta(bitReader, params);
3074 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "UpdateDca3TrackMeta failed");3089 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "UpdateDca3TrackMeta failed");
3075 3090 
3076 MEDIA_LOG_I("MPEG4AtomParser::ParseDca3 out");3091 MEDIA_LOG_I("MPEG4AtomParser::ParseDca3 out");
@@ -3082,7 +3097,7 @@ Status MPEG4AtomParser::ParseDca3Entry(MPEG4Atom currentAtom, ParseContext* ctx)
3082 return Status::OK;3097 return Status::OK;
3083}3098}
3084 3099 
3085-Status MPEG4AtomParser::ParseColorParams(int64_t offset, uint64_t dataSize, const std::string& colorType,3100+Status MPEG4AtomParser::ParseColorParams(int64_t offset, uint64_t dataSize, uint32_t colorType,
3086 ParseContext* ctx)3101 ParseContext* ctx)
3087{3102{
3088 FALSE_RETURN_V_MSG_E(IsLastTrackValid(), Status::ERROR_INVALID_DATA, "Invalid current track");3103 FALSE_RETURN_V_MSG_E(IsLastTrackValid(), Status::ERROR_INVALID_DATA, "Invalid current track");
@@ -3099,7 +3114,7 @@ Status MPEG4AtomParser::ParseColorParams(int64_t offset, uint64_t dataSize, cons
3099 uint8_t colorRange = 0;3114 uint8_t colorRange = 0;
3100 3115 
3101 constexpr uint8_t colorRangeOffset = 6;3116 constexpr uint8_t colorRangeOffset = 6;
3102- if (colorType == "nclx" && dataSize >= 0x07) { // nclx类型有额外的color range信息3117+ if (colorType == static_cast<uint32_t>(FourccType("nclx")) && dataSize >= 0x07) { // nclx类型有额外的color range信息
3103 uint8_t nclxColorRange = (colorParams[colorRangeOffset] >> 0x07) & 1; // 取最高位3118 uint8_t nclxColorRange = (colorParams[colorRangeOffset] >> 0x07) & 1; // 取最高位
3104 if (nclxColorRange) {3119 if (nclxColorRange) {
3105 colorRange = 1;3120 colorRange = 1;
@@ -3127,14 +3142,16 @@ Status MPEG4AtomParser::ParseColr(MPEG4Atom currentAtom, int32_t depth, ParseCon
3127 int32_t typeSize = sizeof(colorParamType);3142 int32_t typeSize = sizeof(colorParamType);
3128 Status ret = dataReader_->ReadUintData(ctx->dataOffset, colorParamType, sizeof(colorParamType));3143 Status ret = dataReader_->ReadUintData(ctx->dataOffset, colorParamType, sizeof(colorParamType));
3129 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "Read color parameter type failed");3144 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "Read color parameter type failed");
3130- std::string colorType(reinterpret_cast<char*>(colorParamType), sizeof(colorParamType));3145+ uint32_t colorType = GetU32Value(colorParamType);
3131 3146 
3132- FALSE_RETURN_V_MSG_W(colorType == "nclx" || colorType == "nclc" || colorType == "prof", Status::OK,3147+ FALSE_RETURN_V_MSG_W(colorType == static_cast<uint32_t>(FourccType("nclx")) ||
3133- "Unsupported color parameter type: " PUBLIC_LOG_S, colorType.c_str());3148+ colorType == static_cast<uint32_t>(FourccType("nclc")) ||
3149+ colorType == static_cast<uint32_t>(FourccType("prof")), Status::OK,
3150+ "Unsupported color parameter type: " PUBLIC_LOG_U32X, colorType);
3134 uint64_t dataSize = 0;3151 uint64_t dataSize = 0;
3135 FALSE_RETURN_V_NOLOG(currentAtom.dataSize > static_cast<uint64_t>(typeSize), Status::ERROR_INVALID_DATA);3152 FALSE_RETURN_V_NOLOG(currentAtom.dataSize > static_cast<uint64_t>(typeSize), Status::ERROR_INVALID_DATA);
3136 dataSize = currentAtom.dataSize - static_cast<uint64_t>(typeSize);3153 dataSize = currentAtom.dataSize - static_cast<uint64_t>(typeSize);
3137- if (colorType != "prof") {3154+ if (colorType != static_cast<uint32_t>(FourccType("prof"))) {
3138 ret = ParseColorParams(ctx->dataOffset + typeSize, dataSize, colorType, ctx);3155 ret = ParseColorParams(ctx->dataOffset + typeSize, dataSize, colorType, ctx);
3139 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "Parse color parameters failed");3156 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "Parse color parameters failed");
3140 }3157 }
@@ -3447,7 +3464,7 @@ void MPEG4AtomParser::CheckSidxReferenceEnd()
3447}3464}
3448 3465 
3449Status MPEG4AtomParser::ParseSidxEntries(const uint8_t* headerInfo, uint64_t entryOffset, uint64_t bufferSize,3466Status MPEG4AtomParser::ParseSidxEntries(const uint8_t* headerInfo, uint64_t entryOffset, uint64_t bufferSize,
3450- SidxParseContext& sidxCtx, std::shared_ptr<Track> currentTrack)3467+ SidxParseContext& sidxCtx, const std::shared_ptr<Track>& currentTrack)
3451{3468{
3452 uint64_t entriesSize = 0;3469 uint64_t entriesSize = 0;
3453 uint64_t entriesEndOffset = 0;3470 uint64_t entriesEndOffset = 0;
@@ -3489,7 +3506,7 @@ Status MPEG4AtomParser::GetSidxEntryOffset(uint64_t entryOffset, uint64_t buffer
3489}3506}
3490 3507 
3491Status MPEG4AtomParser::ParseSidxEntry(const uint8_t* headerInfo, uint64_t currentEntryOffset,3508Status MPEG4AtomParser::ParseSidxEntry(const uint8_t* headerInfo, uint64_t currentEntryOffset,
3492- SidxParseContext& sidxCtx, std::shared_ptr<Track> currentTrack, uint32_t index)3509+ SidxParseContext& sidxCtx, const std::shared_ptr<Track>& currentTrack, uint32_t index)
3493{3510{
3494 uint32_t size = GetU32Value(&headerInfo[currentEntryOffset]);3511 uint32_t size = GetU32Value(&headerInfo[currentEntryOffset]);
3495 uint32_t duration = GetU32Value(&headerInfo[currentEntryOffset + sizeof(uint32_t)]);3512 uint32_t duration = GetU32Value(&headerInfo[currentEntryOffset + sizeof(uint32_t)]);
@@ -3762,18 +3779,50 @@ Status MPEG4AtomParser::ParseUdta(MPEG4Atom currentAtom, int32_t depth, ParseCon
3762 3779 
3763void MPEG4AtomParser::ParseLocationString(const std::string& locationStr)3780void MPEG4AtomParser::ParseLocationString(const std::string& locationStr)
3764{3781{
3765- std::regex pattern(R"([+-]\d+\.\d+)");3782+ constexpr size_t maxLocationValueCount = 3;
3766- std::sregex_iterator numbers(locationStr.cbegin(), locationStr.cend(), pattern);3783+ constexpr size_t minLocationValueCount = 2;
3767- std::sregex_iterator end;3784+ const std::locale locationLocale;
3785+ const auto& ctype = std::use_facet<std::ctype<char>>(locationLocale);
3786+ const auto isDigit = [&ctype](char value) {
3787+ return ctype.is(std::ctype_base::digit, value);
3788+ };
3789+ std::array<std::string_view, maxLocationValueCount> values;
3790+ size_t valueCount = 0;
3791+ for (size_t start = 0; start < locationStr.size() && valueCount < values.size();) {
3792+ if (locationStr[start] != '+' && locationStr[start] != '-') {
3793+ ++start;
3794+ continue;
3795+ }
3796+ size_t position = start + 1;
3797+ size_t integerStart = position;
3798+ while (position < locationStr.size() && isDigit(locationStr[position])) {
3799+ ++position;
3800+ }
3801+ if (position == integerStart || position >= locationStr.size() || locationStr[position] != '.') {
3802+ ++start;
3803+ continue;
3804+ }
3805+ ++position;
3806+ size_t fractionStart = position;
3807+ while (position < locationStr.size() && isDigit(locationStr[position])) {
3808+ ++position;
3809+ }
3810+ if (position == fractionStart) {
3811+ ++start;
3812+ continue;
3813+ }
3814+ values[valueCount++] = std::string_view(locationStr).substr(start, position - start);
3815+ start = position;
3816+ }
3768 3817 
3769- const uint32_t minLocationNum = 2; // 至少需要两个数字:纬度和经度3818+ FALSE_RETURN_MSG_D(valueCount >= minLocationValueCount, "Info format error");
3770- auto cnt = static_cast<uint32_t>(std::distance(numbers, end));3819+ SetToFormatIfConvertSuccess(
3771- FALSE_RETURN_MSG_D(cnt >= minLocationNum, "Info format error");3820+ mediaInfo_.general, Tag::MEDIA_LATITUDE, std::string(values[LATITUDE_OFFSET]), ConvertValueType::FLOAT);
3772- SetToFormatIfConvertSuccess(mediaInfo_.general, Tag::MEDIA_LATITUDE, numbers->str(), ConvertValueType::FLOAT);3821+ SetToFormatIfConvertSuccess(
3773- SetToFormatIfConvertSuccess(mediaInfo_.general, Tag::MEDIA_LONGITUDE, (++numbers)->str(), ConvertValueType::FLOAT);3822+ mediaInfo_.general, Tag::MEDIA_LONGITUDE, std::string(values[LONGITUDE_OFFSET]), ConvertValueType::FLOAT);
3774- if (cnt > minLocationNum) {3823+ if (valueCount > minLocationValueCount) {
3775 SetToFormatIfConvertSuccess(3824 SetToFormatIfConvertSuccess(
3776- mediaInfo_.general, Tag::MEDIA_ALTITUDE, (++numbers)->str(), ConvertValueType::FLOAT);3825+ mediaInfo_.general, Tag::MEDIA_ALTITUDE, std::string(values[ALTITUDE_OFFSET]), ConvertValueType::FLOAT);
3777 }3826 }
3778}3827}
3779 3828 
@@ -3864,8 +3913,7 @@ Status MPEG4AtomParser::ParseCover(MPEG4Atom currentAtom, uint32_t dataType, uin
3864 }3913 }
3865 coverMeta.Set<Tag::VIDEO_WIDTH>(videoWidth);3914 coverMeta.Set<Tag::VIDEO_WIDTH>(videoWidth);
3866 coverMeta.Set<Tag::VIDEO_HEIGHT>(videoHeight);3915 coverMeta.Set<Tag::VIDEO_HEIGHT>(videoHeight);
3867- std::vector<uint8_t> cover(stringSize);3916+ std::vector<uint8_t> cover(coverData.get(), coverData.get() + stringSize);
3868- cover.assign(coverData.get(), coverData.get() + stringSize);
3869 coverMeta.Set<Tag::MEDIA_COVER>(std::move(cover));3917 coverMeta.Set<Tag::MEDIA_COVER>(std::move(cover));
3870 mediaInfo_.tracks.emplace_back(std::move(coverMeta));3918 mediaInfo_.tracks.emplace_back(std::move(coverMeta));
3871 ++trackCount_;3919 ++trackCount_;
@@ -3883,7 +3931,7 @@ Status MPEG4AtomParser::ParseUserDataString(MPEG4Atom currentAtom, int32_t depth
3883{3931{
3884 ctx->offset += static_cast<int64_t>(currentAtom.size);3932 ctx->offset += static_cast<int64_t>(currentAtom.size);
3885 std::string key = GetMetadataKey(currentAtom.type, ctx);3933 std::string key = GetMetadataKey(currentAtom.type, ctx);
3886- if (key.empty() && currentAtom.type != FourccType("covr")) {3934+ if (key.empty() && currentAtom.type != static_cast<uint32_t>(FourccType("covr"))) {
3887 std::string atomTypeStr = FourccToString(currentAtom.type);3935 std::string atomTypeStr = FourccToString(currentAtom.type);
3888 MEDIA_LOG_W("Unknown metadata type: " PUBLIC_LOG_S, atomTypeStr.c_str());3936 MEDIA_LOG_W("Unknown metadata type: " PUBLIC_LOG_S, atomTypeStr.c_str());
3889 return Status::OK;3937 return Status::OK;
@@ -3901,6 +3949,46 @@ Status MPEG4AtomParser::ParseUserDataString(MPEG4Atom currentAtom, int32_t depth
3901 return ret;3949 return ret;
3902}3950}
3903 3951 
3952+std::string GetDefaultKey(uint32_t atomType)
3953+{
3954+ switch (atomType) {
3955+ case static_cast<uint32_t>(FourccType("\251nam")):
3956+ return "title";
3957+ case static_cast<uint32_t>(FourccType("\251ART")):
3958+ case static_cast<uint32_t>(FourccType("\251aut")):
3959+ return "artist";
3960+ case static_cast<uint32_t>(FourccType("\251alb")):
3961+ return "album";
3962+ case static_cast<uint32_t>(FourccType("aART")):
3963+ return "album_artist";
3964+ case static_cast<uint32_t>(FourccType("\251day")):
3965+ return "date";
3966+ case static_cast<uint32_t>(FourccType("\251cmt")):
3967+ case static_cast<uint32_t>(FourccType("\251inf")):
3968+ return "comment";
3969+ case static_cast<uint32_t>(FourccType("\251gen")):
3970+ return "genre";
3971+ case static_cast<uint32_t>(FourccType("\251cpy")):
3972+ case static_cast<uint32_t>(FourccType("cprt")):
3973+ return "copyright";
3974+ case static_cast<uint32_t>(FourccType("\251com")):
3975+ case static_cast<uint32_t>(FourccType("\251wrt")):
3976+ return "composer";
3977+ case static_cast<uint32_t>(FourccType("\251lyr")):
3978+ return "lyrics";
3979+ case static_cast<uint32_t>(FourccType("\251xyz")):
3980+ return "location";
3981+ case static_cast<uint32_t>(FourccType("desc")):
3982+ return "description";
3983+ case static_cast<uint32_t>(FourccType("\251too")):
3984+ case static_cast<uint32_t>(FourccType("\251enc")):
3985+ case static_cast<uint32_t>(FourccType("\251swr")):
3986+ return "encoder";
3987+ default:
3988+ return "";
3989+ }
3990+}
3991+ 
3904std::string MPEG4AtomParser::GetMetadataKey(uint32_t atomType, ParseContext* ctx)3992std::string MPEG4AtomParser::GetMetadataKey(uint32_t atomType, ParseContext* ctx)
3905{3993{
3906 // 如果是动态key(iTunes metadata with keys box)3994 // 如果是动态key(iTunes metadata with keys box)
@@ -3919,31 +4007,7 @@ std::string MPEG4AtomParser::GetMetadataKey(uint32_t atomType, ParseContext* ctx
3919 MEDIA_LOG_W("Dynamic key index out of range: " PUBLIC_LOG_S, atomTypeStr.c_str());4007 MEDIA_LOG_W("Dynamic key index out of range: " PUBLIC_LOG_S, atomTypeStr.c_str());
3920 }4008 }
3921 }4009 }
3922- 4010+ return GetDefaultKey(atomType);
3923- static std::map<uint32_t, std::string> keyMap = {
3924- { FourccType("\251nam"), "title" },
3925- { FourccType("\251ART"), "artist" }, // "\251ART" and "\251aut" refer the same value
3926- { FourccType("\251aut"), "artist" },
3927- { FourccType("\251alb"), "album" },
3928- { FourccType("aART"), "album_artist" },
3929- { FourccType("\251day"), "date" },
3930- { FourccType("\251cmt"), "comment" },
3931- { FourccType("\251inf"), "comment" },
3932- { FourccType("\251gen"), "genre" },
3933- { FourccType("\251cpy"), "copyright" },
3934- { FourccType("cprt"), "copyright" },
3935- { FourccType("\251com"), "composer" },
3936- { FourccType("\251wrt"), "composer" },
3937- { FourccType("\251lyr"), "lyrics" },
3938- { FourccType("\251xyz"), "location" },
3939- { FourccType("desc"), "description" },
3940- { FourccType("\251too"), "encoder" },
3941- { FourccType("\251enc"), "encoder" },
3942- { FourccType("\251swr"), "encoder" },
3943- };
3944- 
3945- auto it = keyMap.find(atomType);
3946- return (it != keyMap.end()) ? it->second : "";
3947}4011}
3948 4012 
3949Status MPEG4AtomParser::ParseItunesMetadata(MPEG4Atom currentAtom, std::string& key, ParseContext* ctx)4013Status MPEG4AtomParser::ParseItunesMetadata(MPEG4Atom currentAtom, std::string& key, ParseContext* ctx)
@@ -4079,7 +4143,11 @@ std::string DecodeMacString(const uint8_t* data, size_t size)
4079 4143 
4080bool MPEG4AtomParser::SetMetadataValue(const std::string& key, const std::string& value)4144bool MPEG4AtomParser::SetMetadataValue(const std::string& key, const std::string& value)
4081{4145{
4082- static const std::map<std::string, TagType> keyToTagMap = {4146+ struct MetadataTagMapping {
4147+ std::string_view key;
4148+ const char* tag;
4149+ };
4150+ static constexpr std::array<MetadataTagMapping, 16> keyToTagMap = {{
4083 {"title", Tag::MEDIA_TITLE},4151 {"title", Tag::MEDIA_TITLE},
4084 {"artist", Tag::MEDIA_ARTIST},4152 {"artist", Tag::MEDIA_ARTIST},
4085 {"album", Tag::MEDIA_ALBUM},4153 {"album", Tag::MEDIA_ALBUM},
@@ -4096,17 +4164,20 @@ bool MPEG4AtomParser::SetMetadataValue(const std::string& key, const std::string
4096 {"creation_time", Tag::MEDIA_CREATION_TIME},4164 {"creation_time", Tag::MEDIA_CREATION_TIME},
4097 {"aigc", Tag::MEDIA_AIGC},4165 {"aigc", Tag::MEDIA_AIGC},
4098 {"encoder", Tag::MEDIA_ENCODER},4166 {"encoder", Tag::MEDIA_ENCODER},
4099- };4167+ }};
4100 4168 
4101- auto it = keyToTagMap.find(Converter::ToLower(key));4169+ const std::string lowerKey = Converter::ToLower(key);
4102- if (it != keyToTagMap.end()) {4170+ const auto it = std::find_if(keyToTagMap.cbegin(), keyToTagMap.cend(),
4171+ [&lowerKey](const MetadataTagMapping& mapping) { return mapping.key == lowerKey; });
4172+ if (it != keyToTagMap.cend()) {
4173+ const TagType tag = it->tag;
4103 std::string resultStr = "";4174 std::string resultStr = "";
4104 if (!Converter::IsUTF8(value) && Converter::IsGBK(value.c_str())) {4175 if (!Converter::IsUTF8(value) && Converter::IsGBK(value.c_str())) {
4105 resultStr = Converter::ConvertGBKToUTF8(value);4176 resultStr = Converter::ConvertGBKToUTF8(value);
4106 }4177 }
4107 resultStr = resultStr.length() > 0 ? resultStr : value;4178 resultStr = resultStr.length() > 0 ? resultStr : value;
4108 if (resultStr.length() > 0) {4179 if (resultStr.length() > 0) {
4109- mediaInfo_.general.SetData(it->second, resultStr);4180+ mediaInfo_.general.SetData(tag, resultStr);
4110 }4181 }
4111 return true;4182 return true;
4112 } else if (key == "location") {4183 } else if (key == "location") {
@@ -4194,7 +4265,7 @@ Status MPEG4AtomParser::ParseMeta(MPEG4Atom currentAtom, int32_t depth, ParseCon
4194 return Status::ERROR_INVALID_DATA;4265 return Status::ERROR_INVALID_DATA;
4195 }4266 }
4196 bool isFileLevelGltfMeta = depth == MPEG4_ROOT_DEPTH &&4267 bool isFileLevelGltfMeta = depth == MPEG4_ROOT_DEPTH &&
4197- ctx->compatibleBrands.count(FourccType("glti")) > 0;4268+ ctx->hasGltfCompatibleBrand;
4198 if (currentAtom.dataSize < sizeof(uint32_t) || (depth == MPEG4_ROOT_DEPTH && !isFileLevelGltfMeta)) {4269 if (currentAtom.dataSize < sizeof(uint32_t) || (depth == MPEG4_ROOT_DEPTH && !isFileLevelGltfMeta)) {
4199 // 数据太小,或者在root级别,直接跳过4270 // 数据太小,或者在root级别,直接跳过
4200 ctx->offset = endOffset;4271 ctx->offset = endOffset;
@@ -4323,17 +4394,15 @@ Status MPEG4AtomParser::ParseLoci(MPEG4Atom currentAtom, int32_t depth, ParseCon
4323 float latitude = latitudeRaw / static_cast<float>(CONVERT_SCALE);4394 float latitude = latitudeRaw / static_cast<float>(CONVERT_SCALE);
4324 float altitude = altitudeRaw / static_cast<float>(CONVERT_SCALE);4395 float altitude = altitudeRaw / static_cast<float>(CONVERT_SCALE);
4325 4396 
4326- std::ostringstream locationStream;4397+ std::string locationStr;
4327- locationStream << std::fixed <<4398+ FALSE_RETURN_V_MSG_E(AppendFixedFloat(locationStr, latitude, PRECISION, LATITUDE_WIDTH),
4328- std::setprecision(PRECISION) <<4399+ Status::ERROR_UNKNOWN, "Format latitude failed");
4329- std::showpos <<4400+ FALSE_RETURN_V_MSG_E(AppendFixedFloat(locationStr, longitude, PRECISION, LONGITUDE_WIDTH),
4330- std::setfill('0') <<4401+ Status::ERROR_UNKNOWN, "Format longitude failed");
4331- std::setw(LATITUDE_WIDTH) << latitude <<
4332- std::setw(LONGITUDE_WIDTH) << longitude;
4333 if (altitude) {4402 if (altitude) {
4334- locationStream << std::setprecision(ALTITUDE_PRECISION) << altitude;4403+ FALSE_RETURN_V_MSG_E(AppendFixedFloat(locationStr, altitude, ALTITUDE_PRECISION, 0),
4404+ Status::ERROR_UNKNOWN, "Format altitude failed");
4335 }4405 }
4336- std::string locationStr = locationStream.str();
4337 ParseLocationString(locationStr);4406 ParseLocationString(locationStr);
4338 return ret;4407 return ret;
4339}4408}
@@ -4997,15 +5066,14 @@ Status MPEG4AtomParser::ParseChan(MPEG4Atom currentAtom, int32_t depth, ParseCon
4997 }5066 }
4998 channelLayoutMask = layoutTag == 0 ? (channelSets ? channelSets : 0) : GetChannelLayoutByBitmap(layoutTag, bitmap);5067 channelLayoutMask = layoutTag == 0 ? (channelSets ? channelSets : 0) : GetChannelLayoutByBitmap(layoutTag, bitmap);
4999 if (channelLayoutMask) {5068 if (channelLayoutMask) {
5000- auto audioParser = std::make_shared<MPEG4AudioParser>();5069+ AudioChannelLayout layout = MPEG4AudioParser::FindValidChannelLayout(
5001- FALSE_RETURN_V_MSG_E(audioParser != nullptr, Status::ERROR_NO_MEMORY, "Failed create audioParser");5070+ static_cast<uint64_t>(channelLayoutMask));
5002- AudioChannelLayout layout = audioParser->FindValidChannelLayout(static_cast<uint64_t>(channelLayoutMask));
5003 if (layout == AudioChannelLayout::UNKNOWN) {5071 if (layout == AudioChannelLayout::UNKNOWN) {
5004 int32_t channelCount = 0;5072 int32_t channelCount = 0;
5005 FALSE_RETURN_V_MSG_E(5073 FALSE_RETURN_V_MSG_E(
5006 mediaInfo_.tracks[lastTrack_->trackIndex].Get<Tag::AUDIO_CHANNEL_COUNT>(channelCount),5074 mediaInfo_.tracks[lastTrack_->trackIndex].Get<Tag::AUDIO_CHANNEL_COUNT>(channelCount),
5007 Status::ERROR_INVALID_DATA, "Channel count missed");5075 Status::ERROR_INVALID_DATA, "Channel count missed");
5008- layout = audioParser->GetDefaultChannelLayout(channelCount);5076+ layout = MPEG4AudioParser::GetDefaultChannelLayout(channelCount);
5009 }5077 }
5010 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::AUDIO_CHANNEL_LAYOUT>(layout);5078 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::AUDIO_CHANNEL_LAYOUT>(layout);
5011 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::AUDIO_OUTPUT_CHANNEL_LAYOUT>(layout);5079 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::AUDIO_OUTPUT_CHANNEL_LAYOUT>(layout);
@@ -5082,8 +5150,8 @@ Status MPEG4AtomParser::ParseClli(MPEG4Atom currentAtom, int32_t depth, ParseCon
5082 Cta861 cta861;5150 Cta861 cta861;
5083 cta861.maxContentLightLevel = maxCLL;5151 cta861.maxContentLightLevel = maxCLL;
5084 cta861.maxFrameAverageLightLevel = maxFALL;5152 cta861.maxFrameAverageLightLevel = maxFALL;
5085- std::vector<uint8_t> cta861Vec(sizeof(cta861));5153+ auto cta861Begin = reinterpret_cast<uint8_t*>(&cta861);
5086- cta861Vec.assign(reinterpret_cast<uint8_t*>(&cta861), reinterpret_cast<uint8_t*>(&cta861) + sizeof(cta861));5154+ std::vector<uint8_t> cta861Vec(cta861Begin, cta861Begin + sizeof(cta861));
5087 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::VIDEO_STATIC_METADATA_CTA861>(cta861Vec);5155 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::VIDEO_STATIC_METADATA_CTA861>(cta861Vec);
5088 return Status::OK;5156 return Status::OK;
5089}5157}
@@ -5117,51 +5185,76 @@ Status MPEG4AtomParser::ParseMdcv(MPEG4Atom currentAtom, int32_t depth, ParseCon
5117 smpte2086.whitePointY = whitePointY * PRIMARY_SCALE;5185 smpte2086.whitePointY = whitePointY * PRIMARY_SCALE;
5118 smpte2086.maxLuminance = maxLuminance * LUMI_SCALE;5186 smpte2086.maxLuminance = maxLuminance * LUMI_SCALE;
5119 smpte2086.minLuminance = minLuminance * LUMI_SCALE;5187 smpte2086.minLuminance = minLuminance * LUMI_SCALE;
5120- std::vector<uint8_t> smpte2086Vec(sizeof(smpte2086));5188+ auto smpte2086Begin = reinterpret_cast<uint8_t*>(&smpte2086);
5121- smpte2086Vec.assign(5189+ std::vector<uint8_t> smpte2086Vec(smpte2086Begin, smpte2086Begin + sizeof(smpte2086));
5122- reinterpret_cast<uint8_t*>(&smpte2086), reinterpret_cast<uint8_t*>(&smpte2086) + sizeof(smpte2086));
5123 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::VIDEO_STATIC_METADATA_SMPT2086>(smpte2086Vec);5190 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::VIDEO_STATIC_METADATA_SMPT2086>(smpte2086Vec);
5124 return Status::OK;5191 return Status::OK;
5125}5192}
5126// LCOV_EXCL_STOP5193// LCOV_EXCL_STOP
5127 5194 
5128-void MPEG4AtomParser::InitParseTable()5195+auto MPEG4AtomParser::FindStaticExtendedAtomParser(int32_t atomType) const -> ParseFunction
5129{5196{
5130- // 填充解析函数表5197+ switch (atomType) {
5131- MPEG4ParseTable_ = {5198+ case FourccType("tref"): return &MPEG4AtomParser::ParseTref;
5132- {FourccType("ftyp"), &MPEG4AtomParser::ParseFtyp}, {FourccType("moov"), &MPEG4AtomParser::ParseMoov},5199+ case FourccType("udta"): return &MPEG4AtomParser::ParseUdta;
5133- {FourccType("wide"), &MPEG4AtomParser::ParseWide}, {FourccType("mdat"), &MPEG4AtomParser::ParseMdat},5200+ case FourccType("meta"): return &MPEG4AtomParser::ParseMeta;
5134- {FourccType("trak"), &MPEG4AtomParser::ParseTrak}, {FourccType("mvhd"), &MPEG4AtomParser::ParseMvhd},5201+ case FourccType("ilst"): return &MPEG4AtomParser::ParseIlst;
5135- {FourccType("tkhd"), &MPEG4AtomParser::ParseTkhd}, {FourccType("edts"), &MPEG4AtomParser::ParseEdts},5202+ case FourccType("loci"): return &MPEG4AtomParser::ParseLoci;
5136- {FourccType("elst"), &MPEG4AtomParser::ParseElst}, {FourccType("tref"), &MPEG4AtomParser::ParseTref},5203+ case FourccType("frma"): return &MPEG4AtomParser::ParseFrma;
5137- {FourccType("mdia"), &MPEG4AtomParser::ParseMdia},5204+ case FourccType("schi"): return &MPEG4AtomParser::ParseSchi;
5138- {FourccType("mdhd"), &MPEG4AtomParser::ParseMdhd}, {FourccType("hdlr"), &MPEG4AtomParser::ParseHdlr},5205+ case FourccType("schm"): return &MPEG4AtomParser::ParseSchm;
5139- {FourccType("minf"), &MPEG4AtomParser::ParseMinf}, {FourccType("stbl"), &MPEG4AtomParser::ParseStbl},5206+ case FourccType("sinf"): return &MPEG4AtomParser::ParseSinf;
5140- {FourccType("stsd"), &MPEG4AtomParser::ParseStsd}, {FourccType("btrt"), &MPEG4AtomParser::ParseBtrt},5207+ case FourccType("pssh"): return &MPEG4AtomParser::ParsePssh;
5141- {FourccType("pasp"), &MPEG4AtomParser::ParsePasp}, {FourccType("esds"), &MPEG4AtomParser::ParseEsds},5208+ case FourccType("tenc"): return &MPEG4AtomParser::ParseTenc;
5142- {FourccType("avcC"), &MPEG4AtomParser::ParseCodecConfig},5209+ case FourccType("senc"): return &MPEG4AtomParser::ParseSenc;
5143- {FourccType("hvcC"), &MPEG4AtomParser::ParseCodecConfig},5210+ case FourccType("gnre"): return &MPEG4AtomParser::ParseMoovGenre;
5144- {FourccType("vvcC"), &MPEG4AtomParser::ParseCodecConfig},5211+ case FourccType("idat"): return &MPEG4AtomParser::ParseIdat;
5145- {FourccType("colr"), &MPEG4AtomParser::ParseColr}, {FourccType("aclr"), &MPEG4AtomParser::ParseAclr},5212+ case FourccType("clli"): return &MPEG4AtomParser::ParseClli;
5146- {FourccType("glbl"), &MPEG4AtomParser::ParseGlbl}, {FourccType("stts"), &MPEG4AtomParser::ParseStts},5213+ case FourccType("mdcv"): return &MPEG4AtomParser::ParseMdcv;
5147- {FourccType("stss"), &MPEG4AtomParser::ParseStss}, {FourccType("ctts"), &MPEG4AtomParser::ParseCtts},5214+ default: return nullptr;
5148- {FourccType("stsc"), &MPEG4AtomParser::ParseStsc}, {FourccType("stsz"), &MPEG4AtomParser::ParseStsz},5215+ }
5149- {FourccType("stz2"), &MPEG4AtomParser::ParseStsz}, {FourccType("stco"), &MPEG4AtomParser::ParseStco},5216+}
5150- {FourccType("sdtp"), &MPEG4AtomParser::ParseSdtp},5217+ 
5151- {FourccType("co64"), &MPEG4AtomParser::ParseStco},5218+auto MPEG4AtomParser::FindStaticAtomParser(int32_t atomType) const -> ParseFunction
5152- {FourccType("udta"), &MPEG4AtomParser::ParseUdta},5219+{
5153- {FourccType("meta"), &MPEG4AtomParser::ParseMeta}, {FourccType("ilst"), &MPEG4AtomParser::ParseIlst},5220+ switch (atomType) {
5154- {FourccType("loci"), &MPEG4AtomParser::ParseLoci},5221+ case FourccType("ftyp"): return &MPEG4AtomParser::ParseFtyp;
5155- {FourccType("wave"), &MPEG4AtomParser::ParseWave}, {FourccType("frma"), &MPEG4AtomParser::ParseFrma},5222+ case FourccType("moov"): return &MPEG4AtomParser::ParseMoov;
5156- {FourccType("schi"), &MPEG4AtomParser::ParseSchi}, {FourccType("schm"), &MPEG4AtomParser::ParseSchm},5223+ case FourccType("wide"): return &MPEG4AtomParser::ParseWide;
5157- {FourccType("sinf"), &MPEG4AtomParser::ParseSinf},5224+ case FourccType("mdat"): return &MPEG4AtomParser::ParseMdat;
5158- {FourccType("pssh"), &MPEG4AtomParser::ParsePssh}, {FourccType("tenc"), &MPEG4AtomParser::ParseTenc},5225+ case FourccType("trak"): return &MPEG4AtomParser::ParseTrak;
5159- {FourccType("senc"), &MPEG4AtomParser::ParseSenc},5226+ case FourccType("mvhd"): return &MPEG4AtomParser::ParseMvhd;
5160- {FourccType("chan"), &MPEG4AtomParser::ParseChan},5227+ case FourccType("tkhd"): return &MPEG4AtomParser::ParseTkhd;
5161- {FourccType("gnre"), &MPEG4AtomParser::ParseMoovGenre},5228+ case FourccType("edts"): return &MPEG4AtomParser::ParseEdts;
5162- {FourccType("idat"), &MPEG4AtomParser::ParseIdat},5229+ case FourccType("elst"): return &MPEG4AtomParser::ParseElst;
5163- {FourccType("clli"), &MPEG4AtomParser::ParseClli}, {FourccType("mdcv"), &MPEG4AtomParser::ParseMdcv},5230+ case FourccType("mdia"): return &MPEG4AtomParser::ParseMdia;
5164- };5231+ case FourccType("mdhd"): return &MPEG4AtomParser::ParseMdhd;
5232+ case FourccType("hdlr"): return &MPEG4AtomParser::ParseHdlr;
5233+ case FourccType("minf"): return &MPEG4AtomParser::ParseMinf;
5234+ case FourccType("stbl"): return &MPEG4AtomParser::ParseStbl;
5235+ case FourccType("stsd"): return &MPEG4AtomParser::ParseStsd;
5236+ case FourccType("btrt"): return &MPEG4AtomParser::ParseBtrt;
5237+ case FourccType("pasp"): return &MPEG4AtomParser::ParsePasp;
5238+ case FourccType("esds"): return &MPEG4AtomParser::ParseEsds;
5239+ case FourccType("avcC"):
5240+ case FourccType("hvcC"):
5241+ case FourccType("vvcC"): return &MPEG4AtomParser::ParseCodecConfig;
5242+ case FourccType("colr"): return &MPEG4AtomParser::ParseColr;
5243+ case FourccType("aclr"): return &MPEG4AtomParser::ParseAclr;
5244+ case FourccType("glbl"): return &MPEG4AtomParser::ParseGlbl;
5245+ case FourccType("stts"): return &MPEG4AtomParser::ParseStts;
5246+ case FourccType("stss"): return &MPEG4AtomParser::ParseStss;
5247+ case FourccType("ctts"): return &MPEG4AtomParser::ParseCtts;
5248+ case FourccType("stsc"): return &MPEG4AtomParser::ParseStsc;
5249+ case FourccType("stsz"):
5250+ case FourccType("stz2"): return &MPEG4AtomParser::ParseStsz;
5251+ case FourccType("stco"):
5252+ case FourccType("co64"): return &MPEG4AtomParser::ParseStco;
5253+ case FourccType("sdtp"): return &MPEG4AtomParser::ParseSdtp;
5254+ case FourccType("wave"): return &MPEG4AtomParser::ParseWave;
5255+ case FourccType("chan"): return &MPEG4AtomParser::ParseChan;
5256+ default: return FindStaticExtendedAtomParser(atomType);
5257+ }
5165}5258}
5166 5259 
5167Status MPEG4AtomParser::ParseAtomHeader(MPEG4Atom& atom, std::string& typeStr, int32_t depth,5260Status MPEG4AtomParser::ParseAtomHeader(MPEG4Atom& atom, std::string& typeStr, int32_t depth,
@@ -5224,7 +5317,7 @@ Status MPEG4AtomParser::ValidateAtomSourceRange(MPEG4Atom& atom, const std::stri
5224 bool atomExceedsSource = __builtin_add_overflow(static_cast<uint64_t>(ctx->offset), atom.size,5317 bool atomExceedsSource = __builtin_add_overflow(static_cast<uint64_t>(ctx->offset), atom.size,
5225 &atomEndOffset) || atomEndOffset > dataSourceSize;5318 &atomEndOffset) || atomEndOffset > dataSourceSize;
5226 if (atomExceedsSource && depth == MPEG4_ROOT_DEPTH && moovFound_ && hasMdatBox_ &&5319 if (atomExceedsSource && depth == MPEG4_ROOT_DEPTH && moovFound_ && hasMdatBox_ &&
5227- MPEG4ParseTable_.find(atom.type) == MPEG4ParseTable_.end()) {5320+ FindStaticAtomParser(atom.type) == nullptr) {
5228 uint64_t remainingSize = dataSourceSize - static_cast<uint64_t>(ctx->offset);5321 uint64_t remainingSize = dataSourceSize - static_cast<uint64_t>(ctx->offset);
5229 FALSE_RETURN_V_MSG_E(remainingSize >= atomInfoSize, Status::ERROR_INVALID_DATA,5322 FALSE_RETURN_V_MSG_E(remainingSize >= atomInfoSize, Status::ERROR_INVALID_DATA,
5230 "Invalid trailing unknown atom size");5323 "Invalid trailing unknown atom size");
@@ -5248,15 +5341,10 @@ void MPEG4AtomParser::SetHdrTypeInfo(MPEG4Atom currentAtom)
5248 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::VIDEO_WIDTH>(0);5341 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::VIDEO_WIDTH>(0);
5249 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::VIDEO_HEIGHT>(0);5342 mediaInfo_.tracks[lastTrack_->trackIndex].Set<Tag::VIDEO_HEIGHT>(0);
5250 }5343 }
5251- std::set<int32_t> hdrVividBox = {5344+ if (currentAtom.type == FourccType("cuvv")) {
5252- FourccType("cuvv")
5253- };
5254- std::set<int32_t> dbBox = {
5255- FourccType("dvcC"), FourccType("dvvC"), FourccType("dvwC"), FourccType("dvh1")
5256- };
5257- if (hdrVividBox.count(currentAtom.type)) {
5258 lastTrack_->codecParms.hdrBoxInfo.haveHdrVividBox = true;5345 lastTrack_->codecParms.hdrBoxInfo.haveHdrVividBox = true;
5259- } else if (dbBox.count(currentAtom.type)) {5346+ } else if (currentAtom.type == FourccType("dvcC") || currentAtom.type == FourccType("dvvC") ||
5347+ currentAtom.type == FourccType("dvwC") || currentAtom.type == FourccType("dvh1")) {
5260 lastTrack_->codecParms.hdrBoxInfo.haveHdrDoblyVisionBox = true;5348 lastTrack_->codecParms.hdrBoxInfo.haveHdrDoblyVisionBox = true;
5261 }5349 }
5262}5350}
@@ -5300,10 +5388,9 @@ Status MPEG4AtomParser::MPEG4ParseAtom(int32_t depth, ParseContext* ctx)
5300 5388 
5301auto MPEG4AtomParser::FindAtomParser(const MPEG4Atom& atom, ParseContext* ctx) -> ParseFunction5389auto MPEG4AtomParser::FindAtomParser(const MPEG4Atom& atom, ParseContext* ctx) -> ParseFunction
5302{5390{
5303- // 首先查找静态解析函数表5391+ ParseFunction parser = FindStaticAtomParser(atom.type);
5304- auto it = MPEG4ParseTable_.find(atom.type);5392+ if (parser != nullptr) {
5305- if (it != MPEG4ParseTable_.end()) {5393+ return parser;
5306- return it->second;
5307 }5394 }
5308 // 查找动态解析函数5395 // 查找动态解析函数
5309 if (ctx->path.size() >= DIRECT_META_PATH_SIZE) {5396 if (ctx->path.size() >= DIRECT_META_PATH_SIZE) {
@@ -5372,7 +5459,7 @@ void MPEG4AtomParser::CalculateMPEG4Attributes()
5372 SetHEVCDefaultValue();5459 SetHEVCDefaultValue();
5373}5460}
5374 5461 
5375-void MPEG4AtomParser::SetTrackType(std::shared_ptr<Track> track)5462+void MPEG4AtomParser::SetTrackType(const std::shared_ptr<Track>& track)
5376{5463{
5377 TagType tagType;5464 TagType tagType;
5378 switch (track->codecParms.trackType) {5465 switch (track->codecParms.trackType) {
@@ -5650,7 +5737,7 @@ int64_t MPEG4AtomParser::FindMaxTrackDuration(int64_t& maxDuration, uint32_t& ma
5650 return (maxDuration > 0) ? maxDuration : 0;5737 return (maxDuration > 0) ? maxDuration : 0;
5651}5738}
5652 5739 
5653-double MPEG4AtomParser::CalculateDuration(std::shared_ptr<Track> track, bool isRawFile)5740+double MPEG4AtomParser::CalculateDuration(const std::shared_ptr<Track>& track, bool isRawFile)
5654{5741{
5655 FALSE_RETURN_V_MSG_E(track != nullptr, 0.0, "Track is null");5742 FALSE_RETURN_V_MSG_E(track != nullptr, 0.0, "Track is null");
5656 FALSE_RETURN_V_MSG_E(track->sampleHelper != nullptr, 0.0, "SampleHelper is null");5743 FALSE_RETURN_V_MSG_E(track->sampleHelper != nullptr, 0.0, "SampleHelper is null");
Mservices/media_engine/plugins/demuxer/mpeg4_demuxer/mpeg4_box_parser.h+24-25
@@ -18,8 +18,6 @@
18 18 
19#include <cstdint>19#include <cstdint>
20#include <memory>20#include <memory>
21-#include <set>
22-#include <map>
23#include <string>21#include <string>
24#include "converter.h"22#include "converter.h"
25#include "mpeg4_audio_parser.h"23#include "mpeg4_audio_parser.h"
@@ -179,7 +177,6 @@ private:
179 struct ParseContext {177 struct ParseContext {
180 int64_t offset = 0; // 当前解析位置178 int64_t offset = 0; // 当前解析位置
181 int64_t dataOffset = 0; // 数据偏移位置179 int64_t dataOffset = 0; // 数据偏移位置
182- std::set<uint32_t> compatibleBrands;
183 std::vector<uint32_t> path;180 std::vector<uint32_t> path;
184 std::vector<std::string> metaKeys;181 std::vector<std::string> metaKeys;
185 int32_t movieDisplayMatrix[3][3] = {{0}}; // movie level 3x3显示变换矩阵182 int32_t movieDisplayMatrix[3][3] = {{0}}; // movie level 3x3显示变换矩阵
@@ -189,6 +186,8 @@ private:
189 bool founditunesMetadata = false;186 bool founditunesMetadata = false;
190 bool isUserMeta = false;187 bool isUserMeta = false;
191 bool foundFileMetaHdlrGltf = false;188 bool foundFileMetaHdlrGltf = false;
189+ bool hasQtCompatibleBrand = false;
190+ bool hasGltfCompatibleBrand = false;
192 int64_t fileMetaIdatPayloadOffset = -1;191 int64_t fileMetaIdatPayloadOffset = -1;
193 };192 };
194 ParseContext ctx_;193 ParseContext ctx_;
@@ -215,8 +214,9 @@ private:
215 uint32_t trackCount_ = 0;214 uint32_t trackCount_ = 0;
216 int64_t moofOffset_ = 0;215 int64_t moofOffset_ = 0;
217 using ParseFunction = Status (MPEG4AtomParser::*)(MPEG4Atom atom, int32_t depth, ParseContext* ctx);216 using ParseFunction = Status (MPEG4AtomParser::*)(MPEG4Atom atom, int32_t depth, ParseContext* ctx);
217+ ParseFunction FindStaticAtomParser(int32_t atomType) const;
218+ __attribute__((visibility("hidden"))) ParseFunction FindStaticExtendedAtomParser(int32_t atomType) const;
218 ParseFunction FindAtomParser(const MPEG4Atom& atom, ParseContext* ctx);219 ParseFunction FindAtomParser(const MPEG4Atom& atom, ParseContext* ctx);
219- std::unordered_map<int32_t, ParseFunction> MPEG4ParseTable_;
220 std::vector<FragmentEntry> fragmentEntry_;220 std::vector<FragmentEntry> fragmentEntry_;
221 std::vector<Mpeg4PsshInfo> psshList_;221 std::vector<Mpeg4PsshInfo> psshList_;
222 std::shared_ptr<DataSource> dataSource_ {nullptr};222 std::shared_ptr<DataSource> dataSource_ {nullptr};
@@ -234,9 +234,8 @@ private:
234 MediaInfo mediaInfo_;234 MediaInfo mediaInfo_;
235 Seekable seekable_;235 Seekable seekable_;
236 std::shared_ptr<Meta> userFormat_ = nullptr;236 std::shared_ptr<Meta> userFormat_ = nullptr;
237- void InitParseTable();237+ void SetCodecConfig(const std::shared_ptr<Track>& track);
238- void SetCodecConfig(std::shared_ptr<Track> track);238+ void AdapterFormat(const std::shared_ptr<Track>& track);
239- void AdapterFormat(std::shared_ptr<Track> track);
240 bool IsValidTrackIndex(const MediaInfo& mediaInfo, uint32_t index);239 bool IsValidTrackIndex(const MediaInfo& mediaInfo, uint32_t index);
241 bool IsLastTrackValid();240 bool IsLastTrackValid();
242 bool UnderMetaPath(const std::vector<uint32_t>& path, int32_t depth);241 bool UnderMetaPath(const std::vector<uint32_t>& path, int32_t depth);
@@ -244,40 +243,40 @@ private:
244 void TrySetGltfOffset(ParseContext* ctx);243 void TrySetGltfOffset(ParseContext* ctx);
245 244 
246 // Display matrix 相关辅助函数245 // Display matrix 相关辅助函数
247- void CalculateSampleAspectRatio(std::shared_ptr<Track> track, uint32_t width, uint32_t height);246+ void CalculateSampleAspectRatio(const std::shared_ptr<Track>& track, uint32_t width, uint32_t height);
248- void CalculateSARFromTrackInfo(std::shared_ptr<Track> track);247+ void CalculateSARFromTrackInfo(const std::shared_ptr<Track>& track);
249- void SetTrackDisplayMatrix(std::shared_ptr<Track> track, const int32_t resultMatrix[3][3],248+ void SetTrackDisplayMatrix(const std::shared_ptr<Track>& track, const int32_t resultMatrix[3][3],
250 uint32_t width, uint32_t height, const size_t len);249 uint32_t width, uint32_t height, const size_t len);
251 Status ParseDisplayMatrix(const uint8_t* data, int32_t matrix[3][3]);250 Status ParseDisplayMatrix(const uint8_t* data, int32_t matrix[3][3]);
252 // 视频方向解析相关辅助函数251 // 视频方向解析相关辅助函数
253- void ParseOrientationFromMatrix(std::shared_ptr<Track> track);252+ void ParseOrientationFromMatrix(const std::shared_ptr<Track>& track);
254- void ParseRotationTypeFromMatrix(std::shared_ptr<Track> track);253+ void ParseRotationTypeFromMatrix(const std::shared_ptr<Track>& track);
255- void ParseImageTrackData(std::shared_ptr<Track> track);254+ void ParseImageTrackData(const std::shared_ptr<Track>& track);
256 // 计算流信息相关辅助函数255 // 计算流信息相关辅助函数
257- void CalculateVideoFrameRate(std::shared_ptr<Track> track);256+ void CalculateVideoFrameRate(const std::shared_ptr<Track>& track);
258- void CalculateTrackBitrates(std::shared_ptr<Track> track);257+ void CalculateTrackBitrates(const std::shared_ptr<Track>& track);
259 int64_t GetBitrateDuration(const std::shared_ptr<Track>& track);258 int64_t GetBitrateDuration(const std::shared_ptr<Track>& track);
260 int64_t GetBitrateTotalSize(const std::shared_ptr<Track>& track);259 int64_t GetBitrateTotalSize(const std::shared_ptr<Track>& track);
261 bool HasEnoughSamplesForBitrate(const std::shared_ptr<Track>& track, const std::string& mime);260 bool HasEnoughSamplesForBitrate(const std::shared_ptr<Track>& track, const std::string& mime);
262- bool GetBitrateDurationAndSize(std::shared_ptr<Track> track, int64_t& duration, int64_t& totalSize);261+ bool GetBitrateDurationAndSize(const std::shared_ptr<Track>& track, int64_t& duration, int64_t& totalSize);
263- void CalculateVideoDelay(std::shared_ptr<Track> track);262+ void CalculateVideoDelay(const std::shared_ptr<Track>& track);
264- void NormalizeAudioAttributes(std::shared_ptr<Track> track);263+ void NormalizeAudioAttributes(const std::shared_ptr<Track>& track);
265 AudioSampleFormat GetAv3aSampleFormat(int32_t bitsPerRawSample) const;264 AudioSampleFormat GetAv3aSampleFormat(int32_t bitsPerRawSample) const;
266 AudioChannelLayout GetAv3aChannelLayout(int32_t channelCount, int32_t sampleRate) const;265 AudioChannelLayout GetAv3aChannelLayout(int32_t channelCount, int32_t sampleRate) const;
267 void CalculateMPEG4Attributes();266 void CalculateMPEG4Attributes();
268- void SetTrackType(std::shared_ptr<Track> track);267+ void SetTrackType(const std::shared_ptr<Track>& track);
269 void SetFileDuration();268 void SetFileDuration();
270 void UpdateTrackStartTime(const std::shared_ptr<Track>& track, int64_t& trackStartTime,269 void UpdateTrackStartTime(const std::shared_ptr<Track>& track, int64_t& trackStartTime,
271 int64_t& containerStartTimeForTrack);270 int64_t& containerStartTimeForTrack);
272 void SetStartTime();271 void SetStartTime();
273 void SetHEVCDefaultValue();272 void SetHEVCDefaultValue();
274- int64_t GetElstDuration(std::shared_ptr<Track> track);273+ int64_t GetElstDuration(const std::shared_ptr<Track>& track);
275 int64_t GetMpeg4FileDuration();274 int64_t GetMpeg4FileDuration();
276- int64_t GetTrackDuration(std::shared_ptr<Track> track, bool calculateBitrate = false);275+ int64_t GetTrackDuration(const std::shared_ptr<Track>& track, bool calculateBitrate = false);
277 int64_t GetSidxTrackStartTime(const std::shared_ptr<Track>& track, int64_t containerStartTime);276 int64_t GetSidxTrackStartTime(const std::shared_ptr<Track>& track, int64_t containerStartTime);
278 int64_t GetSidxSampleEndTime(const std::shared_ptr<Track>& track, int32_t timeScale);277 int64_t GetSidxSampleEndTime(const std::shared_ptr<Track>& track, int32_t timeScale);
279 int64_t FindMaxTrackDuration(int64_t& maxDuration, uint32_t& maxDurationTrackIndex);278 int64_t FindMaxTrackDuration(int64_t& maxDuration, uint32_t& maxDurationTrackIndex);
280- double CalculateDuration(std::shared_ptr<Track> track, bool isRawFile);279+ double CalculateDuration(const std::shared_ptr<Track>& track, bool isRawFile);
281 // 元数据解析辅助函数280 // 元数据解析辅助函数
282 std::string ConvertLanguageCode(uint16_t langcode);281 std::string ConvertLanguageCode(uint16_t langcode);
283 std::string GetMetadataKey(uint32_t atomType, ParseContext* ctx);282 std::string GetMetadataKey(uint32_t atomType, ParseContext* ctx);
@@ -343,7 +342,7 @@ private:
343 Status ReadMetadataString(std::string& key, int64_t offset, uint64_t size, uint32_t dataType, bool isUserMeta);342 Status ReadMetadataString(std::string& key, int64_t offset, uint64_t size, uint32_t dataType, bool isUserMeta);
344 Status SetMetadata(std::string& key, uint8_t* buffer, uint64_t size, uint32_t dataType);343 Status SetMetadata(std::string& key, uint8_t* buffer, uint64_t size, uint32_t dataType);
345 Status ParseDca3Entry(MPEG4Atom currentAtom, ParseContext* ctx);344 Status ParseDca3Entry(MPEG4Atom currentAtom, ParseContext* ctx);
346- Status ParseColorParams(int64_t offset, uint64_t dataSize, const std::string& colorType, ParseContext* parseCtx);345+ Status ParseColorParams(int64_t offset, uint64_t dataSize, uint32_t colorType, ParseContext* parseCtx);
347 std::shared_ptr<Track> FindSidxTrack(uint32_t referenceId);346 std::shared_ptr<Track> FindSidxTrack(uint32_t referenceId);
348 void CheckSidxReferenceEnd();347 void CheckSidxReferenceEnd();
349 Status ReadSidxHeaderInfo(MPEG4Atom currentAtom, ParseContext* ctx, std::unique_ptr<uint8_t[]>& headerInfo,348 Status ReadSidxHeaderInfo(MPEG4Atom currentAtom, ParseContext* ctx, std::unique_ptr<uint8_t[]>& headerInfo,
@@ -351,11 +350,11 @@ private:
351 Status ParseSidxContext(MPEG4Atom currentAtom, ParseContext* ctx, const uint8_t* headerInfo, uint8_t version,350 Status ParseSidxContext(MPEG4Atom currentAtom, ParseContext* ctx, const uint8_t* headerInfo, uint8_t version,
352 uint64_t& entryOffset);351 uint64_t& entryOffset);
353 Status ParseSidxEntries(const uint8_t* headerInfo, uint64_t entryOffset, uint64_t bufferSize,352 Status ParseSidxEntries(const uint8_t* headerInfo, uint64_t entryOffset, uint64_t bufferSize,
354- SidxParseContext& sidxCtx, std::shared_ptr<Track> currentTrack);353+ SidxParseContext& sidxCtx, const std::shared_ptr<Track>& currentTrack);
355 Status GetSidxEntryOffset(uint64_t entryOffset, uint64_t bufferSize, uint32_t index,354 Status GetSidxEntryOffset(uint64_t entryOffset, uint64_t bufferSize, uint32_t index,
356 uint64_t& currentEntryOffset);355 uint64_t& currentEntryOffset);
357 Status ParseSidxEntry(const uint8_t* headerInfo, uint64_t currentEntryOffset, SidxParseContext& sidxCtx,356 Status ParseSidxEntry(const uint8_t* headerInfo, uint64_t currentEntryOffset, SidxParseContext& sidxCtx,
358- std::shared_ptr<Track> currentTrack, uint32_t index);357+ const std::shared_ptr<Track>& currentTrack, uint32_t index);
359 Status FindNextMoof(int64_t& headerOffset, uint32_t& atomSize);358 Status FindNextMoof(int64_t& headerOffset, uint32_t& atomSize);
360 Status UpdateFragmentEntryAndOffset(bool inEntry, uint32_t fragIndex, FragmentEntry& frag,359 Status UpdateFragmentEntryAndOffset(bool inEntry, uint32_t fragIndex, FragmentEntry& frag,
361 int64_t moofOffset, int64_t& currentOffset);360 int64_t moofOffset, int64_t& currentOffset);
Mservices/media_engine/plugins/demuxer/mpeg4_demuxer/mpeg4_demuxer_plugin.cpp+134-90
@@ -17,8 +17,6 @@
17#define HST_LOG_TAG "MPEG4DemuxerPlugin"17#define HST_LOG_TAG "MPEG4DemuxerPlugin"
18#include <algorithm>18#include <algorithm>
19#include <string>19#include <string>
20-#include <sstream>
21-#include <iomanip>
22#include <fstream>20#include <fstream>
23#include <limits>21#include <limits>
24 22 
@@ -37,8 +35,6 @@
37#include "xcollie/xcollie.h"35#include "xcollie/xcollie.h"
38#include "xcollie/xcollie_define.h"36#include "xcollie/xcollie_define.h"
39 37 
40-constexpr uint32_t HEX_CHARS_PER_BYTE = 2;
41- 
42namespace {38namespace {
43constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_DOMAIN_DEMUXER, "MPEG4DemuxerPlugin" };39constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_DOMAIN_DEMUXER, "MPEG4DemuxerPlugin" };
44}40}
@@ -60,21 +56,48 @@ constexpr int32_t READ_LEN = 8;
60constexpr int32_t MIN_ATOM_SIZE = 16;56constexpr int32_t MIN_ATOM_SIZE = 16;
61constexpr int64_t SNIFF_DATA_SIZE = 2048;57constexpr int64_t SNIFF_DATA_SIZE = 2048;
62 58 
63-static const std::set<SeekMode> g_seekMode = {59+bool GetVideoStreamType(const std::string& mime, VideoStreamType& streamType)
64- SeekMode::SEEK_PREVIOUS_SYNC,
65- SeekMode::SEEK_NEXT_SYNC,
66- SeekMode::SEEK_CLOSEST_SYNC,
67-};
68- 
69-static const std::map<std::string, VideoStreamType> g_streamParserMap = {
70- { "video/avc", VideoStreamType::AVC },
71- { "video/hevc", VideoStreamType::HEVC },
72- { "video/vvc", VideoStreamType::VVC },
73-};
74- 
75-bool HaveValidParser(const std::string mime)
76{60{
77- return g_streamParserMap.count(mime) != 0;61+ if (mime == MimeType::VIDEO_AVC) {
62+ streamType = VideoStreamType::AVC;
63+ return true;
64+ }
65+ if (mime == MimeType::VIDEO_HEVC) {
66+ streamType = VideoStreamType::HEVC;
67+ return true;
68+ }
69+ if (mime == MimeType::VIDEO_VVC) {
70+ streamType = VideoStreamType::VVC;
71+ return true;
72+ }
73+ return false;
74+}
75+ 
76+bool HaveValidParser(const std::string& mime)
77+{
78+ VideoStreamType streamType = VideoStreamType::AVC;
79+ return GetVideoStreamType(mime, streamType);
80+}
81+ 
82+bool IsSupportedSeekMode(SeekMode mode)
83+{
84+ return mode == SeekMode::SEEK_PREVIOUS_SYNC || mode == SeekMode::SEEK_NEXT_SYNC ||
85+ mode == SeekMode::SEEK_CLOSEST_SYNC;
86+}
87+ 
88+std::string BytesToHexString(const uint8_t* data, size_t size)
89+{
90+ constexpr size_t hexCharsPerByte = 2;
91+ constexpr uint8_t bitsPerHexDigit = 4;
92+ constexpr uint8_t lowNibbleMask = 0x0F;
93+ constexpr char hexDigits[] = "0123456789abcdef";
94+ std::string result(size * hexCharsPerByte, '0');
95+ for (size_t index = 0; index < size; ++index) {
96+ size_t outputIndex = index * hexCharsPerByte;
97+ result[outputIndex] = hexDigits[data[index] >> bitsPerHexDigit];
98+ result[outputIndex + 1] = hexDigits[data[index] & lowNibbleMask];
99+ }
100+ return result;
78}101}
79 102 
80bool NeedReadPostProcessing(const std::string& mime)103bool NeedReadPostProcessing(const std::string& mime)
@@ -1025,18 +1048,18 @@ int Sniff(const std::string& pluginName, std::shared_ptr<DataSource> dataSource)
1025 1048 
1026Status RegisterMpeg4Plugin(const std::shared_ptr<Register>& reg);1049Status RegisterMpeg4Plugin(const std::shared_ptr<Register>& reg);
1027 1050 
1028-static const std::vector<TrackType> g_streamMediaTypeVec = {
1029- AUDIO_TYPE,
1030- VIDEO_TYPE,
1031- SUBTITLE_TYPE,
1032- TIMEDMETA_TYPE,
1033- AUXILIARY_TYPE,
1034-};
1035- 
1036bool IsSupportedTrackType(const std::shared_ptr<MPEG4AtomParser::Track>& track)1051bool IsSupportedTrackType(const std::shared_ptr<MPEG4AtomParser::Track>& track)
1037{1052{
1038- return (std::find(g_streamMediaTypeVec.cbegin(), g_streamMediaTypeVec.cend(),1053+ switch (track->codecParms.trackType) {
1039- track->codecParms.trackType) != g_streamMediaTypeVec.cend());1054+ case AUDIO_TYPE:
1055+ case VIDEO_TYPE:
1056+ case SUBTITLE_TYPE:
1057+ case TIMEDMETA_TYPE:
1058+ case AUXILIARY_TYPE:
1059+ return true;
1060+ default:
1061+ return false;
1062+ }
1040}1063}
1041 1064 
1042bool IsSupportedTrack(const std::shared_ptr<MPEG4AtomParser::Track>& track)1065bool IsSupportedTrack(const std::shared_ptr<MPEG4AtomParser::Track>& track)
@@ -1229,33 +1252,27 @@ Status MPEG4DemuxerPlugin::Flush()
1229 return Status::OK;1252 return Status::OK;
1230}1253}
1231 1254 
1232-void MPEG4DemuxerPlugin::InitBaseInfoByAtomParser(std::shared_ptr<MPEG4AtomParser> parser)1255+void MPEG4DemuxerPlugin::InitBaseInfoByAtomParser(MPEG4AtomParser& parser)
1233{1256{
1234- mediaInfo_ = parser->GetMediaInfo();1257+ mediaInfo_ = parser.GetMediaInfo();
1235- movieTimeScale_ = parser->GetMovieTimeScale();1258+ movieTimeScale_ = parser.GetMovieTimeScale();
1236- firstTrack_ = parser->GetFirstTrack();1259+ firstTrack_ = parser.GetFirstTrack();
1237- userformat_ = parser->GetUserFormat();1260+ userformat_ = parser.GetUserFormat();
1238- hasSidxBox_ = parser->GetHasSidx();1261+ hasSidxBox_ = parser.GetHasSidx();
1239- hasMoofBox_ = parser->GetHasMoof();1262+ hasMoofBox_ = parser.GetHasMoof();
1240 fragmentEntry_.clear();1263 fragmentEntry_.clear();
1241- parser->GetFragmentEntry(fragmentEntry_);1264+ parser.GetFragmentEntry(fragmentEntry_);
1242 mediaInfo_.general.Set<Tag::MEDIA_TRACK_COUNT>(CountTracks());1265 mediaInfo_.general.Set<Tag::MEDIA_TRACK_COUNT>(CountTracks());
1243}1266}
1244 1267 
1245-void MPEG4DemuxerPlugin::InitDrmInfoCacheByAtomParser(std::shared_ptr<MPEG4AtomParser> parser)1268+void MPEG4DemuxerPlugin::InitDrmInfoCacheByAtomParser(MPEG4AtomParser& parser)
1246{1269{
1247 std::lock_guard<std::mutex> drmLock(cachedDrmInfoMutex_);1270 std::lock_guard<std::mutex> drmLock(cachedDrmInfoMutex_);
1248 cachedDrmInfo_.clear();1271 cachedDrmInfo_.clear();
1249- const auto& psshList = parser->GetPsshList();1272+ const auto& psshList = parser.GetPsshList();
1250 for (const auto& pssh : psshList) {1273 for (const auto& pssh : psshList) {
1251 if (pssh.uuidLen == PSSH_UUID_SIZE) {1274 if (pssh.uuidLen == PSSH_UUID_SIZE) {
1252- std::stringstream ss;1275+ cachedDrmInfo_.emplace(BytesToHexString(pssh.uuid, pssh.uuidLen), pssh.psshData);
1253- for (uint32_t i = 0; i < pssh.uuidLen; ++i) {
1254- ss << std::hex << std::setfill('0') << std::setw(HEX_CHARS_PER_BYTE)
1255- << static_cast<int32_t>(pssh.uuid[i]);
1256- }
1257- //ss.str() is uuid
1258- cachedDrmInfo_.emplace(ss.str(), pssh.psshData);
1259 }1276 }
1260 }1277 }
1261 drmInfoCached_.store(!cachedDrmInfo_.empty());1278 drmInfoCached_.store(!cachedDrmInfo_.empty());
@@ -1300,7 +1317,7 @@ Status MPEG4DemuxerPlugin::SetDataSource(const std::shared_ptr<DataSource>& sour
1300 MEDIA_LOG_I("DemuxerMode: " PUBLIC_LOG_U32, static_cast<uint32_t>(demuxerMode_));1317 MEDIA_LOG_I("DemuxerMode: " PUBLIC_LOG_U32, static_cast<uint32_t>(demuxerMode_));
1301 }1318 }
1302 Status ret = Status::OK;1319 Status ret = Status::OK;
1303- auto atomParser = std::make_shared<MPEG4AtomParser>();1320+ auto atomParser = std::make_unique<MPEG4AtomParser>();
1304 FALSE_RETURN_V_MSG_E(atomParser != nullptr, Status::ERROR_NO_MEMORY, "parser allocation failed");1321 FALSE_RETURN_V_MSG_E(atomParser != nullptr, Status::ERROR_NO_MEMORY, "parser allocation failed");
1305 {1322 {
1306 auto id = HiviewDFX::XCollie::GetInstance().SetTimer("av_codec::demuxer_setdatasource", SETTIMER_TIMEOUT,1323 auto id = HiviewDFX::XCollie::GetInstance().SetTimer("av_codec::demuxer_setdatasource", SETTIMER_TIMEOUT,
@@ -1312,8 +1329,8 @@ Status MPEG4DemuxerPlugin::SetDataSource(const std::shared_ptr<DataSource>& sour
1312 HiviewDFX::XCollie::GetInstance().CancelTimer(id);1329 HiviewDFX::XCollie::GetInstance().CancelTimer(id);
1313 }1330 }
1314 1331 
1315- InitBaseInfoByAtomParser(atomParser);1332+ InitBaseInfoByAtomParser(*atomParser);
1316- InitDrmInfoCacheByAtomParser(atomParser);1333+ InitDrmInfoCacheByAtomParser(*atomParser);
1317 ret = PrepareTrackMetadata();1334 ret = PrepareTrackMetadata();
1318 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "PrepareTrackMetadata failed");1335 FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "PrepareTrackMetadata failed");
1319 1336 
@@ -1402,8 +1419,9 @@ void MPEG4DemuxerPlugin::InitStreamParsers()
1402 for (uint32_t trackIndex = 0; track != nullptr; ++trackIndex) {1419 for (uint32_t trackIndex = 0; track != nullptr; ++trackIndex) {
1403 std::string mime;1420 std::string mime;
1404 mediaInfo_.tracks[trackIndex].Get<Tag::MIME_TYPE>(mime);1421 mediaInfo_.tracks[trackIndex].Get<Tag::MIME_TYPE>(mime);
1405- if (HaveValidParser(mime) && streamParsers_ != nullptr) {1422+ VideoStreamType streamType = VideoStreamType::AVC;
1406- Status ret = streamParsers_->Create(trackIndex, g_streamParserMap.at(mime));1423+ if (GetVideoStreamType(mime, streamType) && streamParsers_ != nullptr) {
1424+ Status ret = streamParsers_->Create(trackIndex, streamType);
1407 if (ret != Status::OK) {1425 if (ret != Status::OK) {
1408 MEDIA_LOG_W("Init parser failed, track " PUBLIC_LOG_U32 ", mime " PUBLIC_LOG_S,1426 MEDIA_LOG_W("Init parser failed, track " PUBLIC_LOG_U32 ", mime " PUBLIC_LOG_S,
1409 trackIndex, mime.c_str());1427 trackIndex, mime.c_str());
@@ -1462,9 +1480,7 @@ Status MPEG4DemuxerPlugin::ParseAVFirstFrames()
1462 1480 
1463 // Process audio track1481 // Process audio track
1464 if (IsAudioType(*currentTrack)) {1482 if (IsAudioType(*currentTrack)) {
1465- auto audioParser = std::make_shared<MPEG4AudioParser>();1483+ ret = MPEG4AudioParser::ParseAudioFrame(mpeg4Sample->sample->data.get(), mpeg4Sample->sample->size,
1466- FALSE_RETURN_V_MSG_E(audioParser != nullptr, Status::ERROR_NO_MEMORY, "Failed create audioParser");
1467- ret = audioParser->ParseAudioFrame(mpeg4Sample->sample->data.get(), mpeg4Sample->sample->size,
1468 currentTrack->sampleHelper->mimeType_, avTrackId, mediaInfo_);1484 currentTrack->sampleHelper->mimeType_, avTrackId, mediaInfo_);
1469 FALSE_CONTINUE_LOGD(ret == Status::OK, "Parse audio failed in track:" PUBLIC_LOG_U32, avTrackId);1485 FALSE_CONTINUE_LOGD(ret == Status::OK, "Parse audio failed in track:" PUBLIC_LOG_U32, avTrackId);
1470 }1486 }
@@ -1755,8 +1771,7 @@ void MPEG4DemuxerPlugin::ConvertCsdToAnnexb(const MPEG4AtomParser::Track& track,
1755 streamParsers_->ConvertPacketToAnnexb(trackIndex, &extradata, extradataSize, convertInfo);1771 streamParsers_->ConvertPacketToAnnexb(trackIndex, &extradata, extradataSize, convertInfo);
1756 }1772 }
1757 if (extradata != nullptr && extradataSize > 0) {1773 if (extradata != nullptr && extradataSize > 0) {
1758- std::vector<uint8_t> extra(extradataSize);1774+ std::vector<uint8_t> extra(extradata, extradata + extradataSize);
1759- extra.assign(extradata, extradata + extradataSize);
1760 format.Set<Tag::MEDIA_CODEC_CONFIG>(extra);1775 format.Set<Tag::MEDIA_CODEC_CONFIG>(extra);
1761 }1776 }
1762}1777}
@@ -1965,7 +1980,8 @@ Status MPEG4DemuxerPlugin::FindBaseTrackAndCalcDelay(int64_t seekTime, SeekMode
1965}1980}
1966 1981 
1967// LCOV_EXCL_START1982// LCOV_EXCL_START
1968-Status MPEG4DemuxerPlugin::FindFragmentSyncSample(uint32_t fragmentIndex, std::shared_ptr<MPEG4AtomParser::Track> track)1983+Status MPEG4DemuxerPlugin::FindFragmentSyncSample(uint32_t fragmentIndex,
1984+ const std::shared_ptr<MPEG4AtomParser::Track>& track)
1969{1985{
1970 int64_t moofOffset = fragmentEntry_[fragmentIndex].moofOffset;1986 int64_t moofOffset = fragmentEntry_[fragmentIndex].moofOffset;
1971 for (const auto& selectedTrackId : selectedTrackIds_) {1987 for (const auto& selectedTrackId : selectedTrackIds_) {
@@ -1983,7 +1999,7 @@ Status MPEG4DemuxerPlugin::FindFragmentSyncSample(uint32_t fragmentIndex, std::s
1983}1999}
1984 2000 
1985Status MPEG4DemuxerPlugin::FindFragmentAtTime(int64_t fragmentSeekTime, SeekMode flag,2001Status MPEG4DemuxerPlugin::FindFragmentAtTime(int64_t fragmentSeekTime, SeekMode flag,
1986- std::shared_ptr<MPEG4AtomParser::Track> track, bool &findFragmentSync)2002+ const std::shared_ptr<MPEG4AtomParser::Track>& track, bool &findFragmentSync)
1987{2003{
1988 FALSE_RETURN_V_NOLOG(fragmentSeekTime >= fragmentEntry_.front().firstDts, Status::OK);2004 FALSE_RETURN_V_NOLOG(fragmentSeekTime >= fragmentEntry_.front().firstDts, Status::OK);
1989 FALSE_RETURN_V_NOLOG(fragmentSeekTime <= fragmentEntry_.back().firstDts + fragmentEntry_.back().duration,2005 FALSE_RETURN_V_NOLOG(fragmentSeekTime <= fragmentEntry_.back().firstDts + fragmentEntry_.back().duration,
@@ -2262,7 +2278,7 @@ Status MPEG4DemuxerPlugin::CheckSeekParams(int64_t seekTime, SeekMode mode) cons
2262 FALSE_RETURN_V_MSG_E(!selectedTrackIds_.empty(), Status::ERROR_INVALID_OPERATION, "No track has been selected");2278 FALSE_RETURN_V_MSG_E(!selectedTrackIds_.empty(), Status::ERROR_INVALID_OPERATION, "No track has been selected");
2263 FALSE_RETURN_V_MSG_E(seekTime >= 0 && seekTime <= INT64_MAX / MS_TO_NS,2279 FALSE_RETURN_V_MSG_E(seekTime >= 0 && seekTime <= INT64_MAX / MS_TO_NS,
2264 Status::ERROR_INVALID_PARAMETER, "Seek time " PUBLIC_LOG_D64 " is not supported", seekTime);2280 Status::ERROR_INVALID_PARAMETER, "Seek time " PUBLIC_LOG_D64 " is not supported", seekTime);
2265- FALSE_RETURN_V_MSG_E(g_seekMode.find(mode) != g_seekMode.end(),2281+ FALSE_RETURN_V_MSG_E(IsSupportedSeekMode(mode),
2266 Status::ERROR_INVALID_PARAMETER,2282 Status::ERROR_INVALID_PARAMETER,
2267 "Seek mode " PUBLIC_LOG_U32 " is not supported", static_cast<uint32_t>(mode));2283 "Seek mode " PUBLIC_LOG_U32 " is not supported", static_cast<uint32_t>(mode));
2268 return Status::OK;2284 return Status::OK;
@@ -2275,7 +2291,7 @@ Status MPEG4DemuxerPlugin::SeekTo(int32_t trackId, int64_t seekTime, SeekMode mo
2275 2291 
2276 Status check = CheckSeekParams(seekTime, mode);2292 Status check = CheckSeekParams(seekTime, mode);
2277 FALSE_RETURN_V_MSG_E(check == Status::OK, check, "CheckSeekParams failed");2293 FALSE_RETURN_V_MSG_E(check == Status::OK, check, "CheckSeekParams failed");
2278- FALSE_RETURN_V_MSG_E(CheckSeekTimeInFileDuration(mediaInfo_, seekTime), Status::ERROR_INVALID_PARAMETER,2294+ FALSE_RETURN_V_MSG_E(CheckSeekTimeInFileDuration(mediaInfo_, seekTime), Status::ERROR_INVALID_OPERATION,
2279 "Seek time out of file duration");2295 "Seek time out of file duration");
2280 2296 
2281 Status denseRet = EnsureSelectedTracksDense();2297 Status denseRet = EnsureSelectedTracksDense();
@@ -3178,7 +3194,7 @@ void IsMPEGPS(int64_t offset, int64_t kMaxOffset, const std::shared_ptr<DemuxerD
3178 }3194 }
3179}3195}
3180 3196 
3181-int32_t GetFtypConfidence(std::shared_ptr<DemuxerDataReader> dataReader_,3197+int32_t GetFtypConfidence(const std::shared_ptr<DemuxerDataReader>& dataReader_,
3182 int64_t chunkDataOffset, int64_t chunkDataSize, int32_t confidence)3198 int64_t chunkDataOffset, int64_t chunkDataSize, int32_t confidence)
3183{3199{
3184 const int32_t readLengHalf = 4;3200 const int32_t readLengHalf = 4;
@@ -3212,7 +3228,8 @@ int32_t GetFtypConfidence(std::shared_ptr<DemuxerDataReader> dataReader_,
3212}3228}
3213 3229 
3214bool UpdateAtomSize(3230bool UpdateAtomSize(
3215- AtomInfo& atom, int64_t offset, int64_t& chunkDataOffset, std::shared_ptr<DemuxerDataReader> dataReader)3231+ AtomInfo& atom, int64_t offset, int64_t& chunkDataOffset,
3232+ const std::shared_ptr<DemuxerDataReader>& dataReader)
3216{3233{
3217 if (atom.size == 1) {3234 if (atom.size == 1) {
3218 uint8_t sizeData[8];3235 uint8_t sizeData[8];
@@ -3261,7 +3278,58 @@ AtomLevel GetAtomLevel(AtomInfo atom)
3261 }3278 }
3262}3279}
3263 3280 
3264-int32_t GetConfidence(std::shared_ptr<DemuxerDataReader> dataReader)3281+struct ConfidenceUpdateResult {
3282+ bool shouldReturn = false;
3283+ int32_t value = 0;
3284+};
3285+ 
3286+struct ConfidenceUpdateContext {
3287+ int64_t offset;
3288+ int64_t chunkDataOffset;
3289+ int64_t chunkDataSize;
3290+ MoovInfo& moov;
3291+ int32_t& confidence;
3292+};
3293+ 
3294+ConfidenceUpdateResult UpdateConfidenceByAtom(const std::shared_ptr<DemuxerDataReader>& dataReader,
3295+ const AtomInfo& atom, ConfidenceUpdateContext& context)
3296+{
3297+ switch (GetAtomLevel(atom)) {
3298+ case AtomLevel::LEVEL_0: {
3299+ if (atom.size >= MPEG4_MAX_BOX_DATA_SIZE) {
3300+ MEDIA_LOG_E("atom data size too large");
3301+ return {true, 0};
3302+ }
3303+ int32_t originalConfidence = context.confidence;
3304+ context.confidence = GetFtypConfidence(dataReader, context.chunkDataOffset,
3305+ context.chunkDataSize, context.confidence);
3306+ return {context.confidence != FIRST_LEVEL_RANK || context.confidence == originalConfidence,
3307+ context.confidence};
3308+ }
3309+ case AtomLevel::LEVEL_1:
3310+ return {true, FIRST_LEVEL_RANK};
3311+ case AtomLevel::LEVEL_2:
3312+ if (__builtin_add_overflow(context.offset, atom.size, &context.moov.endOffset)) {
3313+ MEDIA_LOG_E("Add overflow");
3314+ return {true, 0};
3315+ }
3316+ context.moov.offset = context.offset + sizeof(atom.type);
3317+ context.moov.found = true;
3318+ context.confidence = FIRST_LEVEL_RANK;
3319+ break;
3320+ case AtomLevel::LEVEL_3:
3321+ context.confidence = std::max(context.confidence, SECOND_LEVEL_RANK);
3322+ break;
3323+ case AtomLevel::LEVEL_4:
3324+ context.confidence = std::max(context.confidence, THIRD_LEVEL_RANK);
3325+ break;
3326+ default:
3327+ break;
3328+ }
3329+ return {false, context.confidence};
3330+}
3331+ 
3332+int32_t GetConfidence(const std::shared_ptr<DemuxerDataReader>& dataReader)
3265{3333{
3266 MoovInfo moov {false, -1, -1};3334 MoovInfo moov {false, -1, -1};
3267 int64_t offset = 0;3335 int64_t offset = 0;
@@ -3279,34 +3347,10 @@ int32_t GetConfidence(std::shared_ptr<DemuxerDataReader> dataReader)
3279 FALSE_RETURN_V_MSG_E((!isFirstAtom || atom.type == static_cast<uint32_t>(FourccType("ftyp"))),3347 FALSE_RETURN_V_MSG_E((!isFirstAtom || atom.type == static_cast<uint32_t>(FourccType("ftyp"))),
3280 0, "no ftyp atom");3348 0, "no ftyp atom");
3281 isFirstAtom = false;3349 isFirstAtom = false;
3282- switch (GetAtomLevel(atom)) {3350+ ConfidenceUpdateContext updateContext {offset, chunkDataOffset, chunkDataSize, moov, confidence};
3283- case AtomLevel::LEVEL_0: {3351+ ConfidenceUpdateResult updateResult = UpdateConfidenceByAtom(dataReader, atom, updateContext);
3284- int32_t originalConfidence = confidence;3352+ if (updateResult.shouldReturn) {
3285- FALSE_RETURN_V_MSG_E(atom.size < MPEG4_MAX_BOX_DATA_SIZE, 0, "atom data size too large");3353+ return updateResult.value;
3286- confidence = GetFtypConfidence(dataReader, chunkDataOffset, chunkDataSize, confidence);
3287- FALSE_RETURN_V_NOLOG(!(confidence != FIRST_LEVEL_RANK || confidence == originalConfidence), confidence);
3288- break;
3289- }
3290- case AtomLevel::LEVEL_1: {
3291- return FIRST_LEVEL_RANK;
3292- }
3293- case AtomLevel::LEVEL_2: {
3294- FALSE_RETURN_V_MSG_E(!(__builtin_add_overflow(offset, atom.size, &moov.endOffset)), 0, "Add overflow");
3295- moov.offset = offset + sizeof(atom.type);
3296- moov.found = true;
3297- confidence = FIRST_LEVEL_RANK;
3298- break;
3299- }
3300- case AtomLevel::LEVEL_3: {
3301- confidence = std::max(confidence, SECOND_LEVEL_RANK);
3302- break;
3303- }
3304- case AtomLevel::LEVEL_4: {
3305- confidence = std::max(confidence, THIRD_LEVEL_RANK);
3306- break;
3307- }
3308- default:
3309- break;
3310 }3354 }
3311 FALSE_RETURN_V_MSG_E(!(__builtin_add_overflow(offset, atom.size, &offset)), 0, "Add overflow");3355 FALSE_RETURN_V_MSG_E(!(__builtin_add_overflow(offset, atom.size, &offset)), 0, "Add overflow");
3312 }3356 }
Mservices/media_engine/plugins/demuxer/mpeg4_demuxer/mpeg4_demuxer_plugin.h+6-4
@@ -243,8 +243,8 @@ private:
243 Status PrepareTrackMetadata();243 Status PrepareTrackMetadata();
244 244
245 void InitStreamParsers();245 void InitStreamParsers();
246- void InitBaseInfoByAtomParser(std::shared_ptr<MPEG4AtomParser> parser);246+ void InitBaseInfoByAtomParser(MPEG4AtomParser& parser);
247- void InitDrmInfoCacheByAtomParser(std::shared_ptr<MPEG4AtomParser> parser);247+ void InitDrmInfoCacheByAtomParser(MPEG4AtomParser& parser);
248 bool TrackIsSelected(const uint32_t trackId);248 bool TrackIsSelected(const uint32_t trackId);
249 std::shared_ptr<MPEG4AtomParser::Track> FindTrackById(int32_t trackId);249 std::shared_ptr<MPEG4AtomParser::Track> FindTrackById(int32_t trackId);
250 250 
@@ -258,8 +258,10 @@ private:
258 Status UpdateDynamicBaseTrack(const std::shared_ptr<MPEG4AtomParser::Track>& track, uint32_t trackId,258 Status UpdateDynamicBaseTrack(const std::shared_ptr<MPEG4AtomParser::Track>& track, uint32_t trackId,
259 int64_t seekTime, DynamicBaseTrackState& state);259 int64_t seekTime, DynamicBaseTrackState& state);
260 Status FindBaseTrackAndCalcDelay(int64_t seekTime, SeekMode mode, int32_t &trackId);260 Status FindBaseTrackAndCalcDelay(int64_t seekTime, SeekMode mode, int32_t &trackId);
261- Status FindFragmentSyncSample(uint32_t fragmentIndex, std::shared_ptr<MPEG4AtomParser::Track> track);261+ Status FindFragmentSyncSample(uint32_t fragmentIndex,
262- Status FindFragmentAtTime(int64_t reqTime, SeekMode flag, std::shared_ptr<MPEG4AtomParser::Track> track,262+ const std::shared_ptr<MPEG4AtomParser::Track>& track);
263+ Status FindFragmentAtTime(int64_t reqTime, SeekMode flag,
264+ const std::shared_ptr<MPEG4AtomParser::Track>& track,
263 bool &findFragmentSync);265 bool &findFragmentSync);
264 Status FragmentSeek(int64_t seekTime, SeekMode mode, int32_t trackIndex, bool &findFragmentSync);266 Status FragmentSeek(int64_t seekTime, SeekMode mode, int32_t trackIndex, bool &findFragmentSync);
265 struct SeekTimeContext {267 struct SeekTimeContext {
Mservices/media_engine/plugins/demuxer/mpeg4_demuxer/mpeg4_format_checker.cpp+88-63
@@ -12,7 +12,9 @@
12 * See the License for the specific language governing permissions and12 * See the License for the specific language governing permissions and
13 * limitations under the License.13 * limitations under the License.
14 */14 */
15-#include <unordered_set>15+#include <algorithm>
16+#include <array>
17+#include <string_view>
16#include "mpeg4_format_checker.h"18#include "mpeg4_format_checker.h"
17#include "mpeg4_utils.h"19#include "mpeg4_utils.h"
18 20 
@@ -21,10 +23,25 @@ namespace Media {
21namespace Plugins {23namespace Plugins {
22namespace MPEG4 {24namespace MPEG4 {
23 25 
24-using FourccSet = std::unordered_set<int32_t>;26+namespace {
27+template<typename T, size_t N>
28+bool Contains(const std::array<T, N>& values, const T& value)
29+{
30+ return std::find(values.cbegin(), values.cend(), value) != values.cend();
31+}
32+ 
33+struct StringMapping {
34+ std::string_view key;
35+ std::string_view value;
36+};
37+ 
38+struct FourccMimeMapping {
39+ int32_t fourcc;
40+ std::string_view mime;
41+};
25 42 
26// file format43// file format
27-static const FourccSet g_supportedFileBrandsFourcc = {44+constexpr std::array g_supportedFileBrandsFourcc = {
28 FourccType("isom"), FourccType("iso2"), FourccType("iso3"), FourccType("iso4"),45 FourccType("isom"), FourccType("iso2"), FourccType("iso3"), FourccType("iso4"),
29 FourccType("mp41"), FourccType("mp42"),46 FourccType("mp41"), FourccType("mp42"),
30 FourccType("avc1"), FourccType("avc3"),47 FourccType("avc1"), FourccType("avc3"),
@@ -33,7 +50,7 @@ static const FourccSet g_supportedFileBrandsFourcc = {
33 FourccType("M4A "), FourccType("m4a "),50 FourccType("M4A "), FourccType("m4a "),
34};51};
35 52 
36-static const std::vector<std::string> g_supportedFileBrandsPrefixs = {53+constexpr std::array<std::string_view, 14> g_supportedFileBrandsPrefixes = {
37 "isom", "iso2", "iso3", "iso4",54 "isom", "iso2", "iso3", "iso4",
38 "mp41", "mp42",55 "mp41", "mp42",
39 "avc1", "avc3",56 "avc1", "avc3",
@@ -42,7 +59,7 @@ static const std::vector<std::string> g_supportedFileBrandsPrefixs = {
42 "M4A ", "m4a ",59 "M4A ", "m4a ",
43};60};
44 61 
45-static const FourccSet g_unsupportedFileBrandsFourcc = {62+constexpr std::array g_unsupportedFileBrandsFourcc = {
46 FourccType("qt "), FourccType("MSNV"), FourccType("wmf "),63 FourccType("qt "), FourccType("MSNV"), FourccType("wmf "),
47 FourccType("3gp4"), FourccType("3gp5"), FourccType("3gp6"),64 FourccType("3gp4"), FourccType("3gp5"), FourccType("3gp6"),
48 FourccType("3gp7"), FourccType("3gp8"), FourccType("3gp9"),65 FourccType("3gp7"), FourccType("3gp8"), FourccType("3gp9"),
@@ -74,30 +91,30 @@ static const FourccSet g_unsupportedFileBrandsFourcc = {
74};91};
75 92 
76// codec format93// codec format
77-static const FourccSet g_supportedVideoCodecsFourcc = {94+constexpr std::array g_supportedVideoCodecsFourcc = {
78 FourccType("avc1"), FourccType("avc3"),95 FourccType("avc1"), FourccType("avc3"),
79 FourccType("hvc1"), FourccType("hev1"),96 FourccType("hvc1"), FourccType("hev1"),
80 FourccType("vvc1"), FourccType("vvi1"),97 FourccType("vvc1"), FourccType("vvi1"),
81 FourccType("mjpeg"), FourccType("png "), FourccType("bmp "),98 FourccType("mjpeg"), FourccType("png "), FourccType("bmp "),
82};99};
83 100 
84-static const FourccSet g_supportedAudioCodecsFourcc = {101+constexpr std::array g_supportedAudioCodecsFourcc = {
85 FourccType("mp4a"), FourccType(".mp3"), FourccType(".mp2"), FourccType(".mp1"),102 FourccType("mp4a"), FourccType(".mp3"), FourccType(".mp2"), FourccType(".mp1"),
86 FourccType("av3a"), FourccType("samr"), FourccType("sawb"),103 FourccType("av3a"), FourccType("samr"), FourccType("sawb"),
87 0x6D730055,104 0x6D730055,
88};105};
89 106 
90-static const FourccSet g_supportedSubtitleCodecsFourcc = {107+constexpr std::array g_supportedSubtitleCodecsFourcc = {
91 FourccType("wvtt")108 FourccType("wvtt")
92};109};
93 110 
94-static const FourccSet g_supportedAuxlCodecsFourcc = {111+constexpr std::array g_supportedAuxlCodecsFourcc = {
95 FourccType("avc1"), FourccType("avc3"),112 FourccType("avc1"), FourccType("avc3"),
96 FourccType("hvc1"), FourccType("hev1"),113 FourccType("hvc1"), FourccType("hev1"),
97 FourccType("mp4a"), FourccType(".mp3"), FourccType("mebx"),114 FourccType("mp4a"), FourccType(".mp3"), FourccType("mebx"),
98};115};
99 116 
100-static const std::map<std::string, std::string> g_supportedAllCodecName = {117+constexpr std::array<StringMapping, 13> g_supportedAllCodecName = {{
101 {MimeType::VIDEO_AVC, "h264"},118 {MimeType::VIDEO_AVC, "h264"},
102 {MimeType::VIDEO_HEVC, "hevc"},119 {MimeType::VIDEO_HEVC, "hevc"},
103 {MimeType::VIDEO_VVC, "vvc"},120 {MimeType::VIDEO_VVC, "vvc"},
@@ -111,9 +128,9 @@ static const std::map<std::string, std::string> g_supportedAllCodecName = {
111 {MimeType::IMAGE_JPG, "mjpeg"},128 {MimeType::IMAGE_JPG, "mjpeg"},
112 {MimeType::IMAGE_PNG, "png"},129 {MimeType::IMAGE_PNG, "png"},
113 {MimeType::IMAGE_BMP, "bmp"},130 {MimeType::IMAGE_BMP, "bmp"},
114-};131+}};
115 132 
116-static const std::map<int32_t, std::string> g_supportedMimeFourcc = {133+constexpr std::array<FourccMimeMapping, 19> g_supportedMimeFourcc = {{
117 { FourccType("avc1"), MimeType::VIDEO_AVC },134 { FourccType("avc1"), MimeType::VIDEO_AVC },
118 { FourccType("avc3"), MimeType::VIDEO_AVC },135 { FourccType("avc3"), MimeType::VIDEO_AVC },
119 { FourccType("hvc1"), MimeType::VIDEO_HEVC },136 { FourccType("hvc1"), MimeType::VIDEO_HEVC },
@@ -133,35 +150,21 @@ static const std::map<int32_t, std::string> g_supportedMimeFourcc = {
133 { FourccType("mjpeg"), MimeType::IMAGE_JPG },150 { FourccType("mjpeg"), MimeType::IMAGE_JPG },
134 { FourccType("png "), MimeType::IMAGE_PNG },151 { FourccType("png "), MimeType::IMAGE_PNG },
135 { FourccType("bmp "), MimeType::IMAGE_BMP },152 { FourccType("bmp "), MimeType::IMAGE_BMP },
136-};153+}};
137 154 
138-static const std::map<uint8_t, std::string> g_supportedObjectType = {155+constexpr std::array<std::string_view, 3> g_supportImageMimeType = {
139- // 视频编解码器
140- {0x21, MimeType::VIDEO_AVC}, // H.264/AVC
141- {0x23, MimeType::VIDEO_HEVC}, // H.265/HEVC
142- {0x33, MimeType::VIDEO_VVC}, // H.266/VVC (OHOS扩展)
143- // 音频编解码器
144- {0x40, MimeType::AUDIO_AAC}, // MPEG-4 AAC
145- {0x66, MimeType::AUDIO_AAC}, // MPEG-2 AAC Main
146- {0x67, MimeType::AUDIO_AAC}, // MPEG-2 AAC Low Complexity
147- {0x68, MimeType::AUDIO_AAC}, // MPEG-2 AAC SSR
148- {0x69, MimeType::AUDIO_MPEG}, // MPEG-2 Layer 3 (MP3) / MPEG-1 Layer 2 (MP2)
149- {0x6B, MimeType::AUDIO_MPEG}, // MPEG-1 Layer 3 (MP3)
150-};
151- 
152-static const std::vector<std::string_view> g_supportImageMimeType = {
153 MimeType::IMAGE_JPG,156 MimeType::IMAGE_JPG,
154 MimeType::IMAGE_PNG,157 MimeType::IMAGE_PNG,
155 MimeType::IMAGE_BMP,158 MimeType::IMAGE_BMP,
156};159};
157 160 
158-static const std::vector<std::string_view> g_supportVideoMimeType = {161+constexpr std::array<std::string_view, 3> g_supportVideoMimeType = {
159 MimeType::VIDEO_AVC,162 MimeType::VIDEO_AVC,
160 MimeType::VIDEO_HEVC,163 MimeType::VIDEO_HEVC,
161 MimeType::VIDEO_VVC,164 MimeType::VIDEO_VVC,
162};165};
163 166 
164-static const std::vector<std::string_view> g_supportAudioMimeType = {167+constexpr std::array<std::string_view, 5> g_supportAudioMimeType = {
165 MimeType::AUDIO_MPEG,168 MimeType::AUDIO_MPEG,
166 MimeType::AUDIO_AAC,169 MimeType::AUDIO_AAC,
167 MimeType::AUDIO_AVS3DA,170 MimeType::AUDIO_AVS3DA,
@@ -169,30 +172,16 @@ static const std::vector<std::string_view> g_supportAudioMimeType = {
169 MimeType::AUDIO_AMR_WB,172 MimeType::AUDIO_AMR_WB,
170};173};
171 174 
172-static const std::map<TrackType, MediaType> g_supportMediaType = {175+} // namespace
173- {VIDEO_TYPE, MediaType::VIDEO},
174- {AUDIO_TYPE, MediaType::AUDIO},
175- {SUBTITLE_TYPE, MediaType::SUBTITLE},
176- {TIMEDMETA_TYPE, MediaType::TIMEDMETA},
177- {AUXILIARY_TYPE, MediaType::AUXILIARY},
178-};
179- 
180-static const std::vector<TrackType> g_supportMediaInfoType = {
181- TrackType::VIDEO_TYPE,
182- TrackType::AUDIO_TYPE,
183- TrackType::TIMEDMETA_TYPE,
184- TrackType::AUXILIARY_TYPE,
185-};
186- 
187 176 
188bool IsSupportedBrand(int32_t brand)177bool IsSupportedBrand(int32_t brand)
189{178{
190- return g_supportedFileBrandsFourcc.count(brand) > 0;179+ return Contains(g_supportedFileBrandsFourcc, brand);
191}180}
192 181 
193bool IsSupportedBrandPrefix(const std::string& majorBrand)182bool IsSupportedBrandPrefix(const std::string& majorBrand)
194{183{
195- for (const auto& prefix : g_supportedFileBrandsPrefixs) {184+ for (const auto& prefix : g_supportedFileBrandsPrefixes) {
196 if (majorBrand.size() >= prefix.size() && majorBrand.compare(0, prefix.size(), prefix) == 0) {185 if (majorBrand.size() >= prefix.size() && majorBrand.compare(0, prefix.size(), prefix) == 0) {
197 return true;186 return true;
198 }187 }
@@ -202,6 +191,9 @@ bool IsSupportedBrandPrefix(const std::string& majorBrand)
202 191 
203bool IsSupportedBrand(const std::string& brand)192bool IsSupportedBrand(const std::string& brand)
204{193{
194+ if (brand.size() < sizeof(uint32_t)) {
195+ return false;
196+ }
205 uint32_t majorBrandInt = (static_cast<uint32_t>(brand[0]) << 24) |197 uint32_t majorBrandInt = (static_cast<uint32_t>(brand[0]) << 24) |
206 (static_cast<uint32_t>(brand[1]) << 16) |198 (static_cast<uint32_t>(brand[1]) << 16) |
207 (static_cast<uint32_t>(brand[2]) << 8) |199 (static_cast<uint32_t>(brand[2]) << 8) |
@@ -211,27 +203,27 @@ bool IsSupportedBrand(const std::string& brand)
211 203 
212bool IsUnsupportedBrand(int32_t brand)204bool IsUnsupportedBrand(int32_t brand)
213{205{
214- return g_unsupportedFileBrandsFourcc.count(brand) > 0;206+ return Contains(g_unsupportedFileBrandsFourcc, brand);
215}207}
216 208 
217bool IsSupportedVideoCodec(int32_t fourcc)209bool IsSupportedVideoCodec(int32_t fourcc)
218{210{
219- return g_supportedVideoCodecsFourcc.count(fourcc) > 0;211+ return Contains(g_supportedVideoCodecsFourcc, fourcc);
220}212}
221 213 
222bool IsSupportedAudioCodec(int32_t fourcc)214bool IsSupportedAudioCodec(int32_t fourcc)
223{215{
224- return g_supportedAudioCodecsFourcc.count(fourcc) > 0;216+ return Contains(g_supportedAudioCodecsFourcc, fourcc);
225}217}
226 218 
227bool IsSupportedSubtitleCodec(int32_t fourcc)219bool IsSupportedSubtitleCodec(int32_t fourcc)
228{220{
229- return g_supportedSubtitleCodecsFourcc.count(fourcc) > 0;221+ return Contains(g_supportedSubtitleCodecsFourcc, fourcc);
230}222}
231 223 
232bool IsSupportedAuxiliaryCodec(int32_t fourcc)224bool IsSupportedAuxiliaryCodec(int32_t fourcc)
233{225{
234- return g_supportedAuxlCodecsFourcc.count(fourcc) > 0;226+ return Contains(g_supportedAuxlCodecsFourcc, fourcc);
235}227}
236 228 
237bool IsImageMimeType(const std::string& mime)229bool IsImageMimeType(const std::string& mime)
@@ -291,35 +283,68 @@ bool NeedParseAudioInfo(std::string mimeType, TrackType trackType)
291 283 
292bool NeedParseMediaTrackInfo(TrackType trackType)284bool NeedParseMediaTrackInfo(TrackType trackType)
293{285{
294- return (std::find(g_supportMediaInfoType.cbegin(), g_supportMediaInfoType.cend(),286+ return trackType == VIDEO_TYPE || trackType == AUDIO_TYPE ||
295- trackType) != g_supportMediaInfoType.cend());287+ trackType == TIMEDMETA_TYPE || trackType == AUXILIARY_TYPE;
296}288}
297 289 
298std::string GetMimeType(int32_t atomtype)290std::string GetMimeType(int32_t atomtype)
299{291{
300- auto it = g_supportedMimeFourcc.find(atomtype);292+ for (const auto& mapping : g_supportedMimeFourcc) {
301- if (it != g_supportedMimeFourcc.end()) {293+ if (mapping.fourcc == atomtype) {
302- return it->second;294+ return std::string(mapping.mime);
295+ }
303 }296 }
304 return MimeType::INVALID_TYPE;297 return MimeType::INVALID_TYPE;
305}298}
306 299 
307std::string GetMimeTypeByObjectType(uint8_t objectTypeId)300std::string GetMimeTypeByObjectType(uint8_t objectTypeId)
308{301{
309- auto it = g_supportedObjectType.find(objectTypeId);302+ switch (objectTypeId) {
310- return (it != g_supportedObjectType.end()) ? it->second : "";303+ case 0x21:
304+ return MimeType::VIDEO_AVC;
305+ case 0x23:
306+ return MimeType::VIDEO_HEVC;
307+ case 0x33:
308+ return MimeType::VIDEO_VVC;
309+ case 0x40:
310+ case 0x66:
311+ case 0x67:
312+ case 0x68:
313+ return MimeType::AUDIO_AAC;
314+ case 0x69:
315+ case 0x6B:
316+ return MimeType::AUDIO_MPEG;
317+ default:
318+ return "";
319+ }
311}320}
312 321 
313std::string GetCodecName(std::string mimeType)322std::string GetCodecName(std::string mimeType)
314{323{
315- auto it = g_supportedAllCodecName.find(mimeType);324+ for (const auto& mapping : g_supportedAllCodecName) {
316- return (it != g_supportedAllCodecName.end()) ? it->second : "";325+ if (mapping.key == mimeType) {
326+ return std::string(mapping.value);
327+ }
328+ }
329+ return "";
317}330}
318 331 
319MediaType GetMediaType(TrackType trackType)332MediaType GetMediaType(TrackType trackType)
320{333{
321- auto it = g_supportMediaType.find(trackType);334+ switch (trackType) {
322- return (it != g_supportMediaType.end()) ? it->second : MediaType::UNKNOWN;335+ case VIDEO_TYPE:
336+ return MediaType::VIDEO;
337+ case AUDIO_TYPE:
338+ return MediaType::AUDIO;
339+ case SUBTITLE_TYPE:
340+ return MediaType::SUBTITLE;
341+ case TIMEDMETA_TYPE:
342+ return MediaType::TIMEDMETA;
343+ case AUXILIARY_TYPE:
344+ return MediaType::AUXILIARY;
345+ default:
346+ return MediaType::UNKNOWN;
347+ }
323}348}
324} // namespace MPEG4349} // namespace MPEG4
325} // namespace Plugins350} // namespace Plugins
Mservices/media_engine/plugins/demuxer/mpeg4_demuxer/mpeg4_reference_parser.cpp+4-8
@@ -15,14 +15,10 @@
15 15 
16#define MEDIA_PLUGIN16#define MEDIA_PLUGIN
17#include <unistd.h>17#include <unistd.h>
18-#include <algorithm>18+#include <algorithm>
19-#include <malloc.h>19+#include <string>
20-#include <string>20+#include <fstream>
21-#include <sstream>21+#include <chrono>
22-#include <map>
23-#include <fstream>
24-#include <chrono>
25-#include <limits>
26#include <numeric>22#include <numeric>
27 23 
28#include "avcodec_trace.h"24#include "avcodec_trace.h"
Mtest/unittest/mpeg4_demuxer_plugin_test/mpeg4_demuxer_plugin_unit_test.cpp+1-1
@@ -2699,7 +2699,7 @@ HWTEST_F(Mpeg4DemuxerPluginUnitTest, Mpeg4DemuxerPlugin_InitDrmInfoCache_PsshUui
2699 auto invalidPssh = validPssh;2699 auto invalidPssh = validPssh;
2700 invalidPssh.uuidLen = psshUuidSize - 1;2700 invalidPssh.uuidLen = psshUuidSize - 1;
2701 parser->psshList_.push_back(invalidPssh);2701 parser->psshList_.push_back(invalidPssh);
2702- plugin->InitDrmInfoCacheByAtomParser(parser);2702+ plugin->InitDrmInfoCacheByAtomParser(*parser);
2703 2703 
2704 ASSERT_EQ(plugin->cachedDrmInfo_.size(), 1U);2704 ASSERT_EQ(plugin->cachedDrmInfo_.size(), 1U);
2705 auto cachedPssh = plugin->cachedDrmInfo_.find("000102030405060708090a0b0c0d0e0f");2705 auto cachedPssh = plugin->cachedDrmInfo_.find("000102030405060708090a0b0c0d0e0f");