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_decoder"
18
19 #include "hfp_lc3_decoder.h"
20
21 #include <bluetooth/log.h>
22 #include <lc3.h>
23
24 #include <cstdint>
25 #include <cstring>
26
27 #include "osi/include/allocator.h"
28
29 using namespace bluetooth;
30
31 const int HFP_LC3_H2_HEADER_LEN = 2;
32 const int HFP_LC3_PKT_FRAME_LEN = 58;
33 const int HFP_LC3_PCM_BYTES = 480;
34
35 static void* hfp_lc3_decoder_mem;
36 static lc3_decoder_t hfp_lc3_decoder;
37
hfp_lc3_decoder_init()38 bool hfp_lc3_decoder_init() {
39 if (hfp_lc3_decoder_mem) {
40 log::warn("The decoder instance should have had been released.");
41 osi_free(hfp_lc3_decoder_mem);
42 }
43
44 const int dt_us = 7500;
45 const int sr_hz = 32000;
46 const int sr_pcm_hz = 32000;
47 const unsigned dec_size = lc3_decoder_size(dt_us, sr_pcm_hz);
48
49 hfp_lc3_decoder_mem = osi_malloc(dec_size);
50 hfp_lc3_decoder = lc3_setup_decoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_decoder_mem);
51
52 return true;
53 }
54
hfp_lc3_decoder_cleanup()55 void hfp_lc3_decoder_cleanup() {
56 if (hfp_lc3_decoder_mem) {
57 osi_free_and_reset((void**)&hfp_lc3_decoder_mem);
58 }
59 }
60
hfp_lc3_decoder_decode_packet(const uint8_t * i_buf,int16_t * o_buf,size_t out_len)61 bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) {
62 if (o_buf == nullptr || out_len < HFP_LC3_PCM_BYTES) {
63 log::error("Output buffer size {} is less than LC3 frame size {}", out_len, HFP_LC3_PCM_BYTES);
64 return false;
65 }
66
67 const uint8_t* frame = i_buf ? i_buf + HFP_LC3_H2_HEADER_LEN : nullptr;
68
69 /* Note this only fails when wrong parameters are supplied. */
70 int rc = lc3_decode(hfp_lc3_decoder, frame, HFP_LC3_PKT_FRAME_LEN, LC3_PCM_FORMAT_S16, o_buf, 1);
71
72 log::assert_that(rc == 0 || rc == 1, "assert failed: rc == 0 || rc == 1");
73
74 return !rc;
75 }
76