1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "format_converter.h"
17 #include <string>
18 
19 namespace OHOS {
20 namespace AudioStandard {
S16MonoToS16Stereo(const BufferDesc & srcDesc,const BufferDesc & dstDesc)21 int32_t FormatConverter::S16MonoToS16Stereo(const BufferDesc &srcDesc, const BufferDesc &dstDesc)
22 {
23     size_t half = 2; // mono(1) -> stereo(2)
24     if (srcDesc.bufLength != dstDesc.bufLength / half || srcDesc.buffer == nullptr || dstDesc.buffer == nullptr) {
25         return -1;
26     }
27     int16_t *stcPtr = reinterpret_cast<int16_t *>(srcDesc.buffer);
28     int16_t *dstPtr = reinterpret_cast<int16_t *>(dstDesc.buffer);
29     size_t count = srcDesc.bufLength / sizeof(int16_t);
30     for (size_t idx = 0; idx < count; idx++) {
31         *(dstPtr++) = *stcPtr;
32         *(dstPtr++) = *stcPtr++;
33     }
34     return 0;
35 }
36 
S16StereoToS16Mono(const BufferDesc & srcDesc,const BufferDesc & dstDesc)37 int32_t FormatConverter::S16StereoToS16Mono(const BufferDesc &srcDesc, const BufferDesc &dstDesc)
38 {
39     size_t half = 2; // stereo(2) -> mono(1)
40     if (dstDesc.bufLength != srcDesc.bufLength / half || srcDesc.buffer == nullptr || dstDesc.buffer == nullptr) {
41         return -1;
42     }
43     int16_t *stcPtr = reinterpret_cast<int16_t *>(srcDesc.buffer);
44     int16_t *dstPtr = reinterpret_cast<int16_t *>(dstDesc.buffer);
45     size_t count = srcDesc.bufLength / half / sizeof(int16_t);
46     for (size_t idx = 0; idx < count; idx++) {
47         *(dstPtr++) = (*stcPtr + *(stcPtr + 1)) / 2; // To obtain mono channel, add left to right, then divide by 2
48         stcPtr += 2; // ptr++ on mono is equivalent to ptr+=2 on stereo
49     }
50     return 0;
51 }
52 } // namespace AudioStandard
53 } // namespace OHOS
54