1 /*
2 * Copyright (C) 2025 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "AHAL_OffloadStream"
18 #include <android-base/logging.h>
19
20 #include "ApeHeader.h"
21
22 namespace aidl::android::hardware::audio::core {
23
24 static constexpr uint32_t kApeSignature1 = 0x2043414d; // 'MAC ';
25 static constexpr uint32_t kApeSignature2 = 0x4643414d; // 'MACF';
26 static constexpr uint16_t kMinimumVersion = 3980;
27
findApeHeader(void * buffer,size_t bufferSizeBytes,ApeHeader ** header)28 void* findApeHeader(void* buffer, size_t bufferSizeBytes, ApeHeader** header) {
29 auto advanceBy = [&](size_t bytes) -> void* {
30 buffer = static_cast<uint8_t*>(buffer) + bytes;
31 bufferSizeBytes -= bytes;
32 return buffer;
33 };
34
35 while (bufferSizeBytes >= sizeof(ApeDescriptor) + sizeof(ApeHeader)) {
36 ApeDescriptor* descPtr = static_cast<ApeDescriptor*>(buffer);
37 if (descPtr->signature != kApeSignature1 && descPtr->signature != kApeSignature2) {
38 advanceBy(sizeof(descPtr->signature));
39 continue;
40 }
41 if (descPtr->version < kMinimumVersion) {
42 LOG(ERROR) << __func__ << ": Unsupported APE version: " << descPtr->version
43 << ", minimum supported version: " << kMinimumVersion;
44 // Older versions only have a header, which is of the size similar to the modern header.
45 advanceBy(sizeof(ApeHeader));
46 continue;
47 }
48 if (descPtr->descriptorSizeBytes > bufferSizeBytes) {
49 LOG(ERROR) << __func__
50 << ": Invalid APE descriptor size: " << descPtr->descriptorSizeBytes
51 << ", overruns remaining buffer size: " << bufferSizeBytes;
52 advanceBy(sizeof(ApeDescriptor));
53 continue;
54 }
55 advanceBy(descPtr->descriptorSizeBytes);
56 if (sizeof(ApeHeader) > bufferSizeBytes) {
57 LOG(ERROR) << __func__ << ": APE header is incomplete, want: " << sizeof(ApeHeader)
58 << " bytes, have: " << bufferSizeBytes;
59 return nullptr;
60 }
61 *header = static_cast<ApeHeader*>(buffer);
62 return advanceBy(sizeof(ApeHeader));
63 }
64 return nullptr;
65 }
66
67 } // namespace aidl::android::hardware::audio::core
68