1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
#![warn(missing_docs)]
extern crate opus_sys as ffi;
extern crate libc;
use std::ffi::CStr;
use std::marker::PhantomData;
use libc::c_int;
const OPUS_RESET_STATE: c_int = 4028;
const OPUS_GET_FINAL_RANGE: c_int = 4031;
const OPUS_GET_BANDWIDTH: c_int = 4009;
const OPUS_GET_SAMPLE_RATE: c_int = 4029;
const OPUS_SET_BITRATE: c_int = 4002;
const OPUS_GET_BITRATE: c_int = 4003;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum CodingMode {
Voip = 2048,
Audio = 2049,
LowDelay = 2051,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Channels {
Mono = 1,
Stereo = 2,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Bandwidth {
Auto = -1000,
Narrowband = 1101,
Mediumband = 1102,
Wideband = 1103,
Superwideband = 1104,
Fullband = 1105,
}
impl Bandwidth {
fn from_int(value: i32) -> Option<Bandwidth> {
Some(match value {
-1000 => Bandwidth::Auto,
1101 => Bandwidth::Narrowband,
1102 => Bandwidth::Mediumband,
1103 => Bandwidth::Wideband,
1104 => Bandwidth::Superwideband,
1105 => Bandwidth::Fullband,
_ => return None,
})
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum ErrorCode {
BadArg = -1,
BufferTooSmall = -2,
InternalError = -3,
InvalidPacket = -4,
Unimplemented = -5,
InvalidState = -6,
AllocFail = -7,
Unknown = -8,
}
pub fn version() -> &'static str {
unsafe { CStr::from_ptr(ffi::opus_get_version_string()) }.to_str().unwrap()
}
pub struct Encoder {
ptr: *mut ffi::OpusEncoder,
channels: Channels,
}
impl Encoder {
pub fn new(sample_rate: u32, channels: Channels, mode: CodingMode) -> Result<Encoder> {
let mut error = 0;
let ptr = unsafe { ffi::opus_encoder_create(
sample_rate as i32,
channels as c_int,
mode as c_int,
&mut error) };
if error != ffi::OPUS_OK || ptr.is_null() {
Err(Error::from_code("opus_encoder_create", error))
} else {
Ok(Encoder { ptr: ptr, channels: channels })
}
}
pub fn encode(&mut self, input: &[i16], output: &mut [u8]) -> Result<usize> {
let len = unsafe { ffi::opus_encode(self.ptr,
input.as_ptr(), input.len() as c_int / self.channels as c_int,
output.as_mut_ptr(), output.len() as c_int) };
try!(check("opus_encode", len));
Ok(len as usize)
}
pub fn encode_float(&mut self, input: &[f32], output: &mut [u8]) -> Result<usize> {
let len = unsafe { ffi::opus_encode_float(self.ptr,
input.as_ptr(), input.len() as c_int / self.channels as c_int,
output.as_mut_ptr(), output.len() as c_int) };
try!(check("opus_encode_float", len));
Ok(len as usize)
}
pub fn reset_state(&mut self) -> Result<()> {
check("opus_encoder_ctl(OPUS_RESET_STATE)", unsafe { ffi::opus_encoder_ctl(self.ptr, OPUS_RESET_STATE) })
}
pub fn get_final_range(&mut self) -> Result<u32> {
let mut value: u32 = 0;
let result = unsafe { ffi::opus_encoder_ctl(self.ptr, OPUS_GET_FINAL_RANGE, &mut value) };
try!(check("opus_encoder_ctl(OPUS_GET_FINAL_RANGE)", result));
Ok(value)
}
pub fn get_bandwidth(&mut self) -> Result<Bandwidth> {
let mut value: i32 = 0;
let result = unsafe { ffi::opus_encoder_ctl(self.ptr, OPUS_GET_BANDWIDTH, &mut value) };
try!(check("opus_encoder_ctl(OPUS_GET_BANDWIDTH)", result));
Bandwidth::from_int(result).ok_or_else(|| Error::from_code("opus_encoder_ctl(OPUS_GET_BANDWIDTH)", ffi::OPUS_BAD_ARG))
}
pub fn get_sample_rate(&mut self) -> Result<u32> {
let mut value: i32 = 0;
let result = unsafe { ffi::opus_encoder_ctl(self.ptr, OPUS_GET_SAMPLE_RATE, &mut value) };
try!(check("opus_encoder_ctl(OPUS_GET_SAMPLE_RATE)", result));
Ok(value as u32)
}
pub fn set_bitrate(&mut self, value: i32) -> Result<()> {
let result = unsafe { ffi::opus_encoder_ctl(self.ptr, OPUS_SET_BITRATE, value) };
check("opus_encoder_ctl(OPUS_SET_BITRATE)", result)
}
pub fn get_bitrate(&mut self) -> Result<i32> {
let mut value: i32 = 0;
let result = unsafe { ffi::opus_encoder_ctl(self.ptr, OPUS_GET_BITRATE, &mut value) };
try!(check("opus_encoder_ctl(OPUS_GET_BITRATE)", result));
Ok(value)
}
}
impl Drop for Encoder {
fn drop(&mut self) {
unsafe { ffi::opus_encoder_destroy(self.ptr) }
}
}
pub struct Decoder {
ptr: *mut ffi::OpusDecoder,
channels: Channels,
}
impl Decoder {
pub fn new(sample_rate: u32, channels: Channels) -> Result<Decoder> {
let mut error = 0;
let ptr = unsafe { ffi::opus_decoder_create(
sample_rate as i32,
channels as c_int,
&mut error) };
if error != ffi::OPUS_OK || ptr.is_null() {
Err(Error::from_code("opus_decoder_create", error))
} else {
Ok(Decoder { ptr: ptr, channels: channels })
}
}
pub fn decode(&mut self, input: &[u8], output: &mut [i16], fec: bool) -> Result<usize> {
let len = unsafe { ffi::opus_decode(self.ptr,
input.as_ptr(), input.len() as c_int,
output.as_mut_ptr(), output.len() as c_int / self.channels as c_int,
fec as c_int) };
try!(check("opus_decode", len));
Ok(len as usize)
}
pub fn decode_float(&mut self, input: &[u8], output: &mut [f32], fec: bool) -> Result<usize> {
let len = unsafe { ffi::opus_decode_float(self.ptr,
input.as_ptr(), input.len() as c_int,
output.as_mut_ptr(), output.len() as c_int / self.channels as c_int,
fec as c_int) };
try!(check("opus_decode_float", len));
Ok(len as usize)
}
pub fn get_nb_samples(&self, packet: &[u8]) -> Result<usize> {
let len = unsafe { ffi::opus_decoder_get_nb_samples(self.ptr,
packet.as_ptr(), packet.len() as i32) };
try!(check("opus_decoder_get_nb_samples", len));
Ok(len as usize)
}
pub fn reset_state(&mut self) -> Result<()> {
check("opus_decoder_ctl(OPUS_RESET_STATE)", unsafe { ffi::opus_decoder_ctl(self.ptr, OPUS_RESET_STATE) })
}
pub fn get_final_range(&mut self) -> Result<u32> {
let mut value: u32 = 0;
let result = unsafe { ffi::opus_decoder_ctl(self.ptr, OPUS_GET_FINAL_RANGE, &mut value) };
try!(check("opus_decoder_ctl(OPUS_GET_FINAL_RANGE)", result));
Ok(value)
}
pub fn get_bandwidth(&mut self) -> Result<Bandwidth> {
let mut value: i32 = 0;
let result = unsafe { ffi::opus_decoder_ctl(self.ptr, OPUS_GET_BANDWIDTH, &mut value) };
try!(check("opus_decoder_ctl(OPUS_GET_BANDWIDTH)", result));
Bandwidth::from_int(result).ok_or_else(|| Error::from_code("opus_decoder_ctl(OPUS_GET_BANDWIDTH)", ffi::OPUS_BAD_ARG))
}
pub fn get_sample_rate(&mut self) -> Result<u32> {
let mut value: i32 = 0;
let result = unsafe { ffi::opus_decoder_ctl(self.ptr, OPUS_GET_SAMPLE_RATE, &mut value) };
try!(check("opus_decoder_ctl(OPUS_GET_SAMPLE_RATE)", result));
Ok(value as u32)
}
}
impl Drop for Decoder {
fn drop(&mut self) {
unsafe { ffi::opus_decoder_destroy(self.ptr) }
}
}
pub mod packet {
use super::*;
use super::{ffi, check};
use std::{ptr, slice};
use libc::c_int;
pub fn get_bandwidth(packet: &[u8]) -> Result<Bandwidth> {
if packet.len() < 1 {
return Err(Error::from_code("opus_packet_get_bandwidth", ffi::OPUS_BAD_ARG))
}
let bandwidth = unsafe { ffi::opus_packet_get_bandwidth(packet.as_ptr()) };
try!(check("opus_packet_get_bandwidth", bandwidth));
Bandwidth::from_int(bandwidth).ok_or_else(|| Error::from_code("opus_packet_get_bandwidth", ffi::OPUS_BAD_ARG))
}
pub fn get_nb_channels(packet: &[u8]) -> Result<Channels> {
if packet.len() < 1 {
return Err(Error::from_code("opus_packet_get_nb_channels", ffi::OPUS_BAD_ARG))
}
let channels = unsafe { ffi::opus_packet_get_nb_channels(packet.as_ptr()) };
try!(check("opus_packet_get_nb_channels", channels));
match channels {
1 => Ok(Channels::Mono),
2 => Ok(Channels::Stereo),
_ => Err(Error::from_code("opus_packet_get_nb_channels", ffi::OPUS_BAD_ARG)),
}
}
pub fn get_nb_frames(packet: &[u8]) -> Result<usize> {
let frames = unsafe { ffi::opus_packet_get_nb_frames(packet.as_ptr(), packet.len() as c_int) };
try!(check("opus_packet_get_nb_frames", frames));
Ok(frames as usize)
}
pub fn get_nb_samples(packet: &[u8], sample_rate: u32) -> Result<usize> {
let frames = unsafe { ffi::opus_packet_get_nb_samples(
packet.as_ptr(), packet.len() as c_int,
sample_rate as c_int) };
try!(check("opus_packet_get_nb_samples", frames));
Ok(frames as usize)
}
pub fn get_samples_per_frame(packet: &[u8], sample_rate: u32) -> Result<usize> {
if packet.len() < 1 {
return Err(Error::from_code("opus_packet_get_samples_per_frame", ffi::OPUS_BAD_ARG))
}
let samples = unsafe { ffi::opus_packet_get_samples_per_frame(packet.as_ptr(), sample_rate as c_int) };
try!(check("opus_packet_get_samples_per_frame", samples));
Ok(samples as usize)
}
pub fn parse(packet: &[u8]) -> Result<Packet> {
let mut toc: u8 = 0;
let mut frames = [ptr::null(); 48];
let mut sizes = [0i16; 48];
let mut payload_offset: i32 = 0;
let num_frames = unsafe { ffi::opus_packet_parse(
packet.as_ptr(), packet.len() as c_int,
&mut toc, frames.as_mut_ptr(),
sizes.as_mut_ptr(), &mut payload_offset) };
try!(check("opus_packet_parse", num_frames));
let mut frames_vec = Vec::with_capacity(num_frames as usize);
for i in 0..num_frames as usize {
frames_vec.push(unsafe { slice::from_raw_parts(frames[i], sizes[i] as usize) });
}
Ok(Packet {
toc: toc,
frames: frames_vec,
payload_offset: payload_offset as usize,
})
}
pub struct Packet<'a> {
pub toc: u8,
pub frames: Vec<&'a [u8]>,
pub payload_offset: usize,
}
pub fn pad(packet: &mut [u8], prev_len: usize) -> Result<usize> {
let result = unsafe { ffi::opus_packet_pad(packet.as_mut_ptr(), prev_len as c_int, packet.len() as c_int) };
try!(check("opus_packet_pad", result));
Ok(result as usize)
}
pub fn unpad(packet: &mut [u8]) -> Result<usize> {
let result = unsafe { ffi::opus_packet_unpad(packet.as_mut_ptr(), packet.len() as c_int) };
try!(check("opus_packet_unpad", result));
Ok(result as usize)
}
}
pub struct SoftClip {
channels: Channels,
memory: [f32; 2],
}
impl SoftClip {
pub fn new(channels: Channels) -> SoftClip {
SoftClip { channels: channels, memory: [0.0; 2] }
}
pub fn apply(&mut self, signal: &mut [f32]) {
unsafe { ffi::opus_pcm_soft_clip(
signal.as_mut_ptr(),
signal.len() as c_int / self.channels as c_int,
self.channels as c_int,
self.memory.as_mut_ptr()) };
}
}
pub struct Repacketizer {
ptr: *mut ffi::OpusRepacketizer,
}
impl Repacketizer {
pub fn new() -> Result<Repacketizer> {
let ptr = unsafe { ffi::opus_repacketizer_create() };
if ptr.is_null() {
Err(Error::from_code("opus_repacketizer_create", ffi::OPUS_ALLOC_FAIL))
} else {
Ok(Repacketizer { ptr: ptr })
}
}
pub fn combine(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<usize> {
let mut state = self.begin();
for &packet in input {
try!(state.cat(packet));
}
state.out(output)
}
pub fn begin<'rp, 'buf>(&'rp mut self) -> RepacketizerState<'rp, 'buf> {
unsafe { ffi::opus_repacketizer_init(self.ptr); }
RepacketizerState { rp: self, phantom: PhantomData }
}
}
impl Drop for Repacketizer {
fn drop(&mut self) {
unsafe { ffi::opus_repacketizer_destroy(self.ptr) }
}
}
pub struct RepacketizerState<'rp, 'buf> {
rp: &'rp mut Repacketizer,
phantom: PhantomData<&'buf [u8]>,
}
impl<'rp, 'buf> RepacketizerState<'rp, 'buf> {
pub fn cat(&mut self, packet: &'buf [u8]) -> Result<()> {
let result = unsafe { ffi::opus_repacketizer_cat(self.rp.ptr,
packet.as_ptr(), packet.len() as c_int) };
check("opus_repacketizer_cat", result)
}
#[inline]
pub fn cat_move<'b2>(self, packet: &'b2 [u8]) -> Result<RepacketizerState<'rp, 'b2>> where 'buf: 'b2 {
let mut shorter = self;
try!(shorter.cat(packet));
Ok(shorter)
}
pub fn get_nb_frames(&mut self) -> usize {
unsafe { ffi::opus_repacketizer_get_nb_frames(self.rp.ptr) as usize }
}
pub fn out(&mut self, buffer: &mut [u8]) -> Result<usize> {
let result = unsafe { ffi::opus_repacketizer_out(self.rp.ptr,
buffer.as_mut_ptr(), buffer.len() as c_int) };
try!(check("opus_repacketizer_out", result));
Ok(result as usize)
}
pub fn out_range(&mut self, begin: usize, end: usize, buffer: &mut [u8]) -> Result<usize> {
let result = unsafe { ffi::opus_repacketizer_out_range(self.rp.ptr,
begin as c_int, end as c_int,
buffer.as_mut_ptr(), buffer.len() as c_int) };
try!(check("opus_repacketizer_out_range", result));
Ok(result as usize)
}
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Error {
function: &'static str,
description: &'static str,
code: ErrorCode,
}
impl Error {
fn from_code(what: &'static str, code: c_int) -> Error {
let description = unsafe { CStr::from_ptr(ffi::opus_strerror(code)) }.to_str().unwrap();
let code = match code {
-1 => ErrorCode::BadArg,
-2 => ErrorCode::BufferTooSmall,
-3 => ErrorCode::InternalError,
-4 => ErrorCode::InvalidPacket,
-5 => ErrorCode::Unimplemented,
-6 => ErrorCode::InvalidState,
-7 => ErrorCode::AllocFail,
_ => ErrorCode::Unknown,
};
Error { function: what, description: description, code: code }
}
pub fn function(&self) -> &'static str { self.function }
pub fn description(&self) -> &'static str { self.description }
pub fn code(&self) -> ErrorCode { self.code }
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}: {}", self.function, self.description)
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
self.description
}
}
fn check(what: &'static str, code: c_int) -> Result<()> {
if code < 0 {
Err(Error::from_code(what, code))
} else {
Ok(())
}
}