37 Commits

Author SHA1 Message Date
5aedb0d14a chore: bump version (v1.3.2) 2026-02-15 00:18:59 +01:00
4b9cc3acd3 chore: update to 2024 rust edition 2026-02-15 00:16:19 +01:00
d746fbb152 chore: update deps 2026-02-14 23:49:53 +01:00
6f762742bd chore: bump version (v1.3.1) 2024-07-25 22:44:40 +02:00
1c8ff6d2e9 docs: fix required gstreamer version in readme 2024-07-25 22:42:07 +02:00
ec9188fbaf chore: use new edition 2024-07-25 22:41:27 +02:00
5c11600c64 chore: remove nix files due to lack of maintenance 2024-07-25 22:31:46 +02:00
05ad75e20d chore: update deps 2024-07-25 22:27:33 +02:00
a10345fbbe build: bump version (v1.3.0) 2022-04-07 21:12:25 +02:00
f3423eea53 fix: fix "from", "to" & "config" cli argument processing 2022-04-07 21:10:37 +02:00
80e3d02cb4 refactor: simplify config processing 2022-04-07 20:58:05 +02:00
b7a7abbf61 refactor: fmt 2022-04-07 19:36:49 +02:00
5abadc3131 build: update deps 2022-04-07 19:35:37 +02:00
9c86cdcc62 build: update deps 2022-02-24 21:45:52 +01:00
605fa5c15b build: update deps 2022-02-04 23:29:19 +01:00
9c1d39ba5f fix: allow multiple values for tag "musicbrainz-artistid" & "musicbrainz-albumartistid"
issue #2
2021-12-14 19:08:05 +01:00
c6c9da2f27 build: update deps 2021-12-14 18:49:01 +01:00
6872e7897b build: bump version (v1.2.2) 2021-08-25 17:11:23 +02:00
2d1497cb36 build: update deps 2021-08-25 17:09:33 +02:00
f1fb3506b5 build: update deps 2021-07-25 14:37:08 +02:00
f4050fe645 refactor: switch from space to tab indentation 2021-07-10 10:07:30 +02:00
b533f059d7 build: bump version (v1.2.1) 2021-07-05 20:02:49 +02:00
00a25e168d refactor: use more readable clamp method 2021-07-05 19:53:49 +02:00
b51c9939c1 build: upgrade deps 2021-07-05 19:46:06 +02:00
c22d45818e build: update deps 2021-06-18 11:46:48 +02:00
18cc852e6b build: update deps 2021-05-27 22:52:48 +02:00
65b4f398d9 build: bump version (v1.2.0) 2021-04-22 21:20:51 +02:00
7f40cb0581 build: update nix deps 2021-04-22 21:20:51 +02:00
bc15a4449d build: update cargo deps 2021-04-22 21:20:51 +02:00
1cf7cec8bd feat: add "jobs" cli argument 2021-04-22 21:20:51 +02:00
5cf98b3c17 feat: improve error messages 2021-04-21 00:57:23 +02:00
54e174eb0a build: include "README.md" & "CHANGELOG.md" to crate package 2021-04-21 00:26:28 +02:00
803860cce5 doc: add changelog 2021-04-21 00:26:21 +02:00
f2bfddd76e refactor: move actual transcoding into own fn 2021-04-17 01:53:25 +02:00
d073ef10b5 feat: add "copy" codec 2021-04-17 01:14:34 +02:00
399c4b8a2c build: update cargo deps 2021-04-17 00:21:47 +02:00
3188d074b7 build: update nix deps 2021-04-17 00:20:44 +02:00
13 changed files with 1695 additions and 1437 deletions

View File

@@ -1,7 +1,7 @@
root = true
[*]
indent_style = space
indent_style = tab
indent_size = 4
charset = utf-8
trim_trailing_whitespace = true

1
.rustfmt.toml Normal file
View File

@@ -0,0 +1 @@
hard_tabs = true

32
CHANGELOG.md Normal file
View File

@@ -0,0 +1,32 @@
# Changelog
## v1.3.2
* dependencies upgraded
## v1.3.1
* dependencies upgraded
## v1.3.0
* allow multiple values for the tags "musicbrainz-artistid" and "musicbrainz-albumartistid"
* fix "from", "to" & "config" cli argument processing
## v1.2.2
* dependencies upgraded
## v1.2.1
* dependencies upgraded
## v1.2.0
* "copy" encoding format added
* "jobs" cli argument added, that lets you set the number of concurrent transcodes
## v1.1.0
* "flac" encoding format added
* resampling quality set to highest/"10"

