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 <cstring>
25
26 #include "os/log.h"
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 =
51 lc3_setup_decoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_decoder_mem);
52
53 return true;
54 }
55
hfp_lc3_decoder_cleanup()56 void hfp_lc3_decoder_cleanup() {
57 if (hfp_lc3_decoder_mem) {
58 osi_free_and_reset((void**)&hfp_lc3_decoder_mem);
59 }
60 }
61
hfp_lc3_decoder_decode_packet(const uint8_t * i_buf,int16_t * o_buf,size_t out_len)62 bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf,
63 size_t out_len) {
64 if (o_buf == nullptr || out_len < HFP_LC3_PCM_BYTES) {
65 log::error("Output buffer size {} is less than LC3 frame size {}", out_len,
66 HFP_LC3_PCM_BYTES);
67 return false;
68 }
69
70 const uint8_t* frame = i_buf ? i_buf + HFP_LC3_H2_HEADER_LEN : nullptr;
71
72 /* Note this only fails when wrong parameters are supplied. */
73 int rc = lc3_decode(hfp_lc3_decoder, frame, HFP_LC3_PKT_FRAME_LEN,
74 LC3_PCM_FORMAT_S16, o_buf, 1);
75
76 log::assert_that(rc == 0 || rc == 1, "assert failed: rc == 0 || rc == 1");
77
78 return !rc;
79 }
80