1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "OpusHeader"
19 #include <cstring>
20 #include <inttypes.h>
21 #include <stdint.h>
22 
23 #include <log/log.h>
24 
25 #include "OpusHeader.h"
26 
27 namespace android {
28 
29 // Opus uses Vorbis channel mapping, and Vorbis channel mapping specifies
30 // mappings for up to 8 channels. This information is part of the Vorbis I
31 // Specification:
32 // http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html
33 constexpr int kMaxChannels = 8;
34 
35 constexpr uint8_t kOpusChannelMap[kMaxChannels][kMaxChannels] = {
36         {0},
37         {0, 1},
38         {0, 2, 1},
39         {0, 1, 2, 3},
40         {0, 4, 1, 2, 3},
41         {0, 4, 1, 2, 3, 5},
42         {0, 4, 1, 2, 3, 5, 6},
43         {0, 6, 1, 2, 3, 4, 5, 7},
44 };
45 
46 // Size of the Opus header excluding optional mapping information.
47 constexpr size_t kOpusHeaderSize = 19;
48 // Offset to magic string that starts Opus header.
49 constexpr size_t kOpusHeaderLabelOffset = 0;
50 // Offset to Opus version in the Opus header.
51 constexpr size_t kOpusHeaderVersionOffset = 8;
52 // Offset to the channel count byte in the Opus header.
53 constexpr size_t kOpusHeaderChannelsOffset = 9;
54 // Offset to the pre-skip value in the Opus header.
55 constexpr size_t kOpusHeaderSkipSamplesOffset = 10;
56 // Offset to sample rate in the Opus header.
57 constexpr size_t kOpusHeaderSampleRateOffset = 12;
58 // Offset to the gain value in the Opus header.
59 constexpr size_t kOpusHeaderGainOffset = 16;
60 // Offset to the channel mapping byte in the Opus header.
61 constexpr size_t kOpusHeaderChannelMappingOffset = 18;
62 // Opus Header contains a stream map. The mapping values are in the header
63 // beyond the always present |kOpusHeaderSize| bytes of data. The mapping
64 // data contains stream count, coupling information, and per channel mapping
65 // values:
66 //   - Byte 0: Number of streams.
67 //   - Byte 1: Number coupled.
68 //   - Byte 2: Starting at byte 2 are |header->channels| uint8 mapping
69 //             values.
70 // Offset to the number of streams in the Opus header.
71 constexpr size_t kOpusHeaderNumStreamsOffset = 19;
72 // Offset to the number of streams that are coupled in the Opus header.
73 constexpr size_t kOpusHeaderNumCoupledStreamsOffset = 20;
74 // Offset to the stream to channel mapping in the Opus header.
75 constexpr size_t kOpusHeaderStreamMapOffset = 21;
76 
77 // Default audio output channel layout. Used to initialize |stream_map| in
78 // OpusHeader, and passed to opus_multistream_decoder_create() when the header
79 // does not contain mapping information. The values are valid only for mono and
80 // stereo output: Opus streams with more than 2 channels require a stream map.
81 constexpr int kMaxChannelsWithDefaultLayout = 2;
82 
ReadLE16(const uint8_t * data,size_t data_size,uint32_t read_offset)83 static uint16_t ReadLE16(const uint8_t* data, size_t data_size, uint32_t read_offset) {
84     // check whether the 2nd byte is within the buffer
85     if (read_offset + 1 >= data_size) return 0;
86     uint16_t val;
87     val = data[read_offset];
88     val |= data[read_offset + 1] << 8;
89     return val;
90 }
91 
92 // Parses Opus Header. Header spec: http://wiki.xiph.org/OggOpus#ID_Header
ParseOpusHeader(const uint8_t * data,size_t data_size,OpusHeader * header)93 bool ParseOpusHeader(const uint8_t* data, size_t data_size, OpusHeader* header) {
94     if (data == NULL) {
95         return false;
96     }
97     if (data_size < kOpusHeaderSize) {
98         ALOGV("Header size is too small.");
99         return false;
100     }
101     header->channels = data[kOpusHeaderChannelsOffset];
102 
103     if (header->channels < 1 || header->channels > kMaxChannels) {
104         ALOGV("Invalid Header, bad channel count: %d", header->channels);
105         return false;
106     }
107     header->skip_samples = ReadLE16(data, data_size, kOpusHeaderSkipSamplesOffset);
108     header->gain_db = static_cast<int16_t>(ReadLE16(data, data_size, kOpusHeaderGainOffset));
109     header->channel_mapping = data[kOpusHeaderChannelMappingOffset];
110     if (!header->channel_mapping) {
111         if (header->channels > kMaxChannelsWithDefaultLayout) {
112             ALOGV("Invalid Header, missing stream map.");
113             return false;
114         }
115         header->num_streams = 1;
116         header->num_coupled = header->channels > 1;
117         header->stream_map[0] = 0;
118         header->stream_map[1] = 1;
119         return true;
120     }
121     if (data_size < kOpusHeaderStreamMapOffset + header->channels) {
122         ALOGV("Invalid stream map; insufficient data for current channel "
123               "count: %d",
124               header->channels);
125         return false;
126     }
127     header->num_streams = data[kOpusHeaderNumStreamsOffset];
128     header->num_coupled = data[kOpusHeaderNumCoupledStreamsOffset];
129     if (header->num_coupled > header->num_streams ||
130         header->num_streams + header->num_coupled != header->channels) {
131         ALOGV("Inconsistent channel mapping, streams: %d coupled: %d channels: %d",
132         header->num_streams, header->num_coupled, header->channels);
133         return false;
134     }
135     for (int i = 0; i < header->channels; ++i) {
136         uint8_t value = data[kOpusHeaderStreamMapOffset + i];
137         if (value != 255 && value >= header->channels) {
138             ALOGV("Invalid channel mapping for index %i : %d", i, value);
139             return false;
140         }
141         header->stream_map[i] = value;
142     }
143     return true;
144 }
145 
WriteOpusHeader(const OpusHeader & header,int input_sample_rate,uint8_t * output,size_t output_size)146 int WriteOpusHeader(const OpusHeader &header, int input_sample_rate,
147                     uint8_t* output, size_t output_size) {
148     // See https://wiki.xiph.org/OggOpus#ID_Header.
149     const size_t total_size = kOpusHeaderStreamMapOffset + header.channels;
150     if (output_size < total_size) {
151         ALOGE("Output buffer too small for header.");
152         return -1;
153     }
154 
155     // ensure entire header is cleared, even though we overwrite much of it below
156     memset(output, 0, output_size);
157 
158     // Set magic signature.
159     memcpy(output + kOpusHeaderLabelOffset, "OpusHead", 8);
160     // Set Opus version.
161     output[kOpusHeaderVersionOffset] = 1;
162     // Set channel count.
163     output[kOpusHeaderChannelsOffset] = (uint8_t)header.channels;
164     // Set pre-skip
165     memcpy(output + kOpusHeaderSkipSamplesOffset, &header.skip_samples, sizeof(uint16_t));
166     // Set original input sample rate in Hz.
167     memcpy(output + kOpusHeaderSampleRateOffset, &input_sample_rate, sizeof(uint32_t));
168     // Set output gain in dB.
169     memcpy(output + kOpusHeaderGainOffset, &header.gain_db, sizeof(uint16_t));
170 
171     if (header.channels > 2) {
172         // Set channel mapping
173         output[kOpusHeaderChannelMappingOffset] = 1;
174         // Assuming no coupled streams. This should actually be
175         // channels() - |coupled_streams|.
176         output[kOpusHeaderNumStreamsOffset] = header.channels;
177         output[kOpusHeaderNumCoupledStreamsOffset] = 0;
178 
179         // Set the actual stream map.
180         for (int i = 0; i < header.channels; ++i) {
181             output[kOpusHeaderStreamMapOffset + i] = kOpusChannelMap[header.channels - 1][i];
182         }
183         return kOpusHeaderStreamMapOffset + header.channels + 1;
184     } else {
185         output[kOpusHeaderChannelMappingOffset] = 0;
186         return kOpusHeaderChannelMappingOffset + 1;
187     }
188 }
189 
WriteOpusHeaders(const OpusHeader & header,int inputSampleRate,uint8_t * output,size_t outputSize,uint64_t codecDelay,uint64_t seekPreRoll)190 int WriteOpusHeaders(const OpusHeader &header, int inputSampleRate,
191                      uint8_t* output, size_t outputSize, uint64_t codecDelay,
192                      uint64_t seekPreRoll) {
193     if (outputSize < AOPUS_UNIFIED_CSD_MINSIZE) {
194         ALOGD("Buffer not large enough to hold unified OPUS CSD");
195         return -1;
196     }
197     int headerLen = 0;
198 
199     // Add opus header
200     /*
201       Following is the CSD syntax for signalling OpusHeader
202       (http://wiki.xiph.org/OggOpus#ID_Header)
203 
204       Marker (8 bytes) | Length (8 bytes) | OpusHeader
205 
206       Markers supported:
207       AOPUS_CSD_OPUS_HEADER_MARKER - Signals Opus Header
208 
209       Length should be a value within AOPUS_OPUSHEAD_MINSIZE and AOPUS_OPUSHEAD_MAXSIZE.
210     */
211 
212     memcpy(output + headerLen, AOPUS_CSD_OPUS_HEADER_MARKER, AOPUS_MARKER_SIZE);
213     headerLen += AOPUS_MARKER_SIZE;
214 
215     // Place holder for opusHeader Size
216     headerLen += AOPUS_LENGTH_SIZE;
217 
218     int headerSize = WriteOpusHeader(header, inputSampleRate, output + headerLen,
219         outputSize - headerLen);
220     if (headerSize < 0) {
221         ALOGD("%s: WriteOpusHeader failed", __func__);
222         return -1;
223     }
224     headerLen += headerSize;
225 
226     // Update opus headerSize after AOPUS_CSD_OPUS_HEADER_MARKER
227     uint64_t length = headerSize;
228     memcpy(output + AOPUS_MARKER_SIZE, &length, AOPUS_LENGTH_SIZE);
229 
230     /*
231       Following is the CSD syntax for signalling codec delay and
232       seek pre-roll which is to be appended after OpusHeader
233 
234       Marker (8 bytes) | Length (8 bytes) | Samples in ns (8 bytes)
235 
236       Markers supported:
237       AOPUS_CSD_CODEC_DELAY_MARKER - codec delay as samples in ns, represented in 8 bytes
238       AOPUS_CSD_SEEK_PREROLL_MARKER - preroll adjustment as samples in ns, represented in 8 bytes
239 
240     */
241     length = sizeof(codecDelay);
242     if (headerLen > (outputSize - AOPUS_MARKER_SIZE - AOPUS_LENGTH_SIZE - length)) {
243         ALOGD("Buffer not large enough to hold codec delay");
244         return -1;
245     }
246     // Add codec delay
247     memcpy(output + headerLen, AOPUS_CSD_CODEC_DELAY_MARKER, AOPUS_MARKER_SIZE);
248     headerLen += AOPUS_MARKER_SIZE;
249     memcpy(output + headerLen, &length, AOPUS_LENGTH_SIZE);
250     headerLen += AOPUS_LENGTH_SIZE;
251     memcpy(output + headerLen, &codecDelay, length);
252     headerLen += length;
253 
254     length = sizeof(seekPreRoll);
255     if (headerLen > (outputSize - AOPUS_MARKER_SIZE - AOPUS_LENGTH_SIZE - length)) {
256         ALOGD("Buffer not large enough to hold seek pre roll");
257         return -1;
258     }
259     // Add skip pre roll
260     memcpy(output + headerLen, AOPUS_CSD_SEEK_PREROLL_MARKER, AOPUS_MARKER_SIZE);
261     headerLen += AOPUS_MARKER_SIZE;
262     memcpy(output + headerLen, &length, AOPUS_LENGTH_SIZE);
263     headerLen += AOPUS_LENGTH_SIZE;
264     memcpy(output + headerLen, &seekPreRoll, length);
265     headerLen += length;
266 
267     return headerLen;
268 }
269 
IsOpusHeader(const uint8_t * data,size_t data_size)270 bool IsOpusHeader(const uint8_t *data, size_t data_size) {
271     if (data_size < AOPUS_MARKER_SIZE) {
272         return false;
273     }
274 
275     return !memcmp(data, AOPUS_CSD_OPUS_HEADER_MARKER, AOPUS_MARKER_SIZE);
276 }
277 
GetOpusHeaderBuffers(const uint8_t * data,size_t data_size,void ** opusHeadBuf,size_t * opusHeadSize,void ** codecDelayBuf,size_t * codecDelaySize,void ** seekPreRollBuf,size_t * seekPreRollSize)278 bool GetOpusHeaderBuffers(const uint8_t *data, size_t data_size,
279                           void **opusHeadBuf, size_t *opusHeadSize,
280                           void **codecDelayBuf, size_t *codecDelaySize,
281                           void **seekPreRollBuf, size_t *seekPreRollSize) {
282     *codecDelayBuf = NULL;
283     *codecDelaySize = 0;
284     *seekPreRollBuf = NULL;
285     *seekPreRollSize = 0;
286     *opusHeadBuf = NULL;
287     *opusHeadSize = 0;
288 
289     // AOPUS_MARKER_SIZE is 8 "OpusHead" is of size 8
290     if (data_size < 8)
291         return false;
292 
293     // Check if the CSD is in legacy format
294     if (!memcmp("OpusHead", data, 8)) {
295         if (data_size < AOPUS_OPUSHEAD_MINSIZE || data_size > AOPUS_OPUSHEAD_MAXSIZE) {
296             ALOGD("Unexpected size for opusHeadSize %zu", data_size);
297             return false;
298         }
299         *opusHeadBuf = (void *)data;
300         *opusHeadSize = data_size;
301         return true;
302     } else if (memcmp(AOPUS_CSD_MARKER_PREFIX, data, AOPUS_CSD_MARKER_PREFIX_SIZE) == 0) {
303         if (data_size < AOPUS_UNIFIED_CSD_MINSIZE || data_size > AOPUS_UNIFIED_CSD_MAXSIZE) {
304             ALOGD("Unexpected size for unified opus csd %zu", data_size);
305             return false;
306         }
307         size_t i = 0;
308         bool found = false;
309         while (i <= data_size - AOPUS_MARKER_SIZE - AOPUS_LENGTH_SIZE) {
310             uint8_t *csdBuf = (uint8_t *)data + i;
311             if (!memcmp(csdBuf, AOPUS_CSD_OPUS_HEADER_MARKER, AOPUS_MARKER_SIZE)) {
312                 uint64_t value;
313                 memcpy(&value, csdBuf + AOPUS_MARKER_SIZE, sizeof(value));
314                 if (value < AOPUS_OPUSHEAD_MINSIZE || value > AOPUS_OPUSHEAD_MAXSIZE) {
315                     ALOGD("Unexpected size for opusHeadSize %" PRIu64, value);
316                     return false;
317                 }
318                 i += AOPUS_MARKER_SIZE + AOPUS_LENGTH_SIZE + value;
319                 if (i > data_size) {
320                     ALOGD("Marker signals a header that is larger than input");
321                     return false;
322                 }
323                 *opusHeadBuf = csdBuf + AOPUS_MARKER_SIZE + AOPUS_LENGTH_SIZE;
324                 *opusHeadSize = value;
325                 found = true;
326             } else if (!memcmp(csdBuf, AOPUS_CSD_CODEC_DELAY_MARKER, AOPUS_MARKER_SIZE)) {
327                 uint64_t value;
328                 memcpy(&value, csdBuf + AOPUS_MARKER_SIZE, sizeof(value));
329                 if (value != sizeof(uint64_t)) {
330                     ALOGD("Unexpected size for codecDelay %" PRIu64, value);
331                     return false;
332                 }
333                 i += AOPUS_MARKER_SIZE + AOPUS_LENGTH_SIZE + value;
334                 if (i > data_size) {
335                     ALOGD("Marker signals a header that is larger than input");
336                     return false;
337                 }
338                 *codecDelayBuf = csdBuf + AOPUS_MARKER_SIZE + AOPUS_LENGTH_SIZE;
339                 *codecDelaySize = value;
340             } else if (!memcmp(csdBuf, AOPUS_CSD_SEEK_PREROLL_MARKER, AOPUS_MARKER_SIZE)) {
341                 uint64_t value;
342                 memcpy(&value, csdBuf + AOPUS_MARKER_SIZE, sizeof(value));
343                 if (value != sizeof(uint64_t)) {
344                     ALOGD("Unexpected size for seekPreRollSize %" PRIu64, value);
345                     return false;
346                 }
347                 i += AOPUS_MARKER_SIZE + AOPUS_LENGTH_SIZE + value;
348                 if (i > data_size) {
349                     ALOGD("Marker signals a header that is larger than input");
350                     return false;
351                 }
352                 *seekPreRollBuf = csdBuf + AOPUS_MARKER_SIZE + AOPUS_LENGTH_SIZE;
353                 *seekPreRollSize = value;
354             } else {
355                 i++;
356             }
357         }
358         return found;
359     } else {
360         return false;  // it isn't in either format
361     }
362 }
363 
364 }  // namespace android
365