998
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
[package]
name = "audio-conv"
version = "1.1.0"
edition = "2018"
version = "1.3.2"
edition = "2024"
description = "Copies directory structure and converts audio files in it"
authors = ["Thomas Heck <t@b128.net>"]
repository = "https://gitlab.com/chpio/audio-conv"
@@ -16,25 +16,27 @@ keywords = ["audio", "conversion", "opus", "flac"]
include = [
"/src/**/*",
"/example.audio-conv.yaml",
"/README.md",
"/CHANGELOG.md",
]
[dependencies]
gstreamer-audio = { version = "0.16", features = ["v1_10"] }
gstreamer = { version = "0.16", features = ["v1_10"] }
gstreamer-base = { version = "0.16", features = ["v1_10"] }
glib = "0.10"
gstreamer = { version = "0.24", features = ["v1_16"] }
gstreamer-base = { version = "0.24", features = ["v1_16"] }
gstreamer-audio = { version = "0.24", features = ["v1_16"] }
glib = "0.21"
futures = "0.3"
num_cpus = "1"
walkdir = "2"
libc = "0.2"
anyhow = "1"
clap = "2"
clap = { version = "4", features = ["cargo"] }
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.8"
serde_yaml = "0.9"
regex = "1"
globset = "0.4"
derive_more = "0.99"
tui = { version = "0.14", default-features = false, features = ["crossterm"] }
derive_more = { version = "2", features = ["full"] }
tui = { version = "0.19", default-features = false, features = ["crossterm"] }
[dependencies.tokio]
version = "1"

View File

@@ -5,7 +5,7 @@ second path. The directory structure from the first path gets also copied to the
## Dependencies
Requires *gstreamer* version 1.10 or higher with the *base* plugin.
Requires *gstreamer* version 1.16 or higher with the *base* plugin.
The supported source audio formats (or even other media that is able to contain audio) depend on
the installed *gstreamer* plugins.

View File

@@ -13,6 +13,10 @@ matches:
bitrate: 160
bitrate_type: vbr # or cbr
# for copy (copies file without transcoding it):
# to:
# codec: copy
# for mp3:
# to:
# codec: mp3

58
flake.lock generated
View File

