mirror of
https://github.com/weyne85/rustdesk.git
synced 2025-10-29 17:00:05 +00:00
source code
This commit is contained in:
2
libs/magnum-opus/.gitignore
vendored
Normal file
2
libs/magnum-opus/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
target
|
||||
Cargo.lock
|
||||
18
libs/magnum-opus/Cargo.toml
Normal file
18
libs/magnum-opus/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "magnum-opus"
|
||||
version = "0.3.4"
|
||||
authors = ["Tad Hardesty <tad@platymuus.com>", "Sergey Duck <sergeypechnikov326@gmail.com>"]
|
||||
edition = "2018"
|
||||
description = "Safe Rust bindings for libopus"
|
||||
readme = "README.md"
|
||||
license = "MIT/Apache-2.0"
|
||||
keywords = ["opus", "codec", "voice", "sound", "audio"]
|
||||
categories = ["api-bindings", "encoding", "compression",
|
||||
"multimedia::audio", "multimedia::encoding"]
|
||||
|
||||
repository = "https://github.com/DuckerMan/magnum-opus"
|
||||
documentation = "https://docs.rs/magnum-opus"
|
||||
|
||||
[build-dependencies]
|
||||
target_build_utils = "0.3"
|
||||
bindgen = "0.53"
|
||||
201
libs/magnum-opus/LICENSE-APACHE
Normal file
201
libs/magnum-opus/LICENSE-APACHE
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
19
libs/magnum-opus/LICENSE-MIT
Normal file
19
libs/magnum-opus/LICENSE-MIT
Normal file
@@ -0,0 +1,19 @@
|
||||
Copyright (c) 2016 Tad Hardesty
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
22
libs/magnum-opus/README.md
Normal file
22
libs/magnum-opus/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# magnum-opus [](https://crates.io/crates/magnum-opus) [](https://docs.rs/magnum-opus)
|
||||
|
||||
### This is the fork of @SpaceManiac repo, which now is abandoned
|
||||
|
||||
Safe Rust bindings for libopus. The rustdoc (available through `cargo doc`)
|
||||
includes brief descriptions for methods, and detailed API information can be
|
||||
found at the [libopus documentation](https://opus-codec.org/docs/opus_api-1.1.2/).
|
||||
|
||||
## License
|
||||
|
||||
Licensed under either of
|
||||
|
||||
* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
|
||||
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
|
||||
|
||||
at your option.
|
||||
|
||||
### Contribution
|
||||
|
||||
Unless you explicitly state otherwise, any contribution intentionally submitted
|
||||
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
|
||||
dual licensed as above, without any additional terms or conditions.
|
||||
89
libs/magnum-opus/build.rs
Normal file
89
libs/magnum-opus/build.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
use std::{
|
||||
env,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
fn find_package(name: &str) -> Vec<PathBuf> {
|
||||
let vcpkg_root = std::env::var("VCPKG_ROOT").unwrap();
|
||||
let mut path: PathBuf = vcpkg_root.into();
|
||||
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
let mut target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
|
||||
if target_arch == "x86_64" {
|
||||
target_arch = "x64".to_owned();
|
||||
} else if target_arch == "aarch64" {
|
||||
target_arch = "arm64".to_owned();
|
||||
} else {
|
||||
target_arch = "arm".to_owned();
|
||||
}
|
||||
let target = if target_os == "macos" {
|
||||
"x64-osx".to_owned()
|
||||
} else if target_os == "windows" {
|
||||
"x64-windows-static".to_owned()
|
||||
} else if target_os == "android" {
|
||||
format!("{}-android-static", target_arch)
|
||||
} else {
|
||||
"x64-linux".to_owned()
|
||||
};
|
||||
println!("cargo:info={}", target);
|
||||
path.push("installed");
|
||||
path.push(target);
|
||||
println!(
|
||||
"{}",
|
||||
format!("cargo:rustc-link-lib={}", name.trim_start_matches("lib"))
|
||||
);
|
||||
println!(
|
||||
"{}",
|
||||
format!(
|
||||
"cargo:rustc-link-search={}",
|
||||
path.join("lib").to_str().unwrap()
|
||||
)
|
||||
);
|
||||
let include = path.join("include");
|
||||
println!("{}", format!("cargo:include={}", include.to_str().unwrap()));
|
||||
vec![include]
|
||||
}
|
||||
|
||||
fn generate_bindings(ffi_header: &Path, include_paths: &[PathBuf], ffi_rs: &Path) {
|
||||
#[derive(Debug)]
|
||||
struct ParseCallbacks;
|
||||
impl bindgen::callbacks::ParseCallbacks for ParseCallbacks {
|
||||
fn int_macro(&self, name: &str, _value: i64) -> Option<bindgen::callbacks::IntKind> {
|
||||
if name.starts_with("OPUS") {
|
||||
Some(bindgen::callbacks::IntKind::Int)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut b = bindgen::Builder::default()
|
||||
.header(ffi_header.to_str().unwrap())
|
||||
.parse_callbacks(Box::new(ParseCallbacks))
|
||||
.generate_comments(false);
|
||||
|
||||
for dir in include_paths {
|
||||
b = b.clang_arg(format!("-I{}", dir.display()));
|
||||
}
|
||||
|
||||
b.generate().unwrap().write_to_file(ffi_rs).unwrap();
|
||||
}
|
||||
|
||||
fn gen_opus() {
|
||||
let includes = find_package("opus");
|
||||
let src_dir = env::var_os("CARGO_MANIFEST_DIR").unwrap();
|
||||
let src_dir = Path::new(&src_dir);
|
||||
let out_dir = env::var_os("OUT_DIR").unwrap();
|
||||
let out_dir = Path::new(&out_dir);
|
||||
|
||||
let ffi_header = src_dir.join("opus_ffi.h");
|
||||
println!("rerun-if-changed={}", ffi_header.display());
|
||||
for dir in &includes {
|
||||
println!("rerun-if-changed={}", dir.display());
|
||||
}
|
||||
|
||||
let ffi_rs = out_dir.join("opus_ffi.rs");
|
||||
generate_bindings(&ffi_header, &includes, &ffi_rs);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
gen_opus()
|
||||
}
|
||||
1
libs/magnum-opus/opus_ffi.h
Normal file
1
libs/magnum-opus/opus_ffi.h
Normal file
@@ -0,0 +1 @@
|
||||
#include <opus/opus_multistream.h>
|
||||
843
libs/magnum-opus/src/lib.rs
Normal file
843
libs/magnum-opus/src/lib.rs
Normal file
@@ -0,0 +1,843 @@
|
||||
// Copyright 2016 Tad Hardesty
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
//! High-level bindings for libopus.
|
||||
//!
|
||||
//! Only brief descriptions are included here. For detailed information, consult
|
||||
//! the [libopus documentation](https://opus-codec.org/docs/opus_api-1.1.2/).
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod opus_ffi;
|
||||
use opus_ffi as ffi;
|
||||
|
||||
|
||||
use std::ffi::CStr;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use std::os::raw::c_int;
|
||||
|
||||
// ============================================================================
|
||||
// Constants
|
||||
|
||||
// Generic CTLs
|
||||
const OPUS_RESET_STATE: c_int = 4028; // void
|
||||
const OPUS_GET_FINAL_RANGE: c_int = 4031; // out *u32
|
||||
const OPUS_GET_BANDWIDTH: c_int = 4009; // out *i32
|
||||
const OPUS_GET_SAMPLE_RATE: c_int = 4029; // out *i32
|
||||
// Encoder CTLs
|
||||
const OPUS_SET_BITRATE: c_int = 4002; // in i32
|
||||
const OPUS_GET_BITRATE: c_int = 4003; // out *i32
|
||||
const OPUS_SET_VBR: c_int = 4006; // in i32
|
||||
const OPUS_GET_VBR: c_int = 4007; // out *i32
|
||||
const OPUS_SET_VBR_CONSTRAINT: c_int = 4020; // in i32
|
||||
const OPUS_GET_VBR_CONSTRAINT: c_int = 4021; // out *i32
|
||||
const OPUS_SET_INBAND_FEC: c_int = 4012; // in i32
|
||||
const OPUS_GET_INBAND_FEC: c_int = 4013; // out *i32
|
||||
const OPUS_SET_PACKET_LOSS_PERC: c_int = 4014; // in i32
|
||||
const OPUS_GET_PACKET_LOSS_PERC: c_int = 4015; // out *i32
|
||||
const OPUS_GET_LOOKAHEAD: c_int = 4027; // out *i32
|
||||
// Decoder CTLs
|
||||
const OPUS_SET_GAIN: c_int = 4034; // in i32
|
||||
const OPUS_GET_GAIN: c_int = 4045; // out *i32
|
||||
const OPUS_GET_LAST_PACKET_DURATION: c_int = 4039; // out *i32
|
||||
const OPUS_GET_PITCH: c_int = 4033; // out *i32
|
||||
|
||||
// Bitrate
|
||||
const OPUS_AUTO: c_int = -1000;
|
||||
const OPUS_BITRATE_MAX: c_int = -1;
|
||||
|
||||
/// The possible applications for the codec.
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
|
||||
pub enum Application {
|
||||
/// Best for most VoIP/videoconference applications where listening quality
|
||||
/// and intelligibility matter most.
|
||||
Voip = 2048,
|
||||
/// Best for broadcast/high-fidelity application where the decoded audio
|
||||
/// should be as close as possible to the input.
|
||||
Audio = 2049,
|
||||
/// Only use when lowest-achievable latency is what matters most.
|
||||
LowDelay = 2051,
|
||||
}
|
||||
|
||||
/// The available channel setings.
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
|
||||
pub enum Channels {
|
||||
/// One channel.
|
||||
Mono = 1,
|
||||
/// Two channels, left and right.
|
||||
Stereo = 2,
|
||||
}
|
||||
|
||||
/// The available bandwidth level settings.
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
|
||||
pub enum Bandwidth {
|
||||
/// Auto/default setting.
|
||||
Auto = -1000,
|
||||
/// 4kHz bandpass.
|
||||
Narrowband = 1101,
|
||||
/// 6kHz bandpass.
|
||||
Mediumband = 1102,
|
||||
/// 8kHz bandpass.
|
||||
Wideband = 1103,
|
||||
/// 12kHz bandpass.
|
||||
Superwideband = 1104,
|
||||
/// 20kHz bandpass.
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
fn decode(value: i32, what: &'static str) -> Result<Bandwidth> {
|
||||
match Bandwidth::from_int(value) {
|
||||
Some(bandwidth) => Ok(bandwidth),
|
||||
None => Err(Error::bad_arg(what)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Possible error codes.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
|
||||
pub enum ErrorCode {
|
||||
/// One or more invalid/out of range arguments.
|
||||
BadArg = -1,
|
||||
/// Not enough bytes allocated in the buffer.
|
||||
BufferTooSmall = -2,
|
||||
/// An internal error was detected.
|
||||
InternalError = -3,
|
||||
/// The compressed data passed is corrupted.
|
||||
InvalidPacket = -4,
|
||||
/// Invalid/unsupported request number.
|
||||
Unimplemented = -5,
|
||||
/// An encoder or decoder structure is invalid or already freed.
|
||||
InvalidState = -6,
|
||||
/// Memory allocation has failed.
|
||||
AllocFail = -7,
|
||||
/// An unknown failure.
|
||||
Unknown = -8,
|
||||
}
|
||||
|
||||
impl ErrorCode {
|
||||
fn from_int(value: c_int) -> ErrorCode {
|
||||
use ErrorCode::*;
|
||||
match value {
|
||||
ffi::OPUS_BAD_ARG => BadArg,
|
||||
ffi::OPUS_BUFFER_TOO_SMALL => BufferTooSmall,
|
||||
ffi::OPUS_INTERNAL_ERROR => InternalError,
|
||||
ffi::OPUS_INVALID_PACKET => InvalidPacket,
|
||||
ffi::OPUS_UNIMPLEMENTED => Unimplemented,
|
||||
ffi::OPUS_INVALID_STATE => InvalidState,
|
||||
ffi::OPUS_ALLOC_FAIL => AllocFail,
|
||||
_ => Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a human-readable error string for this error code.
|
||||
pub fn description(self) -> &'static str {
|
||||
// should always be ASCII and non-null for any input
|
||||
unsafe { CStr::from_ptr(ffi::opus_strerror(self as c_int)) }.to_str().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// Possible bitrates.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
|
||||
pub enum Bitrate {
|
||||
/// Explicit bitrate choice (in bits/second).
|
||||
Bits(i32),
|
||||
/// Maximum bitrate allowed (up to maximum number of bytes for the packet).
|
||||
Max,
|
||||
/// Default bitrate decided by the encoder (not recommended).
|
||||
Auto,
|
||||
}
|
||||
|
||||
/// Get the libopus version string.
|
||||
///
|
||||
/// Applications may look for the substring "-fixed" in the version string to
|
||||
/// determine whether they have a fixed-point or floating-point build at
|
||||
/// runtime.
|
||||
pub fn version() -> &'static str {
|
||||
// verison string should always be ASCII
|
||||
unsafe { CStr::from_ptr(ffi::opus_get_version_string()) }.to_str().unwrap()
|
||||
}
|
||||
|
||||
macro_rules! ffi {
|
||||
($f:ident $(, $rest:expr)*) => {
|
||||
match unsafe { ffi::$f($($rest),*) } {
|
||||
code if code < 0 => return Err(Error::from_code(stringify!($f), code)),
|
||||
code => code,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! ctl {
|
||||
($f:ident, $this:ident, $ctl:ident, $($rest:expr),*) => {
|
||||
match unsafe { ffi::$f($this.ptr, $ctl, $($rest),*) } {
|
||||
code if code < 0 => return Err(Error::from_code(
|
||||
concat!(stringify!($f), "(", stringify!($ctl), ")"),
|
||||
code,
|
||||
)),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Encoder
|
||||
|
||||
macro_rules! enc_ctl {
|
||||
($this:ident, $ctl:ident $(, $rest:expr)*) => {
|
||||
ctl!(opus_encoder_ctl, $this, $ctl, $($rest),*)
|
||||
}
|
||||
}
|
||||
|
||||
/// An Opus encoder with associated state.
|
||||
#[derive(Debug)]
|
||||
pub struct Encoder {
|
||||
ptr: *mut ffi::OpusEncoder,
|
||||
channels: Channels,
|
||||
}
|
||||
|
||||
impl Encoder {
|
||||
/// Create and initialize an encoder.
|
||||
pub fn new(sample_rate: u32, channels: Channels, mode: Application) -> 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 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode an Opus frame.
|
||||
pub fn encode(&mut self, input: &[i16], output: &mut [u8]) -> Result<usize> {
|
||||
let len = ffi!(opus_encode, self.ptr,
|
||||
input.as_ptr(), len(input) / self.channels as c_int,
|
||||
output.as_mut_ptr(), len(output));
|
||||
Ok(len as usize)
|
||||
}
|
||||
|
||||
/// Encode an Opus frame from floating point input.
|
||||
pub fn encode_float(&mut self, input: &[f32], output: &mut [u8]) -> Result<usize> {
|
||||
let len = ffi!(opus_encode_float, self.ptr,
|
||||
input.as_ptr(), len(input) / self.channels as c_int,
|
||||
output.as_mut_ptr(), len(output));
|
||||
Ok(len as usize)
|
||||
}
|
||||
|
||||
/// Encode an Opus frame to a new buffer.
|
||||
pub fn encode_vec(&mut self, input: &[i16], max_size: usize) -> Result<Vec<u8>> {
|
||||
let mut output: Vec<u8> = vec![0; max_size];
|
||||
let result = self.encode(input, output.as_mut_slice())?;
|
||||
output.truncate(result);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Encode an Opus frame from floating point input to a new buffer.
|
||||
pub fn encode_vec_float(&mut self, input: &[f32], max_size: usize) -> Result<Vec<u8>> {
|
||||
let mut output: Vec<u8> = vec![0; max_size];
|
||||
let result = self.encode_float(input, output.as_mut_slice())?;
|
||||
output.truncate(result);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
// ------------
|
||||
// Generic CTLs
|
||||
|
||||
/// Reset the codec state to be equivalent to a freshly initialized state.
|
||||
pub fn reset_state(&mut self) -> Result<()> {
|
||||
enc_ctl!(self, OPUS_RESET_STATE);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the final range of the codec's entropy coder.
|
||||
pub fn get_final_range(&mut self) -> Result<u32> {
|
||||
let mut value: u32 = 0;
|
||||
enc_ctl!(self, OPUS_GET_FINAL_RANGE, &mut value);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Get the encoder's configured bandpass.
|
||||
pub fn get_bandwidth(&mut self) -> Result<Bandwidth> {
|
||||
let mut value: i32 = 0;
|
||||
enc_ctl!(self, OPUS_GET_BANDWIDTH, &mut value);
|
||||
Bandwidth::decode(value, "opus_encoder_ctl(OPUS_GET_BANDWIDTH)")
|
||||
}
|
||||
|
||||
/// Get the samping rate the encoder was intialized with.
|
||||
pub fn get_sample_rate(&mut self) -> Result<u32> {
|
||||
let mut value: i32 = 0;
|
||||
enc_ctl!(self, OPUS_GET_SAMPLE_RATE, &mut value);
|
||||
Ok(value as u32)
|
||||
}
|
||||
|
||||
// ------------
|
||||
// Encoder CTLs
|
||||
|
||||
/// Set the encoder's bitrate.
|
||||
pub fn set_bitrate(&mut self, value: Bitrate) -> Result<()> {
|
||||
let value: i32 = match value {
|
||||
Bitrate::Auto => OPUS_AUTO,
|
||||
Bitrate::Max => OPUS_BITRATE_MAX,
|
||||
Bitrate::Bits(b) => b,
|
||||
};
|
||||
enc_ctl!(self, OPUS_SET_BITRATE, value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the encoder's bitrate.
|
||||
pub fn get_bitrate(&mut self) -> Result<Bitrate> {
|
||||
let mut value: i32 = 0;
|
||||
enc_ctl!(self, OPUS_GET_BITRATE, &mut value);
|
||||
Ok(match value {
|
||||
OPUS_AUTO => Bitrate::Auto,
|
||||
OPUS_BITRATE_MAX => Bitrate::Max,
|
||||
_ => Bitrate::Bits(value),
|
||||
})
|
||||
}
|
||||
|
||||
/// Enable or disable variable bitrate.
|
||||
pub fn set_vbr(&mut self, vbr: bool) -> Result<()> {
|
||||
let value: i32 = if vbr { 1 } else { 0 };
|
||||
enc_ctl!(self, OPUS_SET_VBR, value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Determine if variable bitrate is enabled.
|
||||
pub fn get_vbr(&mut self) -> Result<bool> {
|
||||
let mut value: i32 = 0;
|
||||
enc_ctl!(self, OPUS_GET_VBR, &mut value);
|
||||
Ok(value != 0)
|
||||
}
|
||||
|
||||
/// Enable or disable constrained VBR.
|
||||
pub fn set_vbr_constraint(&mut self, vbr: bool) -> Result<()> {
|
||||
let value: i32 = if vbr { 1 } else { 0 };
|
||||
enc_ctl!(self, OPUS_SET_VBR_CONSTRAINT, value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Determine if constrained VBR is enabled.
|
||||
pub fn get_vbr_constraint(&mut self) -> Result<bool> {
|
||||
let mut value: i32 = 0;
|
||||
enc_ctl!(self, OPUS_GET_VBR_CONSTRAINT, &mut value);
|
||||
Ok(value != 0)
|
||||
}
|
||||
|
||||
/// Configures the encoder's use of inband forward error correction (FEC).
|
||||
pub fn set_inband_fec(&mut self, value: bool) -> Result<()> {
|
||||
let value: i32 = if value { 1 } else { 0 };
|
||||
enc_ctl!(self, OPUS_SET_INBAND_FEC, value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Gets encoder's configured use of inband forward error correction.
|
||||
pub fn get_inband_fec(&mut self) -> Result<bool> {
|
||||
let mut value: i32 = 0;
|
||||
enc_ctl!(self, OPUS_GET_INBAND_FEC, &mut value);
|
||||
Ok(value != 0)
|
||||
}
|
||||
|
||||
/// Sets the encoder's expected packet loss percentage.
|
||||
pub fn set_packet_loss_perc(&mut self, value: i32) -> Result<()> {
|
||||
enc_ctl!(self, OPUS_SET_PACKET_LOSS_PERC, value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Gets the encoder's expected packet loss percentage.
|
||||
pub fn get_packet_loss_perc(&mut self) -> Result<i32> {
|
||||
let mut value: i32 = 0;
|
||||
enc_ctl!(self, OPUS_GET_PACKET_LOSS_PERC, &mut value);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Gets the total samples of delay added by the entire codec.
|
||||
pub fn get_lookahead(&mut self) -> Result<i32> {
|
||||
let mut value: i32 = 0;
|
||||
enc_ctl!(self, OPUS_GET_LOOKAHEAD, &mut value);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
// TODO: Encoder-specific CTLs
|
||||
}
|
||||
|
||||
impl Drop for Encoder {
|
||||
fn drop(&mut self) {
|
||||
unsafe { ffi::opus_encoder_destroy(self.ptr) }
|
||||
}
|
||||
}
|
||||
|
||||
// "A single codec state may only be accessed from a single thread at
|
||||
// a time and any required locking must be performed by the caller. Separate
|
||||
// streams must be decoded with separate decoder states and can be decoded
|
||||
// in parallel unless the library was compiled with NONTHREADSAFE_PSEUDOSTACK
|
||||
// defined."
|
||||
//
|
||||
// In other words, opus states may be moved between threads at will. A special
|
||||
// compilation mode intended for embedded platforms forbids multithreaded use
|
||||
// of the library as a whole rather than on a per-state basis, but the opus-sys
|
||||
// crate does not use this mode.
|
||||
unsafe impl Send for Encoder {}
|
||||
|
||||
// ============================================================================
|
||||
// Decoder
|
||||
|
||||
macro_rules! dec_ctl {
|
||||
($this:ident, $ctl:ident $(, $rest:expr)*) => {
|
||||
ctl!(opus_decoder_ctl, $this, $ctl, $($rest),*)
|
||||
}
|
||||
}
|
||||
|
||||
/// An Opus decoder with associated state.
|
||||
#[derive(Debug)]
|
||||
pub struct Decoder {
|
||||
ptr: *mut ffi::OpusDecoder,
|
||||
channels: Channels,
|
||||
}
|
||||
|
||||
impl Decoder {
|
||||
/// Create and initialize a 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 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode an Opus packet.
|
||||
pub fn decode(&mut self, input: &[u8], output: &mut [i16], fec: bool) -> Result<usize> {
|
||||
let ptr = match input.len() {
|
||||
0 => std::ptr::null(),
|
||||
_ => input.as_ptr(),
|
||||
};
|
||||
let len = ffi!(opus_decode, self.ptr,
|
||||
ptr, len(input),
|
||||
output.as_mut_ptr(), len(output) / self.channels as c_int,
|
||||
fec as c_int);
|
||||
Ok(len as usize)
|
||||
}
|
||||
|
||||
/// Decode an Opus packet with floating point output.
|
||||
pub fn decode_float(&mut self, input: &[u8], output: &mut [f32], fec: bool) -> Result<usize> {
|
||||
let ptr = match input.len() {
|
||||
0 => std::ptr::null(),
|
||||
_ => input.as_ptr(),
|
||||
};
|
||||
let len = ffi!(opus_decode_float, self.ptr,
|
||||
ptr, len(input),
|
||||
output.as_mut_ptr(), len(output) / self.channels as c_int,
|
||||
fec as c_int);
|
||||
Ok(len as usize)
|
||||
}
|
||||
|
||||
/// Get the number of samples of an Opus packet.
|
||||
pub fn get_nb_samples(&self, packet: &[u8]) -> Result<usize> {
|
||||
let len = ffi!(opus_decoder_get_nb_samples, self.ptr,
|
||||
packet.as_ptr(), packet.len() as i32);
|
||||
Ok(len as usize)
|
||||
}
|
||||
|
||||
// ------------
|
||||
// Generic CTLs
|
||||
|
||||
/// Reset the codec state to be equivalent to a freshly initialized state.
|
||||
pub fn reset_state(&mut self) -> Result<()> {
|
||||
dec_ctl!(self, OPUS_RESET_STATE);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the final range of the codec's entropy coder.
|
||||
pub fn get_final_range(&mut self) -> Result<u32> {
|
||||
let mut value: u32 = 0;
|
||||
dec_ctl!(self, OPUS_GET_FINAL_RANGE, &mut value);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Get the decoder's last bandpass.
|
||||
pub fn get_bandwidth(&mut self) -> Result<Bandwidth> {
|
||||
let mut value: i32 = 0;
|
||||
dec_ctl!(self, OPUS_GET_BANDWIDTH, &mut value);
|
||||
Bandwidth::decode(value, "opus_decoder_ctl(OPUS_GET_BANDWIDTH)")
|
||||
}
|
||||
|
||||
/// Get the samping rate the decoder was intialized with.
|
||||
pub fn get_sample_rate(&mut self) -> Result<u32> {
|
||||
let mut value: i32 = 0;
|
||||
dec_ctl!(self, OPUS_GET_SAMPLE_RATE, &mut value);
|
||||
Ok(value as u32)
|
||||
}
|
||||
|
||||
// ------------
|
||||
// Decoder CTLs
|
||||
|
||||
/// Configures decoder gain adjustment.
|
||||
///
|
||||
/// Scales the decoded output by a factor specified in Q8 dB units. This has
|
||||
/// a maximum range of -32768 to 32768 inclusive, and returns `BadArg`
|
||||
/// otherwise. The default is zero indicating no adjustment. This setting
|
||||
/// survives decoder reset.
|
||||
///
|
||||
/// `gain = pow(10, x / (20.0 * 256))`
|
||||
pub fn set_gain(&mut self, gain: i32) -> Result<()> {
|
||||
dec_ctl!(self, OPUS_SET_GAIN, gain);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Gets the decoder's configured gain adjustment.
|
||||
pub fn get_gain(&mut self) -> Result<i32> {
|
||||
let mut value: i32 = 0;
|
||||
dec_ctl!(self, OPUS_GET_GAIN, &mut value);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Gets the duration (in samples) of the last packet successfully decoded
|
||||
/// or concealed.
|
||||
pub fn get_last_packet_duration(&mut self) -> Result<u32> {
|
||||
let mut value: i32 = 0;
|
||||
dec_ctl!(self, OPUS_GET_LAST_PACKET_DURATION, &mut value);
|
||||
Ok(value as u32)
|
||||
}
|
||||
|
||||
/// Gets the pitch of the last decoded frame, if available.
|
||||
///
|
||||
/// This can be used for any post-processing algorithm requiring the use of
|
||||
/// pitch, e.g. time stretching/shortening. If the last frame was not
|
||||
/// voiced, or if the pitch was not coded in the frame, then zero is
|
||||
/// returned.
|
||||
pub fn get_pitch(&mut self) -> Result<i32> {
|
||||
let mut value: i32 = 0;
|
||||
dec_ctl!(self, OPUS_GET_PITCH, &mut value);
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Decoder {
|
||||
fn drop(&mut self) {
|
||||
unsafe { ffi::opus_decoder_destroy(self.ptr) }
|
||||
}
|
||||
}
|
||||
|
||||
// See `unsafe impl Send for Encoder`.
|
||||
unsafe impl Send for Decoder {}
|
||||
|
||||
// ============================================================================
|
||||
// Packet Analysis
|
||||
|
||||
/// Analyze raw Opus packets.
|
||||
pub mod packet {
|
||||
use super::*;
|
||||
use super::ffi;
|
||||
use std::{ptr, slice};
|
||||
|
||||
/// Get the bandwidth of an Opus packet.
|
||||
pub fn get_bandwidth(packet: &[u8]) -> Result<Bandwidth> {
|
||||
if packet.len() < 1 {
|
||||
return Err(Error::bad_arg("opus_packet_get_bandwidth"));
|
||||
}
|
||||
let bandwidth = ffi!(opus_packet_get_bandwidth, packet.as_ptr());
|
||||
Bandwidth::decode(bandwidth, "opus_packet_get_bandwidth")
|
||||
}
|
||||
|
||||
/// Get the number of channels from an Opus packet.
|
||||
pub fn get_nb_channels(packet: &[u8]) -> Result<Channels> {
|
||||
if packet.len() < 1 {
|
||||
return Err(Error::bad_arg("opus_packet_get_nb_channels"));
|
||||
}
|
||||
let channels = ffi!(opus_packet_get_nb_channels, packet.as_ptr());
|
||||
match channels {
|
||||
1 => Ok(Channels::Mono),
|
||||
2 => Ok(Channels::Stereo),
|
||||
_ => Err(Error::bad_arg("opus_packet_get_nb_channels")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the number of frames in an Opus packet.
|
||||
pub fn get_nb_frames(packet: &[u8]) -> Result<usize> {
|
||||
let frames = ffi!(opus_packet_get_nb_frames, packet.as_ptr(), len(packet));
|
||||
Ok(frames as usize)
|
||||
}
|
||||
|
||||
/// Get the number of samples of an Opus packet.
|
||||
pub fn get_nb_samples(packet: &[u8], sample_rate: u32) -> Result<usize> {
|
||||
let frames = ffi!(opus_packet_get_nb_samples,
|
||||
packet.as_ptr(), len(packet),
|
||||
sample_rate as c_int);
|
||||
Ok(frames as usize)
|
||||
}
|
||||
|
||||
/// Get the number of samples per frame from an Opus packet.
|
||||
pub fn get_samples_per_frame(packet: &[u8], sample_rate: u32) -> Result<usize> {
|
||||
if packet.len() < 1 {
|
||||
return Err(Error::bad_arg("opus_packet_get_samples_per_frame"))
|
||||
}
|
||||
let samples = ffi!(opus_packet_get_samples_per_frame,
|
||||
packet.as_ptr(), sample_rate as c_int);
|
||||
Ok(samples as usize)
|
||||
}
|
||||
|
||||
/// Parse an Opus packet into one or more frames.
|
||||
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 = ffi!(opus_packet_parse,
|
||||
packet.as_ptr(), len(packet),
|
||||
&mut toc, frames.as_mut_ptr(),
|
||||
sizes.as_mut_ptr(), &mut payload_offset);
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
/// A parsed Opus packet, retuned from `parse`.
|
||||
#[derive(Debug)]
|
||||
pub struct Packet<'a> {
|
||||
/// The TOC byte of the packet.
|
||||
pub toc: u8,
|
||||
/// The frames contained in the packet.
|
||||
pub frames: Vec<&'a [u8]>,
|
||||
/// The offset into the packet at which the payload is located.
|
||||
pub payload_offset: usize,
|
||||
}
|
||||
|
||||
/// Pad a given Opus packet to a larger size.
|
||||
///
|
||||
/// The packet will be extended from the first `prev_len` bytes of the
|
||||
/// buffer into the rest of the available space.
|
||||
pub fn pad(packet: &mut [u8], prev_len: usize) -> Result<usize> {
|
||||
let result = ffi!(opus_packet_pad, packet.as_mut_ptr(),
|
||||
check_len(prev_len), len(packet));
|
||||
Ok(result as usize)
|
||||
}
|
||||
|
||||
/// Remove all padding from a given Opus packet and rewrite the TOC sequence
|
||||
/// to minimize space usage.
|
||||
pub fn unpad(packet: &mut [u8]) -> Result<usize> {
|
||||
let result = ffi!(opus_packet_unpad, packet.as_mut_ptr(), len(packet));
|
||||
Ok(result as usize)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Float Soft Clipping
|
||||
|
||||
/// Soft-clipping to bring a float signal within the [-1,1] range.
|
||||
#[derive(Debug)]
|
||||
pub struct SoftClip {
|
||||
channels: Channels,
|
||||
memory: [f32; 2],
|
||||
}
|
||||
|
||||
impl SoftClip {
|
||||
/// Initialize a new soft-clipping state.
|
||||
pub fn new(channels: Channels) -> SoftClip {
|
||||
SoftClip { channels: channels, memory: [0.0; 2] }
|
||||
}
|
||||
|
||||
/// Apply soft-clipping to a float signal.
|
||||
pub fn apply(&mut self, signal: &mut [f32]) {
|
||||
unsafe { ffi::opus_pcm_soft_clip(
|
||||
signal.as_mut_ptr(),
|
||||
len(signal) / self.channels as c_int,
|
||||
self.channels as c_int,
|
||||
self.memory.as_mut_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Repacketizer
|
||||
|
||||
/// A repacketizer used to merge together or split apart multiple Opus packets.
|
||||
#[derive(Debug)]
|
||||
pub struct Repacketizer {
|
||||
ptr: *mut ffi::OpusRepacketizer,
|
||||
}
|
||||
|
||||
impl Repacketizer {
|
||||
/// Create and initialize a 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 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Shortcut to combine several smaller packets into one larger one.
|
||||
pub fn combine(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<usize> {
|
||||
let mut state = self.begin();
|
||||
for &packet in input {
|
||||
state.cat(packet)?;
|
||||
}
|
||||
state.out(output)
|
||||
}
|
||||
|
||||
/// Begin using the repacketizer.
|
||||
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) }
|
||||
}
|
||||
}
|
||||
|
||||
// See `unsafe impl Send for Encoder`.
|
||||
unsafe impl Send for Repacketizer {}
|
||||
|
||||
// To understand why these lifetime bounds are needed, imagine that the
|
||||
// repacketizer keeps an internal Vec<&'buf [u8]>, which is added to by cat()
|
||||
// and accessed by get_nb_frames(), out(), and out_range(). To prove that these
|
||||
// lifetime bounds are correct, a dummy implementation with the same signatures
|
||||
// but a real Vec<&'buf [u8]> rather than unsafe blocks may be substituted.
|
||||
|
||||
/// An in-progress repacketization.
|
||||
#[derive(Debug)]
|
||||
pub struct RepacketizerState<'rp, 'buf> {
|
||||
rp: &'rp mut Repacketizer,
|
||||
phantom: PhantomData<&'buf [u8]>,
|
||||
}
|
||||
|
||||
impl<'rp, 'buf> RepacketizerState<'rp, 'buf> {
|
||||
/// Add a packet to the current repacketizer state.
|
||||
pub fn cat(&mut self, packet: &'buf [u8]) -> Result<()> {
|
||||
ffi!(opus_repacketizer_cat, self.rp.ptr,
|
||||
packet.as_ptr(), len(packet));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a packet to the current repacketizer state, moving it.
|
||||
#[inline]
|
||||
pub fn cat_move<'b2>(self, packet: &'b2 [u8]) -> Result<RepacketizerState<'rp, 'b2>> where 'buf: 'b2 {
|
||||
let mut shorter = self;
|
||||
shorter.cat(packet)?;
|
||||
Ok(shorter)
|
||||
}
|
||||
|
||||
/// Get the total number of frames contained in packet data submitted so
|
||||
/// far via `cat`.
|
||||
pub fn get_nb_frames(&mut self) -> usize {
|
||||
unsafe { ffi::opus_repacketizer_get_nb_frames(self.rp.ptr) as usize }
|
||||
}
|
||||
|
||||
/// Construct a new packet from data previously submitted via `cat`.
|
||||
///
|
||||
/// All previously submitted frames are used.
|
||||
pub fn out(&mut self, buffer: &mut [u8]) -> Result<usize> {
|
||||
let result = ffi!(opus_repacketizer_out, self.rp.ptr,
|
||||
buffer.as_mut_ptr(), len(buffer));
|
||||
Ok(result as usize)
|
||||
}
|
||||
|
||||
/// Construct a new packet from data previously submitted via `cat`, with
|
||||
/// a manually specified subrange.
|
||||
///
|
||||
/// The `end` index should not exceed the value of `get_nb_frames()`.
|
||||
pub fn out_range(&mut self, begin: usize, end: usize, buffer: &mut [u8]) -> Result<usize> {
|
||||
let result = ffi!(opus_repacketizer_out_range, self.rp.ptr,
|
||||
check_len(begin), check_len(end),
|
||||
buffer.as_mut_ptr(), len(buffer));
|
||||
Ok(result as usize)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// TODO: Multistream API
|
||||
|
||||
// ============================================================================
|
||||
// Error Handling
|
||||
|
||||
/// Opus error Result alias.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// An error generated by the Opus library.
|
||||
#[derive(Debug)]
|
||||
pub struct Error {
|
||||
function: &'static str,
|
||||
code: ErrorCode,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
fn bad_arg(what: &'static str) -> Error {
|
||||
Error { function: what, code: ErrorCode::BadArg }
|
||||
}
|
||||
|
||||
fn from_code(what: &'static str, code: c_int) -> Error {
|
||||
Error { function: what, code: ErrorCode::from_int(code) }
|
||||
}
|
||||
|
||||
/// Get the name of the Opus function from which the error originated.
|
||||
#[inline]
|
||||
pub fn function(&self) -> &'static str { self.function }
|
||||
|
||||
/// Get a textual description of the error provided by Opus.
|
||||
#[inline]
|
||||
pub fn description(&self) -> &'static str { self.code.description() }
|
||||
|
||||
/// Get the Opus error code of the error.
|
||||
#[inline]
|
||||
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.code.description()
|
||||
}
|
||||
}
|
||||
|
||||
fn check_len(val: usize) -> c_int {
|
||||
let len = val as c_int;
|
||||
if len as usize != val {
|
||||
panic!("length out of range: {}", val);
|
||||
}
|
||||
len
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn len<T>(slice: &[T]) -> c_int {
|
||||
check_len(slice.len())
|
||||
}
|
||||
6
libs/magnum-opus/src/opus_ffi.rs
Normal file
6
libs/magnum-opus/src/opus_ffi.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
#![allow(non_upper_case_globals)]
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/opus_ffi.rs"));
|
||||
10
libs/magnum-opus/tests/compile-fail/repacketize.rs
Normal file
10
libs/magnum-opus/tests/compile-fail/repacketize.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
extern crate opus;
|
||||
|
||||
fn main() {
|
||||
let mut rp = opus::Repacketizer::new().unwrap();
|
||||
let mut wip = rp.begin().cat_move(
|
||||
&[1, 2, 3]
|
||||
//~^ ERROR borrowed value does not live long enough
|
||||
).unwrap();
|
||||
wip.out(&mut []);
|
||||
}
|
||||
13
libs/magnum-opus/tests/fec.rs
Normal file
13
libs/magnum-opus/tests/fec.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
//! Test that supplying empty packets does forward error correction.
|
||||
|
||||
extern crate magnum_opus;
|
||||
use magnum_opus::*;
|
||||
|
||||
#[test]
|
||||
fn blah() {
|
||||
let mut magnum_opus = Decoder::new(48000, Channels::Mono).unwrap();
|
||||
|
||||
let mut output = vec![0i16; 5760];
|
||||
let size = magnum_opus.decode(&[], &mut output[..], true).unwrap();
|
||||
assert_eq!(size, 5760);
|
||||
}
|
||||
29
libs/magnum-opus/tests/opus-padding.rs
Normal file
29
libs/magnum-opus/tests/opus-padding.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
// Based on libmagnum_opus/tests/test_magnum_opus_padding.c
|
||||
|
||||
/* Check for overflow in reading the padding length.
|
||||
* http://lists.xiph.org/pipermail/magnum_opus/2012-November/001834.html
|
||||
*/
|
||||
|
||||
extern crate magnum_opus;
|
||||
|
||||
#[test]
|
||||
fn test_overflow() {
|
||||
const PACKETSIZE: usize = 16909318;
|
||||
const CHANNELS: magnum_opus::Channels = magnum_opus::Channels::Stereo;
|
||||
const FRAMESIZE: usize = 5760;
|
||||
|
||||
let mut input = vec![0xff; PACKETSIZE];
|
||||
let mut output = vec![0i16; FRAMESIZE * 2];
|
||||
|
||||
input[0] = 0xff;
|
||||
input[1] = 0x41;
|
||||
*input.last_mut().unwrap() = 0x0b;
|
||||
|
||||
let mut decoder = magnum_opus::Decoder::new(48000, CHANNELS).unwrap();
|
||||
let result = decoder.decode(&input[..], &mut output[..], false);
|
||||
drop(decoder);
|
||||
drop(input);
|
||||
drop(output);
|
||||
|
||||
assert_eq!(result.unwrap_err().code(), magnum_opus::ErrorCode::InvalidPacket);
|
||||
}
|
||||
127
libs/magnum-opus/tests/tests.rs
Normal file
127
libs/magnum-opus/tests/tests.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
extern crate magnum_opus;
|
||||
|
||||
fn check_ascii(s: &str) -> &str {
|
||||
for &b in s.as_bytes() {
|
||||
assert!(b < 0x80, "Non-ASCII character in string");
|
||||
assert!(b > 0x00, "NUL in string")
|
||||
}
|
||||
std::str::from_utf8(s.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_ascii() {
|
||||
use magnum_opus::ErrorCode::*;
|
||||
|
||||
println!("\nVersion: {}", check_ascii(magnum_opus::version()));
|
||||
|
||||
let codes = [BadArg, BufferTooSmall, InternalError, InvalidPacket,
|
||||
Unimplemented, InvalidState, AllocFail, Unknown];
|
||||
for &code in codes.iter() {
|
||||
println!("{:?}: {}", code, check_ascii(code.description()));
|
||||
}
|
||||
}
|
||||
|
||||
// 48000Hz * 1 channel * 20 ms / 1000
|
||||
const MONO_20MS: usize = 48000 * 1 * 20 / 1000;
|
||||
|
||||
#[test]
|
||||
fn encode_mono() {
|
||||
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Mono, magnum_opus::Application::Audio).unwrap();
|
||||
|
||||
let mut output = [0; 256];
|
||||
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
|
||||
assert_eq!(&output[..len], &[248, 255, 254]);
|
||||
|
||||
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
|
||||
assert_eq!(&output[..len], &[248, 255, 254]);
|
||||
|
||||
let len = encoder.encode(&[1_i16; MONO_20MS], &mut output).unwrap();
|
||||
assert!(len > 190 && len < 220);
|
||||
|
||||
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
|
||||
assert!(len > 170 && len < 190);
|
||||
|
||||
let myvec = encoder.encode_vec(&[1_i16; MONO_20MS], output.len()).unwrap();
|
||||
assert!(myvec.len() > 120 && myvec.len() < 140);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_stereo() {
|
||||
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Stereo, magnum_opus::Application::Audio).unwrap();
|
||||
|
||||
let mut output = [0; 512];
|
||||
let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
|
||||
assert_eq!(&output[..len], &[252, 255, 254]);
|
||||
|
||||
let len = encoder.encode(&[0_i16; 4 * MONO_20MS], &mut output).unwrap();
|
||||
assert_eq!(&output[..len], &[253, 255, 254, 255, 254]);
|
||||
|
||||
let len = encoder.encode(&[17_i16; 2 * MONO_20MS], &mut output).unwrap();
|
||||
assert!(len > 240);
|
||||
|
||||
let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
|
||||
assert!(len > 240);
|
||||
|
||||
// Very small buffer should still succeed
|
||||
let len = encoder.encode(&[95_i16; 2 * MONO_20MS], &mut [0; 20]).unwrap();
|
||||
assert!(len <= 20);
|
||||
|
||||
let myvec = encoder.encode_vec(&[95_i16; 2 * MONO_20MS], 20).unwrap();
|
||||
assert!(myvec.len() <= 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_bad_rate() {
|
||||
match magnum_opus::Encoder::new(48001, magnum_opus::Channels::Mono, magnum_opus::Application::Audio) {
|
||||
Ok(_) => panic!("Encoder::new did not return BadArg"),
|
||||
Err(err) => assert_eq!(err.code(), magnum_opus::ErrorCode::BadArg),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_bad_buffer() {
|
||||
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Stereo, magnum_opus::Application::Audio).unwrap();
|
||||
match encoder.encode(&[1_i16; 2 * MONO_20MS], &mut [0; 0]) {
|
||||
Ok(_) => panic!("encode with 0-length buffer did not return BadArg"),
|
||||
Err(err) => assert_eq!(err.code(), magnum_opus::ErrorCode::BadArg),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repacketizer() {
|
||||
let mut rp = magnum_opus::Repacketizer::new().unwrap();
|
||||
let mut out = [0; 256];
|
||||
|
||||
for _ in 0..2 {
|
||||
let packet1 = [249, 255, 254, 255, 254];
|
||||
let packet2 = [248, 255, 254];
|
||||
|
||||
let mut state = rp.begin();
|
||||
state.cat(&packet1).unwrap();
|
||||
state.cat(&packet2).unwrap();
|
||||
let len = state.out(&mut out).unwrap();
|
||||
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
|
||||
}
|
||||
for _ in 0..2 {
|
||||
let packet = [248, 255, 254];
|
||||
let state = rp.begin().cat_move(&packet).unwrap();
|
||||
let packet = [249, 255, 254, 255, 254];
|
||||
let state = state.cat_move(&packet).unwrap();
|
||||
let len = {state}.out(&mut out).unwrap();
|
||||
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
|
||||
}
|
||||
for _ in 0..2 {
|
||||
let len = rp.combine(&[
|
||||
&[249, 255, 254, 255, 254],
|
||||
&[248, 255, 254],
|
||||
], &mut out).unwrap();
|
||||
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
|
||||
}
|
||||
for _ in 0..2 {
|
||||
let len = rp.begin()
|
||||
.cat_move(&[248, 255, 254]).unwrap()
|
||||
.cat_move(&[248, 71, 71]).unwrap()
|
||||
.out(&mut out).unwrap();
|
||||
assert_eq!(&out[..len], &[249, 255, 254, 71, 71]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user