]> code.octet-stream.net Git - m17rt/blob - m17codec2/src/lib.rs
0f3c8a5e2cb0199e7754fa3289d80818f8123d00
[m17rt] / m17codec2 / src / lib.rs
1 use codec2::{Codec2, Codec2Mode};
2 use cpal::traits::DeviceTrait;
3 use cpal::traits::HostTrait;
4 use cpal::traits::StreamTrait;
5 use cpal::{Sample, SampleFormat, SampleRate};
6 use log::debug;
7 use m17app::adapter::StreamAdapter;
8 use m17app::app::TxHandle;
9 use m17app::link_setup::LinkSetup;
10 use m17app::link_setup::M17Address;
11 use m17core::address::Address;
12 use m17core::address::Callsign;
13 use m17core::protocol::LsfFrame;
14 use m17core::protocol::StreamFrame;
15 use std::collections::VecDeque;
16 use std::fs::File;
17 use std::io::Write;
18 use std::path::Path;
19 use std::path::PathBuf;
20 use std::sync::{
21 mpsc::{channel, Receiver, Sender},
22 Arc, Mutex,
23 };
24 use std::time::Duration;
25 use std::time::Instant;
26
27 pub fn decode_codec2<P: AsRef<Path>>(data: &[u8], out_path: P) -> Vec<i16> {
28 let codec2 = Codec2::new(Codec2Mode::MODE_3200);
29 let var_name = codec2;
30 let mut codec = var_name;
31 let mut all_samples: Vec<i16> = vec![];
32 for i in 0..(data.len() / 8) {
33 let mut samples = vec![0; codec.samples_per_frame()];
34 codec.decode(&mut samples, &data[i * 8..((i + 1) * 8)]);
35 all_samples.append(&mut samples);
36 }
37
38 // dude this works
39 let mut speech_out = File::create(out_path).unwrap();
40 for b in &all_samples {
41 speech_out.write_all(&b.to_le_bytes()).unwrap();
42 }
43 all_samples
44 }
45
46 pub struct Codec2Adapter {
47 state: Arc<Mutex<AdapterState>>,
48 // TODO: make this configurable
49 output_card: String,
50 }
51
52 impl Codec2Adapter {
53 pub fn new() -> Self {
54 Self {
55 state: Arc::new(Mutex::new(AdapterState {
56 tx: None,
57 out_buf: VecDeque::new(),
58 codec2: Codec2::new(Codec2Mode::MODE_3200),
59 end_tx: None,
60 })),
61 // TODO: this doesn't work on rpi. Use default_output_device() by default
62 output_card: "default".to_owned(),
63 }
64 }
65 }
66
67 struct AdapterState {
68 tx: Option<TxHandle>,
69 /// Circular buffer of output samples for playback
70 out_buf: VecDeque<i16>,
71 codec2: Codec2,
72 end_tx: Option<Sender<()>>,
73 }
74
75 impl StreamAdapter for Codec2Adapter {
76 fn adapter_registered(&self, _id: usize, handle: TxHandle) {
77 self.state.lock().unwrap().tx = Some(handle);
78
79 let (end_tx, end_rx) = channel();
80 let state = self.state.clone();
81 let output_card = self.output_card.clone();
82 std::thread::spawn(move || stream_thread(end_rx, state, output_card));
83 self.state.lock().unwrap().end_tx = Some(end_tx);
84 }
85
86 fn adapter_removed(&self) {
87 let mut state = self.state.lock().unwrap();
88 state.tx = None;
89 state.end_tx = None;
90 }
91
92 fn tnc_started(&self) {}
93
94 fn tnc_closed(&self) {}
95
96 fn stream_began(&self, _link_setup: LinkSetup) {
97 // for now we will assume:
98 // - unencrypted
99 // - data type is Voice (Codec2 3200), not Voice+Data
100 // TODO: is encryption handled here or in M17App, such that we get a decrypted stream?
101 // TODO: handle the Voice+Data combination with Codec2 1600
102 self.state.lock().unwrap().codec2 = Codec2::new(Codec2Mode::MODE_3200);
103 }
104
105 fn stream_data(&self, _frame_number: u16, _is_final: bool, data: Arc<[u8; 16]>) {
106 let mut state = self.state.lock().unwrap();
107 for encoded in data.chunks(8) {
108 if state.out_buf.len() < 1024 {
109 let mut samples = [i16::EQUILIBRIUM; 160]; // while assuming 3200
110 state.codec2.decode(&mut samples, encoded);
111 // TODO: maybe get rid of VecDeque so we can decode directly into ring buffer?
112 for s in samples {
113 state.out_buf.push_back(s);
114 }
115 } else {
116 debug!("out_buf overflow");
117 }
118 }
119 }
120 }
121
122 fn output_cb(data: &mut [i16], state: &Mutex<AdapterState>) {
123 let mut state = state.lock().unwrap();
124 for d in data {
125 *d = state.out_buf.pop_front().unwrap_or(i16::EQUILIBRIUM);
126 }
127 }
128
129 /// Create and manage the stream from a dedicated thread since it's `!Send`
130 fn stream_thread(end: Receiver<()>, state: Arc<Mutex<AdapterState>>, output_card: String) {
131 let host = cpal::default_host();
132 let device = host
133 .output_devices()
134 .unwrap()
135 .find(|d| d.name().unwrap() == output_card)
136 .unwrap();
137 let mut configs = device.supported_output_configs().unwrap();
138 // TODO: channels == 1 doesn't work on a Raspberry Pi
139 // make this configurable and support interleaving LRLR stereo samples if using 2 channels
140 let config = configs
141 .find(|c| c.channels() == 1 && c.sample_format() == SampleFormat::I16)
142 .unwrap()
143 .with_sample_rate(SampleRate(8000));
144 let stream = device
145 .build_output_stream(
146 &config.into(),
147 move |data: &mut [i16], _info: &cpal::OutputCallbackInfo| {
148 output_cb(data, &state);
149 },
150 |e| {
151 // trigger end_tx here? always more edge cases
152 debug!("error occurred in codec2 playback: {e:?}");
153 },
154 None,
155 )
156 .unwrap();
157 stream.play().unwrap();
158 let _ = end.recv();
159 // it seems concrete impls of Stream have a Drop implementation that will handle termination
160 }
161
162 pub struct WavePlayer;
163
164 impl WavePlayer {
165 pub fn play(
166 path: PathBuf,
167 tx: TxHandle,
168 source: &M17Address,
169 destination: &M17Address,
170 channel_access_number: u8,
171 ) {
172 let mut reader = hound::WavReader::open(path).unwrap();
173 let mut samples = reader.samples::<i16>();
174
175 let mut codec = Codec2::new(Codec2Mode::MODE_3200);
176 let mut in_buf = [0i16; 160];
177 let mut out_buf = [0u8; 16];
178 let mut lsf_chunk: usize = 0;
179 const TICK: Duration = Duration::from_millis(40);
180 let mut next_tick = Instant::now() + TICK;
181 let mut frame_number = 0;
182
183 let mut setup = LinkSetup::new_voice(source, destination);
184 setup.set_channel_access_number(channel_access_number);
185 tx.transmit_stream_start(&setup);
186
187 loop {
188 let mut last_one = false;
189 for mut out in out_buf.chunks_mut(8) {
190 for i in 0..160 {
191 let sample = match samples.next() {
192 Some(Ok(sample)) => sample,
193 _ => {
194 last_one = true;
195 0
196 }
197 };
198 in_buf[i] = sample;
199 }
200 codec.encode(&mut out, &in_buf);
201 }
202 tx.transmit_stream_next(&StreamFrame {
203 lich_idx: lsf_chunk as u8,
204 lich_part: setup.lich_part(lsf_chunk as u8),
205 frame_number,
206 end_of_stream: last_one,
207 stream_data: out_buf.clone(),
208 });
209 frame_number += 1;
210 lsf_chunk = (lsf_chunk + 1) % 6;
211
212 if last_one {
213 break;
214 }
215
216 std::thread::sleep(next_tick.duration_since(Instant::now()));
217 next_tick += TICK;
218 }
219 }
220 }