@@ -1,58 +0,0 @@
{
"nodes": {
"flake-utils": {
"locked": {
"lastModified": 1610051610,
"narHash": "sha256-U9rPz/usA1/Aohhk7Cmc2gBrEEKRzcW4nwPWMPwja4Y=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "3982c9903e93927c2164caa727cd3f6a0e6d14cc",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"import-cargo": {
"locked": {
"lastModified": 1594305518,
"narHash": "sha256-frtArgN42rSaEcEOYWg8sVPMUK+Zgch3c+wejcpX3DY=",
"owner": "edolstra",
"repo": "import-cargo",
"rev": "25d40be4a73d40a2572e0cc233b83253554f06c5",
"type": "github"
},
"original": {
"owner": "edolstra",
"repo": "import-cargo",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1612988144,
"narHash": "sha256-X1IO9gtzE0dRVpDqknjF39IVDnuKuZsRis38WnLfHLo=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "26f6af373ec1b867d751b56fb802f14010c8351b",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"import-cargo": "import-cargo",
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

View File

@@ -1,63 +0,0 @@
{
description = "Converts audio files";
inputs = {
nixpkgs.url = github:NixOS/nixpkgs;
flake-utils.url = "github:numtide/flake-utils";
import-cargo.url = github:edolstra/import-cargo;
};
outputs = { self, flake-utils, nixpkgs, import-cargo }:
flake-utils.lib.eachDefaultSystem (system:
let
pkgs = import nixpkgs { inherit system; };
buildtimeDeps = with pkgs; [
cargo
rustc
pkg-config
];
runtimeDeps = with pkgs; [
gst_all_1.gstreamer
# needed for opus, resample, ...
gst_all_1.gst-plugins-base
# needed for flac
gst_all_1.gst-plugins-good
];
inherit (import-cargo.builders) importCargo;
in {
defaultPackage = pkgs.stdenv.mkDerivation {
name = "audio-conv";
src = self;
nativeBuildInputs = [
# setupHook which makes sure that a CARGO_HOME with vendored dependencies
# exists
(importCargo { lockFile = ./Cargo.lock; inherit pkgs; }).cargoHome
]
++ buildtimeDeps;
buildInputs = runtimeDeps;
buildPhase = ''
cargo build --release --offline
'';
installPhase = ''
install -Dm775 ./target/release/audio-conv $out/bin/audio-conv
'';
};
devShell = pkgs.stdenv.mkDerivation {
name = "audio-conv";
buildInputs = [ pkgs.rustfmt pkgs.rust-analyzer ]
++ buildtimeDeps
++ runtimeDeps;
};
}
);
}

View File

@@ -1,4 +1,5 @@
use anyhow::{Context, Error, Result};
use clap::{ArgAction, builder::ValueParser};
use globset::GlobBuilder;
use regex::bytes::{Regex, RegexBuilder};
use serde::Deserialize;
@@ -12,6 +13,7 @@ pub struct Config {
pub from: PathBuf,
pub to: PathBuf,
pub matches: Vec<TranscodeMatch>,
pub jobs: Option<usize>,
}
#[derive(Debug)]
@@ -46,6 +48,9 @@ pub enum Transcode {
#[serde(default = "bitrate_type_vbr")]
bitrate_type: BitrateType,
},
#[serde(rename = "copy")]
Copy,
}
impl Transcode {
@@ -54,6 +59,7 @@ impl Transcode {
Transcode::Opus { .. } => "opus",
Transcode::Flac { .. } => "flac",
Transcode::Mp3 { .. } => "mp3",
Transcode::Copy => "",
}
}
}
@@ -98,6 +104,8 @@ struct ConfigFile {
#[serde(default)]
matches: Vec<TranscodeMatchFile>,
jobs: Option<usize>,
}
#[derive(Debug, Deserialize)]
@@ -112,42 +120,54 @@ struct TranscodeMatchFile {
}
pub fn config() -> Result<Config> {
use clap::{App, Arg, SubCommand};
use clap::{Arg, Command};
let arg_matches = App::new("audio-conv")
let arg_matches = Command::new("audio-conv")
.version(clap::crate_version!())
.about("Converts audio files")
.arg(
Arg::with_name("config")
.short("c")
Arg::new("config")
.short('c')
.long("config")
.required(false)
.takes_value(true)
.help("path to an audio-conv config file, defaults to \"audio-conv.yaml\""),
.value_parser(ValueParser::path_buf())
.action(ArgAction::Set)
.help("Path to an audio-conv config file, defaults to \"audio-conv.yaml\""),
)
.arg(
Arg::with_name("from")
.short("f")
Arg::new("from")
.short('f')
.long("from")
.required(false)
.takes_value(true)
.help("from directory path"),
.value_parser(ValueParser::path_buf())
.action(ArgAction::Set)
.help("\"from\" directory path"),
)
.arg(
Arg::with_name("to")
.short("t")
Arg::new("to")
.short('t')
.long("to")
.required(false)
.takes_value(true)
.help("to directory path"),
.value_parser(ValueParser::path_buf())
.action(ArgAction::Set)
.help("\"to\" directory path"),
)
.subcommand(SubCommand::with_name("init").about("writes an example config"))
.arg(
Arg::new("jobs")
.short('j')
.long("jobs")
.required(false)
.value_parser(clap::value_parser!(usize))
.action(ArgAction::Set)
.help("Allow N jobs/transcodes at once. Defaults to number of logical cores"),
)
.subcommand(Command::new("init").about("writes an example config"))
.get_matches();
let current_dir = std::env::current_dir().context("could not get current directory")?;
let current_dir = std::env::current_dir().context("Could not get current directory")?;
let config_path = arg_matches.value_of_os("config");
let force_load = config_path.is_some();
let config_path = arg_matches.get_one::<PathBuf>("config");
let enforce_config_load = config_path.is_some();
let config_path = config_path
.map(AsRef::<Path>::as_ref)
.unwrap_or_else(|| AsRef::<Path>::as_ref("audio-conv.yaml"));
@@ -159,19 +179,19 @@ pub fn config() -> Result<Config> {
.create_new(true)
.open(&config_path)
.and_then(|mut f| f.write_all(std::include_bytes!("../example.audio-conv.yaml")))
.with_context(|| format!("unable to write config file to {}", config_path.display()))?;
.with_context(|| format!("Unable to write config file to {}", config_path.display()))?;
std::process::exit(0);
}
let config_dir = config_path
.parent()
.context("could not get parent directory of the config file")?;
.context("Could not get parent directory of the config file")?;
let config_file = load_config_file(&config_path)
.with_context(|| format!("failed loading config file \"{}\"", config_path.display()))?;
.with_context(|| format!("Failed loading config file {}", config_path.display()))?;
if force_load && config_file.is_none() {
if enforce_config_load && config_file.is_none() {
return Err(Error::msg(format!(
"could not find config file \"{}\"",
config_path.display()
@@ -181,7 +201,7 @@ pub fn config() -> Result<Config> {
let default_regex = RegexBuilder::new("\\.(flac|wav)$")
.case_insensitive(true)
.build()
.expect("failed compiling default match regex");
.expect("Failed compiling default match regex");
let transcode_matches = config_file
.as_ref()
@@ -194,8 +214,8 @@ pub fn config() -> Result<Config> {
let glob = GlobBuilder::new(glob)
.case_insensitive(true)
.build()
.context("failed building glob")?;
let regex = Regex::new(glob.regex()).context("failed compiling regex")?;
.context("Failed building glob")?;
let regex = Regex::new(glob.regex()).context("Failed compiling regex")?;
Ok(regex)
});
@@ -203,7 +223,7 @@ pub fn config() -> Result<Config> {
let regex = RegexBuilder::new(regex)
.case_insensitive(true)
.build()
.context("failed compiling regex")?;
.context("Failed compiling regex")?;
Ok(regex)
});
@@ -215,7 +235,7 @@ pub fn config() -> Result<Config> {
let regex = RegexBuilder::new(&ext)
.case_insensitive(true)
.build()
.context("failed compiling regex")?;
.context("Failed compiling regex")?;
Ok(regex)
});
@@ -247,7 +267,7 @@ pub fn config() -> Result<Config> {
Ok(Config {
from: {
arg_matches
.value_of_os("from")
.get_one::<PathBuf>("from")
.map(|p| current_dir.join(p))
.or_else(|| {
config_file
@@ -258,10 +278,10 @@ pub fn config() -> Result<Config> {
})
.ok_or_else(|| Error::msg("\"from\" not configured"))?
.canonicalize()
.context("could not canonicalize \"from\" path")?
.context("Could not canonicalize \"from\" path")?
},
to: arg_matches
.value_of_os("to")
.get_one::<PathBuf>("to")
.map(|p| current_dir.join(p))
.or_else(|| {
config_file
@@ -272,8 +292,21 @@ pub fn config() -> Result<Config> {
})
.ok_or_else(|| Error::msg("\"to\" not configured"))?
.canonicalize()
.context("could not canonicalize \"to\" path")?,
.context("Could not canonicalize \"to\" path")?,
matches: transcode_matches,
jobs: arg_matches
.get_one("jobs")
.copied()
.or_else(|| config_file.as_ref().map(|c| c.jobs).flatten()),
// .map(|jobs_str| {
// jobs_str.parse().with_context(|| {
// format!(
// "Could not parse \"jobs\" argument \"{}\" to a number",
// &jobs_str
// )
// })
// })
// .transpose()?,
})
}
@@ -284,6 +317,6 @@ fn load_config_file(path: &Path) -> Result<Option<ConfigFile>> {
Err(err) => return Err(Error::new(err)),
};
let config: ConfigFile =
serde_yaml::from_reader(&mut file).context("could not parse config file")?;
serde_yaml::from_reader(&mut file).context("Could not parse config file")?;
Ok(Some(config))
}

View File

@@ -1,16 +1,17 @@
mod config;
mod tag;
mod ui;
use crate::config::Config;
use crate::config::{Config, Transcode};
use anyhow::{Context, Error, Result};
use futures::{pin_mut, prelude::*};
use glib::{subclass::prelude::*, GBoxed, GString};
use gstreamer::{gst_element_error, prelude::*, Element};
use glib::Boxed;
use gstreamer::{Element, element_error, prelude::*};
use gstreamer_base::prelude::*;
use std::{
borrow::Cow,
error::Error as StdError,
ffi, fmt,
fmt,
fmt::Write as FmtWrite,
path::{Path, PathBuf},
result::Result as StdResult,
@@ -19,8 +20,8 @@ use std::{
};
use tokio::{fs, io::AsyncWriteExt, task, time::interval};
#[derive(Clone, Debug, GBoxed)]
#[gboxed(type_name = "GBoxErrorWrapper")]
#[derive(Clone, Debug, Boxed)]
#[boxed_type(name = "GBoxErrorWrapper")]
struct GBoxErrorWrapper(Arc<Error>);
impl GBoxErrorWrapper {
@@ -42,7 +43,7 @@ impl fmt::Display for GBoxErrorWrapper {
}
#[derive(Debug, derive_more::Display, derive_more::Error)]
#[display(fmt = "Received error from {}: {} (debug: {:?})", src, error, debug)]
#[display("Received error from {}: {} (debug: {:?})", src, error, debug)]
struct GErrorMessage {
src: String,
error: String,
@@ -50,14 +51,21 @@ struct GErrorMessage {
source: glib::Error,
}
fn gmake<T: IsA<Element>>(factory_name: &str) -> Result<T> {
let res = gstreamer::ElementFactory::make(factory_name, None)
.with_context(|| format!("could not make gstreamer Element \"{}\"", factory_name))?
fn gmake<T: IsA<Element>>(factory_name: &str, properties: &[(&str, &dyn ToValue)]) -> Result<T> {
let builder = gstreamer::ElementFactory::make(factory_name);
let builder = properties
.into_iter()
.fold(builder, |builder, (name, value)| {
builder.property(name, value.to_value())
});
let res = builder
.build()
.with_context(|| format!("Could not make gstreamer Element \"{}\"", factory_name))?
.downcast()
.ok()
.with_context(|| {
format!(
"could not cast gstreamer Element \"{}\" into `{}`",
"Could not cast gstreamer Element \"{}\" into `{}`",
factory_name,
std::any::type_name::<T>()
)
@@ -68,7 +76,7 @@ fn gmake<T: IsA<Element>>(factory_name: &str) -> Result<T> {
#[derive(Debug, Clone)]
pub struct ConversionArgs {
rel_from_path: PathBuf,
transcode: config::Transcode,
transcode: Transcode,
}
fn get_conversion_args(config: &Config) -> impl Iterator<Item = Result<ConversionArgs>> + '_ {
@@ -97,7 +105,7 @@ fn get_conversion_args(config: &Config) -> impl Iterator<Item = Result<Conversio
let rel_path = e.path().strip_prefix(&config.from).with_context(|| {
format!(
"unable to get relative path for {} from {}",
"Unable to get relative path for {} from {}",
e.path().display(),
config.from.display()
)
@@ -112,7 +120,10 @@ fn get_conversion_args(config: &Config) -> impl Iterator<Item = Result<Conversio
.map_err(Error::new)
.and_then(|md| md.modified().map_err(Error::new))
.with_context(|| {
format!("unable to get mtime for from file {}", e.path().display())
format!(
"Unable to get mtime for \"from\" file {}",
e.path().display()
)
})?;
let to_mtime = to.metadata().and_then(|md| md.modified());
match to_mtime {
@@ -120,8 +131,8 @@ fn get_conversion_args(config: &Config) -> impl Iterator<Item = Result<Conversio
Err(err) if err.kind() == std::io::ErrorKind::NotFound => true,
Err(err) => {
return Err(err).with_context(|| {
format!("unable to get mtime for to file {}", to.display())
})
format!("Unable to get mtime for \"to\" file {}", to.display())
});
}
}
};
@@ -147,15 +158,15 @@ async fn main() -> Result<()> {
let main_handle = async move {
let ok = task::spawn_local(main_loop(ui_queue))
.await
.context("main task failed")??;
.context("Main task failed")??;
Result::<_>::Ok(ok)
};
let ui_handle = async move {
let ok = task::spawn_local(ui_fut)
.await
.context("ui task failed")?
.context("ui failed")?;
.context("Ui task failed")?
.context("Ui failed")?;
Result::<_>::Ok(ok)
};
@@ -168,20 +179,23 @@ async fn main() -> Result<()> {
async fn main_loop(ui_queue: ui::MsgQueue) -> Result<()> {
let (config, conv_args) = task::spawn_blocking(|| -> Result<_> {
gstreamer::init()?;
let config = config::config().context("could not get the config")?;
gstreamer::tags::register::<tag::MbArtistId>();
gstreamer::tags::register::<tag::MbAlbumArtistId>();
let config = config::config().context("Could not get the config")?;
let conv_args = get_conversion_args(&config)
.collect::<Result<Vec<_>>>()
.context("failed loading dir structure")?;
.context("Failed loading dir structure")?;
Ok((config, conv_args))
})
.await
.context("init task failed")??;
.context("Init task failed")??;
let log_path = Path::new(".")
.canonicalize()
.context("unable to canonicalize path to log file")?
.context("Unable to canonicalize path to log file")?
.join("audio-conv.log");
ui_queue.push(ui::Msg::Init {
@@ -189,9 +203,11 @@ async fn main_loop(ui_queue: ui::MsgQueue) -> Result<()> {
log_path: log_path.clone(),
});
let concurrent_jobs = config.jobs.unwrap_or_else(|| num_cpus::get());
stream::iter(conv_args.into_iter().enumerate())
.map(Ok)
.try_for_each_concurrent(num_cpus::get(), |(i, args)| {
.try_for_each_concurrent(concurrent_jobs, |(i, args)| {
let config = &config;
let ui_queue = &ui_queue;
let log_path = &log_path;
@@ -206,7 +222,7 @@ async fn main_loop(ui_queue: ui::MsgQueue) -> Result<()> {
Ok(()) => ui_queue.push(ui::Msg::TaskEnd { id: i }),
Err(err) => {
let err = err.context(format!(
"failed transcoding \"{}\"",
"Transcoding failed for {}",
args.rel_from_path.display()
));
@@ -264,20 +280,68 @@ async fn transcode(
) -> Result<()> {
let from_path = config.from.join(&args.rel_from_path);
let mut to_path = config.to.join(&args.rel_from_path);
to_path.set_extension(args.transcode.extension());
let file_src: Element = gmake("filesrc")?;
file_src.set_property("location", &path_to_gstring(&from_path))?;
fs::create_dir_all(
to_path
.parent()
.with_context(|| format!("Could not get parent dir for {}", to_path.display()))?,
)
.await?;
// encode into a tmp file first, then rename to actuall file name, that way we're writing
// "whole" files to the intended file path, ignoring partial files in the mtime check
let to_path_tmp = to_path.with_extension("tmp");
let decodebin: Element = gmake("decodebin")?;
rm_file_on_err(&to_path_tmp, async {
match args.transcode {
Transcode::Copy => {
fs::copy(&from_path, &to_path_tmp).await.with_context(|| {
format!(
"Could not copy file from {} to {}",
from_path.display(),
to_path_tmp.display()
)
})?;
}
_ => {
to_path.set_extension(args.transcode.extension());
transcode_gstreamer(
&from_path,
&to_path_tmp,
args.transcode.clone(),
task_id,
queue,
)
.await?
}
}
fs::rename(&to_path_tmp, &to_path).await.with_context(|| {
format!(
"Could not rename temporary file {} to {}",
to_path_tmp.display(),
to_path.display()
)
})
})
.await
}
async fn transcode_gstreamer(
from_path: &Path,
to_path: &Path,
transcode: Transcode,
task_id: usize,
queue: &ui::MsgQueue,
) -> Result<()> {
let file_src: Element = gmake("filesrc", &[("location", &from_path)])?;
let decodebin: Element = gmake("decodebin", &[])?;
let src_elems: &[&Element] = &[&file_src, &decodebin];
let pipeline = gstreamer::Pipeline::new(None);
let pipeline = gstreamer::Pipeline::new();
pipeline.add_many(src_elems)?;
Element::link_many(src_elems)?;
@@ -285,10 +349,7 @@ async fn transcode(
// downgrade pipeline RC to a weak RC to break the reference cycle
let pipeline_weak = pipeline.downgrade();
let transcode_args = args.transcode.clone();
let to_path_tmp_clone = to_path_tmp.clone();
let to_path_clone = to_path.to_owned();
decodebin.connect_pad_added(move |decodebin, src_pad| {
let insert_sink = || -> Result<()> {
let pipeline = match pipeline_weak.upgrade() {
@@ -299,9 +360,9 @@ async fn transcode(
}
};
let is_audio = src_pad.get_current_caps().and_then(|caps| {
caps.get_structure(0).map(|s| {
let name = s.get_name();
let is_audio = src_pad.current_caps().and_then(|caps| {
caps.structure(0).map(|s| {
let name = s.name();
name.starts_with("audio/")
})
});
@@ -309,7 +370,7 @@ async fn transcode(
None => {
return Err(Error::msg(format!(
"Failed to get media type from pad {}",
src_pad.get_name()
src_pad.name()
)));
}
Some(false) => {
@@ -319,69 +380,86 @@ async fn transcode(
Some(true) => {}
}
let resample: Element = gmake("audioresample")?;
let resample: Element = gmake(
"audioresample",
&[
// quality from 0 to 10
resample.set_property("quality", &10)?;
("quality", &10i32),
],
)?;
let mut dest_elems = vec![
resample,
// `audioconvert` converts audio format, bitdepth, ...
gmake("audioconvert")?,
gmake("audioconvert", &[])?,
];
match &transcode_args {
config::Transcode::Opus {
match &transcode {
Transcode::Opus {
bitrate,
bitrate_type,
} => {
let encoder: Element = gmake("opusenc")?;
encoder.set_property(
let encoder: Element = gmake(
"opusenc",
&[
(
"bitrate",
&i32::from(*bitrate)
.checked_mul(1_000)
.context("bitrate overflowed")?,
)?;
encoder.set_property_from_str(
.context("Bitrate overflowed")?,
),
(
"bitrate-type",
match bitrate_type {
config::BitrateType::Vbr => "1",
config::BitrateType::Cbr => "0",
config::BitrateType::Vbr => &"1",
config::BitrateType::Cbr => &"0",
},
);
),
],
)?;
dest_elems.push(encoder);
dest_elems.push(gmake("oggmux")?);
dest_elems.push(gmake("oggmux", &[])?);
}
config::Transcode::Flac { compression } => {
let encoder: Element = gmake("flacenc")?;
encoder.set_property_from_str("quality", &compression.to_string());
Transcode::Flac { compression } => {
let encoder: Element =
gmake("flacenc", &[("quality", &compression.to_string())])?;
dest_elems.push(encoder);
}
config::Transcode::Mp3 {
Transcode::Mp3 {
bitrate,
bitrate_type,
} => {
let encoder: Element = gmake("lamemp3enc")?;
let encoder: Element = gmake(
"lamemp3enc",
&[
// target: "1" = "bitrate"
encoder.set_property_from_str("target", "1");
encoder.set_property("bitrate", &i32::from(*bitrate))?;
encoder.set_property(
("target", &"1"),
("bitrate", &i32::from(*bitrate)),
(
"cbr",
match bitrate_type {
config::BitrateType::Vbr => &false,
config::BitrateType::Cbr => &true,
},
),
],
)?;
dest_elems.push(encoder);
dest_elems.push(gmake("id3v2mux")?);
dest_elems.push(gmake("id3v2mux", &[])?);
}
Transcode::Copy => {
// already handled outside this fn
unreachable!();
}
};
let file_dest: gstreamer_base::BaseSink = gmake("filesink")?;
file_dest.set_property("location", &path_to_gstring(&to_path_tmp_clone))?;
let file_dest: gstreamer_base::BaseSink =
gmake("filesink", &[("location", &to_path_clone)])?;
file_dest.set_sync(false);
dest_elems.push(file_dest.upcast());
@@ -396,7 +474,7 @@ async fn transcode(
let sink_pad = dest_elems
.get(0)
.unwrap()
.get_static_pad("sink")
.static_pad("sink")
.expect("1. dest element has no sinkpad");
src_pad.link(&sink_pad)?;
@@ -408,7 +486,7 @@ async fn transcode(
.field("error", &GBoxErrorWrapper::new(err))
.build();
gst_element_error!(
element_error!(
decodebin,
gstreamer::LibraryError::Failed,
("Failed to insert sink"),
@@ -417,16 +495,8 @@ async fn transcode(
}
});
let bus = pipeline.get_bus().context("pipe get bus")?;
let bus = pipeline.bus().context("Could not get bus for pipeline")?;
fs::create_dir_all(
to_path
.parent()
.with_context(|| format!("could not get parent dir for {}", to_path.display()))?,
)
.await?;
rm_file_on_err(&to_path_tmp, async {
pipeline
.set_state(gstreamer::State::Playing)
.context("Unable to set the pipeline to the `Playing` state")?;
@@ -446,37 +516,43 @@ async fn transcode(
Ok(false)
}
MessageView::Error(err) => {
pipeline.set_state(gstreamer::State::Null).context(
"Unable to set the pipeline to the `Null` state, after error",
)?;
let pipe_stop_res = pipeline.set_state(gstreamer::State::Null);
let err = err
.get_details()
let err: Error = err
.details()
.and_then(|details| {
if details.get_name() != "error-details" {
if details.name() != "error-details" {
return None;
}
let err = details
.get::<&GBoxErrorWrapper>("error")
.unwrap()
.map(|err| err.clone().into())
.expect("error-details message without actual error");
.clone()
.into();
Some(err)
})
.unwrap_or_else(|| {
GErrorMessage {
src: msg
.get_src()
.map(|s| String::from(s.get_path_string()))
.src()
.map(|s| String::from(s.path_string()))
.unwrap_or_else(|| String::from("None")),
error: err.get_error().to_string(),
debug: err.get_debug(),
source: err.get_error(),
error: err.error().to_string(),
debug: err.debug().map(|gstring| gstring.into()),
source: err.error(),
}
.into()
});
if let Err(pipe_err) = pipe_stop_res {
let err = err.context(pipe_err).context(
"Unable to set the pipeline to the `Null` state, after error",
);
Err(err)
} else {
Err(err)
}
}
_ => Ok(true),
}
@@ -489,8 +565,7 @@ async fn transcode(
}
})
.try_for_each(|_| futures::future::ready(Ok(())))
.await
.context("failed converting")?;
.await?;
Result::<_>::Ok(())
};
@@ -505,7 +580,7 @@ async fn transcode(
let dur = decodebin
.query_duration::<ClockTime>()
.and_then(|time| time.nanoseconds());
.map(|time| time.nseconds());
let ratio = dur.and_then(|dur| {
if dur == 0 {
@@ -514,11 +589,11 @@ async fn transcode(
let pos = decodebin
.query_position::<ClockTime>()
.and_then(|time| time.nanoseconds());
.map(|time| time.nseconds());
pos.map(|pos| {
let ratio = pos as f64 / dur as f64;
ratio.max(0.0).min(1.0)
ratio.clamp(0.0, 1.0)
})
});
@@ -540,11 +615,7 @@ async fn transcode(
.set_state(gstreamer::State::Null)
.context("Unable to set the pipeline to the `Null` state")?;
fs::rename(&to_path_tmp, &to_path).await?;
Ok(())
})
.await
}
async fn rm_file_on_err<F, T>(path: &Path, f: F) -> Result<T>
@@ -558,7 +629,7 @@ where
Err(fs_err) => {
let err = err
.context(fs_err)
.context(format!("removing {} failed", path.display()));
.context(format!("Removing file {} failed", path.display()));
Err(err)
}
},
@@ -588,10 +659,3 @@ fn path_to_bytes(path: &Path) -> Cow<'_, [u8]> {
Cow::Owned(buf)
}
}
fn path_to_gstring(path: &Path) -> GString {
let buf = path_to_bytes(path);
ffi::CString::new(buf)
.expect("Path contained null byte")
.into()
}

39
src/tag.rs Normal file
View File

@@ -0,0 +1,39 @@
use glib::{GStr, Value, gstr};
use gstreamer::{
Tag, TagFlag,
tags::{CustomTag, merge_strings_with_comma},
};
pub struct MbArtistId;
impl<'a> Tag<'a> for MbArtistId {
type TagType = &'a str;
const TAG_NAME: &'static GStr = gstr!("musicbrainz-artistid");
}
impl CustomTag<'_> for MbArtistId {
const FLAG: TagFlag = TagFlag::Meta;
const NICK: &'static GStr = gstr!("artist ID");
const DESCRIPTION: &'static GStr = gstr!("MusicBrainz artist ID");
fn merge_func(src: &Value) -> Value {
merge_strings_with_comma(src)
}
}
pub struct MbAlbumArtistId;
impl<'a> Tag<'a> for MbAlbumArtistId {
type TagType = &'a str;
const TAG_NAME: &'static GStr = gstr!("musicbrainz-albumartistid");
}
impl CustomTag<'_> for MbAlbumArtistId {
const FLAG: TagFlag = TagFlag::Meta;
const NICK: &'static GStr = gstr!("album artist ID");
const DESCRIPTION: &'static GStr = gstr!("MusicBrainz album artist ID");
fn merge_func(src: &Value) -> Value {
merge_strings_with_comma(src)
}
}

View File

@@ -6,7 +6,7 @@ use std::{
time::Duration,
};
use tokio::{task, time::interval};
use tui::{backend::CrosstermBackend, Terminal};
use tui::{Terminal, backend::CrosstermBackend};
pub const UPDATE_INTERVAL_MILLIS: u64 = 100;
@@ -88,11 +88,11 @@ impl State {
Msg::TaskEnd { id } => {
self.running_tasks
.remove(&id)
.context("unable to remove finished task; could't find task")?;
.context("Unable to remove finished task; could't find task")?;
self.ended_tasks += 1;
}
Msg::TaskProgress { id, ratio } => {
let mut task = self
let task = self
.running_tasks
.get_mut(&id)
.context("Unable to update task progress; could't find task")?;
@@ -102,7 +102,7 @@ impl State {
// TODO
self.running_tasks
.remove(&id)
.context("unable to remove errored task; could't find task")?;
.context("Unable to remove errored task; could't find task")?;
self.ended_tasks += 1;
self.has_errored = true;
}
@@ -136,7 +136,7 @@ impl State {
running_tasks.sort_by_key(|task| task.id);
if !self.has_rendered {
self.terminal.clear().context("cleaning ui failed")?;
self.terminal.clear().context("Clearing ui failed")?;
self.has_rendered = true;
}
@@ -222,7 +222,7 @@ impl State {
chunks[1],
);
})
.context("rendering ui failed")?;
.context("Rendering ui failed")?;
Ok(())
}
@@ -267,8 +267,8 @@ pub fn init() -> (MsgQueue, impl Future<Output = Result<()>>) {
}
})
.await
.context("ui update task failed")?
.context("ui update failed")?;
.context("Ui update task failed")?
.context("Ui update failed")?;
match render_res {
Some(s) => wrapped = Some(s),