1 /*
2 * Copyright (C) 2023 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 "hfp_lc3_encoder"
18
19 #include <bluetooth/log.h>
20
21 #include "hfp_lc3_encoder.h"
22 #include "mmc/codec_client/codec_client.h"
23 #include "mmc/proto/mmc_config.pb.h"
24
25 using namespace bluetooth;
26
27 const int HFP_LC3_PCM_BYTES = 480;
28 const int HFP_LC3_PKT_FRAME_LEN = 58;
29
30 static mmc::CodecClient* client = nullptr;
31
hfp_lc3_encoder_init()32 void hfp_lc3_encoder_init() {
33 hfp_lc3_encoder_cleanup();
34 client = new mmc::CodecClient;
35
36 const int dt_us = 7500;
37 const int sr_hz = 32000;
38 const int sr_pcm_hz = 32000;
39
40 mmc::Lc3Param param;
41 param.set_dt_us(dt_us);
42 param.set_sr_hz(sr_hz);
43 param.set_sr_pcm_hz(sr_pcm_hz);
44 param.set_stride(1);
45 param.set_fmt(mmc::Lc3Param::kLc3PcmFormatS16);
46
47 mmc::ConfigParam config;
48 *config.mutable_hfp_lc3_encoder_param() = param;
49
50 int ret = client->init(config);
51 if (ret < 0) {
52 log::error("Init failed with error message, {}", strerror(-ret));
53 }
54 return;
55 }
56
hfp_lc3_encoder_cleanup()57 void hfp_lc3_encoder_cleanup() {
58 if (client) {
59 client->cleanup();
60 delete client;
61 client = nullptr;
62 }
63 }
64
hfp_lc3_encode_frames(int16_t * input,uint8_t * output)65 uint32_t hfp_lc3_encode_frames(int16_t* input, uint8_t* output) {
66 if (input == nullptr || output == nullptr) {
67 log::error("Buffer is null");
68 return 0;
69 }
70
71 if (!client) {
72 log::error("CodecClient has not been initialized");
73 return 0;
74 }
75
76 int rc = client->transcode((uint8_t*)input, HFP_LC3_PCM_BYTES, output, HFP_LC3_PKT_FRAME_LEN);
77
78 if (rc < 0) {
79 log::warn("Encode failed with error message, {}", strerror(-rc));
80 return 0;
81 }
82
83 return HFP_LC3_PCM_BYTES;
84 }
85