mirror of
https://github.com/darksaid98/mediaplex.git
synced 2026-12-02 06:28:51 +00:00
0.0.2
This commit is contained in:
1 parent
33426fd667
commit
1b90c1f497
30 files changed
+796
-323
No files matched your search
@@ -1,76 +0,0 @@
|
||||
use std::ops::Deref;
|
||||
use thiserror::Error;
|
||||
|
||||
pub mod symphonia_decoder;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum DecoderError {
|
||||
#[error("Symphonia Decoder Error: {0}")]
|
||||
SymphoniaDecoder(String),
|
||||
}
|
||||
|
||||
pub type DecoderResult<T> = Result<T, DecoderError>;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum AudioPacketError {
|
||||
#[error("Decoder Raw Error: Can't return Raw on Samples")]
|
||||
Raw,
|
||||
#[error("Decoder Samples Error: Can't return Samples on Raw")]
|
||||
Samples,
|
||||
}
|
||||
|
||||
pub type AudioPacketResult<T> = Result<T, AudioPacketError>;
|
||||
|
||||
pub enum AudioPacket {
|
||||
Samples(Vec<f64>),
|
||||
Raw(Vec<u8>),
|
||||
}
|
||||
|
||||
impl AudioPacket {
|
||||
pub fn samples(&self) -> AudioPacketResult<&[f64]> {
|
||||
match self {
|
||||
AudioPacket::Samples(s) => Ok(s),
|
||||
AudioPacket::Raw(_) => Err(AudioPacketError::Raw),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn raw(&self) -> AudioPacketResult<&[u8]> {
|
||||
match self {
|
||||
AudioPacket::Raw(d) => Ok(d),
|
||||
AudioPacket::Samples(_) => Err(AudioPacketError::Samples),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
AudioPacket::Samples(s) => s.is_empty(),
|
||||
AudioPacket::Raw(d) => d.is_empty(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AudioPacketPosition {
|
||||
pub position_ms: u32,
|
||||
pub skipped: bool,
|
||||
}
|
||||
|
||||
impl Deref for AudioPacketPosition {
|
||||
type Target = u32;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.position_ms
|
||||
}
|
||||
}
|
||||
|
||||
pub trait AudioDecoder {
|
||||
fn seek(&mut self, position_ms: u32) -> Result<u32, DecoderError>;
|
||||
fn next_packet(
|
||||
&mut self,
|
||||
) -> DecoderResult<Option<(AudioPacketPosition, AudioPacket, u16, u32)>>;
|
||||
}
|
||||
|
||||
impl From<symphonia::core::errors::Error> for DecoderError {
|
||||
fn from(err: symphonia::core::errors::Error) -> Self {
|
||||
Self::SymphoniaDecoder(err.to_string())
|
||||
}
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
use std::io;
|
||||
|
||||
use log::warn;
|
||||
use symphonia::core::{
|
||||
audio::SampleBuffer,
|
||||
codecs::{Decoder, DecoderOptions, CODEC_TYPE_NULL},
|
||||
errors::Error,
|
||||
formats::{FormatOptions, FormatReader, SeekMode, SeekTo, Track},
|
||||
io::{MediaSource, MediaSourceStream},
|
||||
meta::{MetadataOptions, Visual},
|
||||
probe::{Hint, ProbeResult},
|
||||
units::{Time, TimeBase},
|
||||
};
|
||||
|
||||
use super::{AudioDecoder, AudioPacket, AudioPacketPosition, DecoderError, DecoderResult};
|
||||
|
||||
use crate::PAGES_PER_MS;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct PlayTrackOptions {
|
||||
track_id: u32,
|
||||
seek_ts: u64,
|
||||
}
|
||||
|
||||
fn first_supported_track(tracks: &[Track]) -> Option<&Track> {
|
||||
tracks
|
||||
.iter()
|
||||
.find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
|
||||
}
|
||||
|
||||
pub struct SymphoniaDecoder {
|
||||
format: Box<dyn FormatReader>,
|
||||
decoder: Box<dyn Decoder>,
|
||||
sample_buffer: Option<SampleBuffer<f64>>,
|
||||
}
|
||||
|
||||
impl SymphoniaDecoder {
|
||||
pub fn new<R>(input: R, hint: Hint) -> DecoderResult<Self>
|
||||
where
|
||||
R: MediaSource + 'static,
|
||||
{
|
||||
let mss = MediaSourceStream::new(Box::new(input), Default::default());
|
||||
|
||||
let format_opts = FormatOptions {
|
||||
enable_gapless: false,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let metadata_opts: MetadataOptions = Default::default();
|
||||
|
||||
let track: Option<usize> = None;
|
||||
|
||||
match symphonia::default::get_probe().format(&hint, mss, &format_opts, &metadata_opts) {
|
||||
Ok(probed) => {
|
||||
let decode_opts = DecoderOptions {
|
||||
verify: false,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let track = track
|
||||
.and_then(|t| probed.format.tracks().get(t))
|
||||
.or_else(|| first_supported_track(probed.format.tracks()));
|
||||
|
||||
let track_id = match track {
|
||||
Some(track) => track.id,
|
||||
_ => {
|
||||
return Err(DecoderError::SymphoniaDecoder(
|
||||
"No supported tracks found".to_string(),
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
let seek_ts = 0;
|
||||
|
||||
let track_info = PlayTrackOptions { track_id, seek_ts };
|
||||
|
||||
let track = match probed
|
||||
.format
|
||||
.tracks()
|
||||
.iter()
|
||||
.find(|track| track.id == track_info.track_id)
|
||||
{
|
||||
Some(track) => track,
|
||||
_ => {
|
||||
return Err(DecoderError::SymphoniaDecoder(
|
||||
"No supported tracks found".to_string(),
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
let decoder =
|
||||
symphonia::default::get_codecs().make(&track.codec_params, &decode_opts)?;
|
||||
return Ok(SymphoniaDecoder {
|
||||
format: probed.format,
|
||||
decoder,
|
||||
sample_buffer: None,
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(DecoderError::SymphoniaDecoder(format!(
|
||||
"format not supported. reason? {}",
|
||||
err
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ts_to_ms(&self, ts: u64) -> u32 {
|
||||
let time_base = self.decoder.codec_params().time_base;
|
||||
let seeked_to_ms = match time_base {
|
||||
Some(time_base) => {
|
||||
let time = time_base.calc_time(ts);
|
||||
(time.seconds as f64 + time.frac) * 1000.
|
||||
}
|
||||
|
||||
None => ts as f64 * PAGES_PER_MS,
|
||||
};
|
||||
seeked_to_ms as u32
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioDecoder for SymphoniaDecoder {
|
||||
fn seek(&mut self, position_ms: u32) -> Result<u32, DecoderError> {
|
||||
let seconds = position_ms as u64 / 1000;
|
||||
let frac = (position_ms as f64 % 1000.) / 1000.;
|
||||
let time = Time::new(seconds, frac);
|
||||
|
||||
let seeked_to_ts = self.format.seek(
|
||||
SeekMode::Accurate,
|
||||
SeekTo::Time {
|
||||
time,
|
||||
track_id: None,
|
||||
},
|
||||
)?;
|
||||
|
||||
self.decoder.reset();
|
||||
|
||||
Ok(self.ts_to_ms(seeked_to_ts.actual_ts))
|
||||
}
|
||||
|
||||
fn next_packet(
|
||||
&mut self,
|
||||
) -> DecoderResult<Option<(AudioPacketPosition, AudioPacket, u16, u32)>> {
|
||||
let mut skipped = false;
|
||||
|
||||
loop {
|
||||
let packet = match self.format.next_packet() {
|
||||
Ok(packet) => packet,
|
||||
Err(Error::IoError(err)) => {
|
||||
if err.kind() == io::ErrorKind::UnexpectedEof {
|
||||
return Ok(None);
|
||||
} else {
|
||||
return Err(DecoderError::SymphoniaDecoder(err.to_string()));
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(err.into());
|
||||
}
|
||||
};
|
||||
|
||||
let position_ms = self.ts_to_ms(packet.ts());
|
||||
let packet_position = AudioPacketPosition {
|
||||
position_ms,
|
||||
skipped,
|
||||
};
|
||||
|
||||
match self.decoder.decode(&packet) {
|
||||
Ok(decoded) => {
|
||||
let spec = *decoded.spec();
|
||||
let sample_buffer = match self.sample_buffer.as_mut() {
|
||||
Some(buffer) => buffer,
|
||||
None => {
|
||||
let duration = decoded.capacity() as u64;
|
||||
self.sample_buffer.insert(SampleBuffer::new(duration, spec))
|
||||
}
|
||||
};
|
||||
|
||||
sample_buffer.copy_interleaved_ref(decoded);
|
||||
let samples = AudioPacket::Samples(sample_buffer.samples().to_vec());
|
||||
|
||||
return Ok(Some((
|
||||
packet_position,
|
||||
samples,
|
||||
spec.channels.count() as u16,
|
||||
spec.rate,
|
||||
)));
|
||||
}
|
||||
Err(Error::DecodeError(_)) => {
|
||||
skipped = true;
|
||||
continue;
|
||||
}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -4,4 +4,5 @@
|
||||
#[macro_use]
|
||||
extern crate napi_derive;
|
||||
|
||||
mod probe;
|
||||
mod opus;
|
||||
mod probe;
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
use audiopus::coder::{Decoder, Encoder};
|
||||
use audiopus::{Application, Bitrate, Channels, SampleRate};
|
||||
use napi::bindgen_prelude::*;
|
||||
use napi::Error;
|
||||
use napi::Result;
|
||||
|
||||
const FRAME_SIZE: usize = 960;
|
||||
const MAX_FRAME_SIZE: usize = 6 * FRAME_SIZE;
|
||||
|
||||
#[napi]
|
||||
pub struct OpusEncoder {
|
||||
encoder: Option<Encoder>,
|
||||
decoder: Option<Decoder>,
|
||||
sample_rate: i32,
|
||||
channels: i32,
|
||||
out_buffer: Vec<u8>,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl OpusEncoder {
|
||||
#[napi(constructor)]
|
||||
pub fn new(sample_rate: i32, channels: i32) -> Result<Self> {
|
||||
if channels != 1 && channels != 2 {
|
||||
return Err(Error::new(Status::InvalidArg, "Invalid channels"));
|
||||
}
|
||||
|
||||
Ok(OpusEncoder {
|
||||
encoder: None,
|
||||
decoder: None,
|
||||
sample_rate,
|
||||
channels,
|
||||
out_buffer: vec![0u8; MAX_FRAME_SIZE],
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_encoder(&mut self) {
|
||||
if self.encoder.is_none() {
|
||||
let rate = self.resolve_sample_rate().unwrap();
|
||||
let channels = self.resolve_channels().unwrap();
|
||||
self.encoder = Some(Encoder::new(rate, channels, Application::Audio).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_decoder(&mut self) {
|
||||
if self.decoder.is_none() {
|
||||
let rate = self.resolve_sample_rate().unwrap();
|
||||
let channels = self.resolve_channels().unwrap();
|
||||
self.decoder = Some(Decoder::new(rate, channels).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_sample_rate(&self) -> std::result::Result<SampleRate, Error> {
|
||||
match self.sample_rate {
|
||||
8000 => Ok(SampleRate::Hz8000),
|
||||
12000 => Ok(SampleRate::Hz12000),
|
||||
16000 => Ok(SampleRate::Hz16000),
|
||||
24000 => Ok(SampleRate::Hz24000),
|
||||
48000 => Ok(SampleRate::Hz48000),
|
||||
_ => return Err(Error::new(Status::InvalidArg, "Invalid sample rate")),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_channels(&self) -> std::result::Result<Channels, Error> {
|
||||
match self.channels {
|
||||
1 => Ok(Channels::Mono),
|
||||
2 => Ok(Channels::Stereo),
|
||||
_ => return Err(Error::new(Status::InvalidArg, "Invalid channels")),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub fn encode(&mut self, data: Buffer) -> Result<Buffer> {
|
||||
self.ensure_encoder();
|
||||
|
||||
let encoder = self.encoder.as_mut().unwrap();
|
||||
let data_ref: &[u8] = &data;
|
||||
|
||||
let data_i16 = unsafe {
|
||||
let ptr = data_ref.as_ptr() as *const i16;
|
||||
let len = data_ref.len() / 2;
|
||||
std::slice::from_raw_parts(ptr, len)
|
||||
};
|
||||
|
||||
let len = encoder
|
||||
.encode(data_i16, &mut self.out_buffer)
|
||||
.map_err(|e| Error::new(Status::GenericFailure, format!("Failed to encode: {}", e)))?;
|
||||
|
||||
Ok(self.out_buffer[..len].to_vec().into())
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub fn decode(&mut self, data: Buffer) -> Result<Buffer> {
|
||||
self.ensure_decoder();
|
||||
|
||||
let decoder = self.decoder.as_mut().unwrap();
|
||||
let data_ref: &[u8] = &data;
|
||||
|
||||
let mut out = vec![0i16; MAX_FRAME_SIZE * self.channels as usize];
|
||||
|
||||
let len = decoder
|
||||
.decode(Some(data_ref), &mut out, false)
|
||||
.map_err(|e| Error::new(Status::GenericFailure, format!("Failed to decode: {}", e)))?;
|
||||
|
||||
if len == 0 {
|
||||
return Err(Error::new(Status::GenericFailure, "Failed to decode"));
|
||||
}
|
||||
|
||||
let decoded_length = len * 2 * self.channels as usize;
|
||||
|
||||
let out = unsafe {
|
||||
let ptr = out.as_ptr() as *const u8;
|
||||
std::slice::from_raw_parts(ptr, decoded_length)
|
||||
};
|
||||
|
||||
Ok(out.to_vec().into())
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub fn set_bitrate(&mut self, bitrate: i32) -> Result<()> {
|
||||
self.ensure_encoder();
|
||||
|
||||
let encoder = self.encoder.as_mut().unwrap();
|
||||
|
||||
encoder
|
||||
.set_bitrate(Bitrate::BitsPerSecond(bitrate))
|
||||
.map_err(|e| {
|
||||
Error::new(
|
||||
Status::GenericFailure,
|
||||
format!("Failed to set bitrate: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub fn get_bitrate(&mut self) -> Result<i32> {
|
||||
self.ensure_encoder();
|
||||
|
||||
let encoder = self.encoder.as_mut().unwrap();
|
||||
|
||||
let bitrate = encoder.bitrate().map_err(|e| {
|
||||
Error::new(
|
||||
Status::GenericFailure,
|
||||
format!("Failed to get bitrate: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
match bitrate {
|
||||
Bitrate::BitsPerSecond(bitrate) => Ok(bitrate),
|
||||
_ => Err(Error::new(
|
||||
Status::GenericFailure,
|
||||
"Failed to get bitrate: Invalid bitrate",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub fn apply_encoder_ctl(&mut self, request: i32, value: i32) -> Result<()> {
|
||||
self.ensure_encoder();
|
||||
|
||||
let encoder = self.encoder.as_mut().unwrap();
|
||||
|
||||
encoder
|
||||
.set_encoder_ctl_request(request, value)
|
||||
.map_err(|e| {
|
||||
Error::new(
|
||||
Status::GenericFailure,
|
||||
format!("Failed to apply encoder ctl: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn apply_decoder_ctl(&mut self, _request: i32, _value: i32) -> Result<()> {
|
||||
// Currently, this function is not implemented due to being private in the library.
|
||||
// It will be implemented if it becomes available in the future. This currently exists
|
||||
// for compatibility reasons.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn destroy(&mut self) {
|
||||
self.encoder = None;
|
||||
self.decoder = None;
|
||||
}
|
||||
}
|
||||
+17
-9
@@ -139,12 +139,17 @@ pub fn probe(data: Buffer) -> Result<JsProbeResult> {
|
||||
|
||||
let mut probed = symphonia::default::get_probe()
|
||||
.format(&hint, mss, &fmt_opts, &meta_opts)
|
||||
.expect("unsupported format");
|
||||
.map_err(|e| {
|
||||
Error::new(
|
||||
Status::GenericFailure,
|
||||
format!("failed to probe media: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut format = probed.format;
|
||||
|
||||
|
||||
let metadata: Vec<MetadataField>;
|
||||
|
||||
|
||||
if let Some(metadata_rev) = format.metadata().current() {
|
||||
metadata = parse_metadata(&metadata_rev);
|
||||
} else if let Some(metadata_rev) = probed.metadata.get().as_ref().and_then(|m| m.current()) {
|
||||
@@ -157,7 +162,7 @@ pub fn probe(data: Buffer) -> Result<JsProbeResult> {
|
||||
.tracks()
|
||||
.iter()
|
||||
.find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
|
||||
.expect("no supported audio tracks");
|
||||
.ok_or(Error::new(Status::GenericFailure, "no audio tracks found"))?;
|
||||
|
||||
let codec_params = &track.codec_params;
|
||||
|
||||
@@ -249,9 +254,12 @@ pub fn probe(data: Buffer) -> Result<JsProbeResult> {
|
||||
}
|
||||
|
||||
fn parse_metadata(rev: &MetadataRevision) -> Vec<MetadataField> {
|
||||
let tags = rev.tags();
|
||||
tags.iter().map(|tag| MetadataField {
|
||||
name: tag.key.to_string(),
|
||||
value: tag.value.to_string(),
|
||||
}).collect()
|
||||
let tags = rev.tags();
|
||||
tags
|
||||
.iter()
|
||||
.map(|tag| MetadataField {
|
||||
name: tag.key.to_string(),
|
||||
value: tag.value.to_string(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
Reference in new issue
Block a user