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 "hfp_lc3_encoder.h"
20
21 #include <bluetooth/log.h>
22 #include <lc3.h>
23
24 #include <cstring>
25
26 #include "os/log.h"
27 #include "osi/include/allocator.h"
28
29 using namespace bluetooth;
30
31 const int HFP_LC3_PCM_BYTES = 480;
32 const int HFP_LC3_PKT_FRAME_LEN = 58;
33
34 static void* hfp_lc3_encoder_mem;
35 static lc3_encoder_t hfp_lc3_encoder;
36
hfp_lc3_encoder_init()37 void hfp_lc3_encoder_init() {
38 if (hfp_lc3_encoder_mem) {
39 log::warn("The encoder instance should have had been released.");
40 osi_free(hfp_lc3_encoder_mem);
41 }
42
43 const int dt_us = 7500;
44 const int sr_hz = 32000;
45 const int sr_pcm_hz = 32000;
46 const unsigned enc_size = lc3_encoder_size(dt_us, sr_pcm_hz);
47
48 hfp_lc3_encoder_mem = osi_malloc(enc_size);
49 hfp_lc3_encoder =
50 lc3_setup_encoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_encoder_mem);
51 }
52
hfp_lc3_encoder_cleanup()53 void hfp_lc3_encoder_cleanup() {
54 if (hfp_lc3_encoder_mem) {
55 osi_free_and_reset((void**)&hfp_lc3_encoder_mem);
56 }
57 }
58
hfp_lc3_encode_frames(int16_t * input,uint8_t * output)59 uint32_t hfp_lc3_encode_frames(int16_t* input, uint8_t* output) {
60 if (input == nullptr || output == nullptr) {
61 log::error("Buffer is null.");
62 return 0;
63 }
64
65 /* Note this only fails when wrong parameters are supplied. */
66 int rc = lc3_encode(hfp_lc3_encoder, LC3_PCM_FORMAT_S16, input, 1,
67 HFP_LC3_PKT_FRAME_LEN, output);
68
69 log::assert_that(rc == 0, "assert failed: rc == 0");
70
71 return HFP_LC3_PCM_BYTES;
72 }
73