ffmpeg_cmdline_utils-0.1.3/.cargo_vcs_info.json0000644000000001360000000000100152140ustar { "git": { "sha1": "74dde7001a0dccabdebd7dfbcde89bc7744cae9b" }, "path_in_vcs": "" }ffmpeg_cmdline_utils-0.1.3/.gitignore000064400000000000000000000001331046102023000157710ustar 00000000000000/target **/*.rs.bk #file.out# file.out Cargo.lock .vscode/launch.json .vscode/tasks.json ffmpeg_cmdline_utils-0.1.3/Cargo.toml0000644000000023540000000000100132160ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "ffmpeg_cmdline_utils" version = "0.1.3" description = "Rust wrapper around the commandline interface to FFMPEG. Can be used to read frames from videos into bufrers in rust." readme = "README.md" keywords = ["ffmpeg"] categories = [ "multimedia::video", "api-bindings", ] license = "MIT OR Apache-2.0" repository = "https://github.com/Farmadupe/ffmpeg_cmdline_utils" [lib] name = "ffmpeg_cmdline_utils" crate-type = ["lib"] path = "src/lib.rs" [dependencies.image] version = "0.24" [dependencies.rayon] version = "1.5" [dependencies.serde] version = "1.0" features = ["derive"] [dependencies.serde_json] version = "1.0" [dependencies.thiserror] version = "1.0" [target."cfg(windows)".dependencies.winapi] version = "0.3" features = ["winbase"] ffmpeg_cmdline_utils-0.1.3/Cargo.toml.orig000064400000000000000000000013011046102023000166660ustar 00000000000000[package] name = "ffmpeg_cmdline_utils" version = "0.1.3" edition = "2018" license = "MIT OR Apache-2.0" description = "Rust wrapper around the commandline interface to FFMPEG. Can be used to read frames from videos into bufrers in rust." repository = "https://github.com/Farmadupe/ffmpeg_cmdline_utils" readme = "README.md" keywords = ["ffmpeg"] categories = ["multimedia::video", "api-bindings"] [lib] name = "ffmpeg_cmdline_utils" path = "src/lib.rs" crate-type = ["lib"] [dependencies] rayon = "1.5" thiserror = "1.0" image = "0.24" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" [target.'cfg(windows)'.dependencies] winapi = {version = "0.3", features = ["winbase"]} ffmpeg_cmdline_utils-0.1.3/LICENSE-APACHE000064400000000000000000000261141046102023000157340ustar 00000000000000 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 2021 Farmadupe 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. ffmpeg_cmdline_utils-0.1.3/LICENSE-MIT000064400000000000000000000020531046102023000154400ustar 00000000000000MIT License Copyright (c) 2021 Farmadupe 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. ffmpeg_cmdline_utils-0.1.3/README.md000064400000000000000000000000271046102023000152620ustar 00000000000000# ffmpeg_cmdline_utils ffmpeg_cmdline_utils-0.1.3/src/ffmpeg_error_kind.rs000064400000000000000000000026701046102023000206300ustar 00000000000000use serde::Deserialize; use serde::Serialize; use thiserror::Error; use crate::*; /// Various causes of failure for ffmpeg/ffprobe functions. #[derive(Error, Debug, Clone, Serialize, Deserialize)] pub enum FfmpegErrorKind { /// Ffmpeg/Ffprobe command was not found. Make sure Ffmpeg is installed and can be found on the command line. #[error("ffmpeg/ffprobe file not found. Make sure ffmpeg/ffprobe are installed and visible on the command line")] FfmpegNotFound, /// Io error occurred while executing Ffmpeg/Ffprobe command #[error("Ffmpeg IO error")] Io(String), /// Ffmpeg/Ffprobe returned a nonzero exit code. Because ffmpeg sometimes prints long error strings /// to stderr, The resulting string contains the first few hundred characters of the error message. #[error("Internal Ffmpeg Failure: {0}")] FfmpegInternal(String), /// Failed to interpret Ffmpeg/Ffprobe output as a utf8-string. #[error("utf8 parsing/conversion failure")] Utf8Conversion, /// When using Ffprobe to obtain the resolution of the video file before beginning the /// decoding process, either the X or Y dimensions was zero. /// Note: This sometimes occur when attempting to decode frames from an audio file. #[error("Ffmmpeg decoded no frames from the video")] InvalidResolution, /// Failed to obtain video information. #[error("Failed to get video properties")] Info(#[from] VideoInfoError), } ffmpeg_cmdline_utils-0.1.3/src/ffmpeg_ops.rs000064400000000000000000000315621046102023000172750ustar 00000000000000use std::{ ffi::OsStr, io::prelude::*, path::{Path, PathBuf}, process::{Child, Command, ExitStatus, Stdio}, time::{Duration, SystemTime}, }; #[cfg(target_family = "windows")] use std::os::windows::process::CommandExt; use FfmpegCommandName::*; use FfmpegErrorKind::*; use crate::*; const FFPROBE_TIMEOUT_SECS: usize = 60; #[derive(Debug)] pub struct FfmpegFrames { x: u32, y: u32, child: std::process::Child, num_frames: u32, frames_read: u32, timeout_time: SystemTime, finished: bool, } impl Iterator for FfmpegFrames { type Item = image::RgbImage; fn next(&mut self) -> Option { //Check exit conditions let read_enough_frames = self.frames_read >= self.num_frames; let exceeded_timeout = SystemTime::now() > self.timeout_time; if self.finished || read_enough_frames || exceeded_timeout { self.finished = true; let _kill_error = self.child.kill(); let _wait_error = self.child.wait(); return None; } let mut raw_buf = vec![0u8; (self.x * self.y * 3) as usize]; // Otherwise wait for the frame until the timeout is exceeded let stdout = self.child.stdout.as_mut().unwrap(); let mut buf_head = 0; while buf_head < raw_buf.len() { //abort on timeout. if SystemTime::now() > self.timeout_time { self.finished = true; return None; } let slice_to_read_into = &mut raw_buf[buf_head..]; match stdout.read(slice_to_read_into) { //something went wrong, or no more data can be read Err(_) | Ok(0) => { self.finished = true; return None; } Ok(bytes_read) => buf_head += bytes_read, } //sleep for a small amount of time; std::thread::sleep(Duration::from_millis(10)); } self.frames_read += 1; Some(image::RgbImage::from_raw(self.x, self.y, raw_buf).unwrap()) } } // to prevent accumulation of zombie processes, reap the return code of // ffmpeg subcommands (if nothing else has done so already) here impl Drop for FfmpegFrames { fn drop(&mut self) { let _kill_error = self.child.kill(); let _wait_error = self.child.wait(); } } pub struct FfmpegFrameReaderBuilder { src_path: PathBuf, fps: Option, num_frames: Option, timeout_secs: Option, } impl FfmpegFrameReaderBuilder { pub fn new(src_path: PathBuf) -> Self { Self { src_path, fps: None, num_frames: None, timeout_secs: None, } } pub fn fps(&mut self, fps: impl AsRef) -> &mut Self { self.fps = Some(fps.as_ref().to_string()); self } pub fn num_frames(&mut self, num_frames: u32) -> &mut Self { self.num_frames = Some(num_frames); self } pub fn timeout_secs(&mut self, timeout_secs: u64) -> &mut Self { self.timeout_secs = Some(timeout_secs); self } pub fn spawn(&self) -> Result<(FfmpegFrames, VideoInfo), FfmpegErrorKind> { //we also need to find out the resolution of the video so that stdout can be converted into frames. let stats = VideoInfo::new(&self.src_path).map_err(|e| FfmpegErrorKind::Io(e.to_string()))?; //bail out if we get invalid dimensions. let (x, y) = stats.resolution(); if x == 0 || y == 0 { return Err(FfmpegErrorKind::InvalidResolution); } let fps_string: String; let fps_arg = match self.fps { Some(ref fps) => { fps_string = format!("fps={}", fps); vec![OsStr::new("-vf"), OsStr::new(&fps_string)] } None => vec![], }; let num_frames_string: String; let num_frames_arg = match self.num_frames { Some(ref num_frames) => { num_frames_string = num_frames.to_string(); vec![OsStr::new("-vframes"), OsStr::new(&num_frames_string)] } None => vec![], }; #[rustfmt::skip] let mut args = vec![ OsStr::new("-hide_banner"), OsStr::new("-loglevel"), OsStr::new("warning"), OsStr::new("-nostats"), // OsStr::new("-ss"), OsStr::new("00:00:30"), OsStr::new("-i"), OsStr::new(&self.src_path), ]; args.extend(fps_arg); args.extend(num_frames_arg); #[rustfmt::skip] args.extend(&[ OsStr::new("-pix_fmt"), OsStr::new("rgb24"), OsStr::new("-c:v"), OsStr::new("rawvideo"), OsStr::new("-f"), OsStr::new("image2pipe"), OsStr::new("-") ]); //println!("{:?}", args); let mut child = spawn_ffmpeg_command(Ffmpeg, &args, true)?; //Prevent possible lockup if stderr gets full by dropping the //handle from our side std::mem::drop(child.stderr.take()); let (x, y) = stats.resolution; let frame_iterator = FfmpegFrames { x, y, child, num_frames: self.num_frames.unwrap_or(u32::MAX), frames_read: 0, timeout_time: SystemTime::now() + Duration::from_secs(self.timeout_secs.unwrap_or(u32::MAX as u64)), // (just in case u64::MAX has wraparound issues) finished: false, }; //Ok((frames, stats)) Ok((frame_iterator, stats)) } } pub fn get_video_stats>(src_path: P) -> Result { let args = &[ OsStr::new("-v"), OsStr::new("quiet"), OsStr::new("-show_format"), OsStr::new("-show_streams"), OsStr::new("-print_format"), OsStr::new("json"), OsStr::new(src_path.as_ref()), ]; let stdout = run_ffmpeg_command(Ffprobe, args, true)?.stdout; String::from_utf8(stdout).map_err(|_| Utf8Conversion) } pub fn is_video_file>(src_path: P) -> Result { fn get_ffprobe_output>(src_path: P) -> Result { //"ffprobe -v error -select_streams v -show_entries stream=codec_type,codec_name,duration -of compact=p=0:nk=1 {}" #[rustfmt::skip] let args = &[ OsStr::new("-v"), OsStr::new("error"), OsStr::new("-select_streams"), OsStr::new("v"), OsStr::new("-show_entries"), OsStr::new("stream=codec_type,codec_name,duration"), OsStr::new("-of"), OsStr::new("compact=p=0:nk=1"), OsStr::new(src_path.as_ref()) ]; run_ffmpeg_command(Ffprobe, args, true).and_then(|output| { String::from_utf8(output.stdout) .map_err(|_| Utf8Conversion) .map(|s| s.trim().to_string()) }) } let streams_string = get_ffprobe_output(src_path.as_ref())?; let mut fields_iter = streams_string.split('|'); let _codec_name = fields_iter.next().unwrap_or(""); let codec_type = fields_iter.next().unwrap_or(""); let duration = fields_iter .next() .unwrap_or("") .trim() .parse::() .unwrap_or(999.0); if codec_type != "video" { return Ok(false); } if duration < 1.0 { return Ok(false); } Ok(true) } pub fn ffmpeg_and_ffprobe_are_callable() -> bool { //check ffprobe is callable. if run_ffmpeg_command(Ffprobe, &[OsStr::new("-version")], true).is_err() { return false; } //now ffmpeg. if run_ffmpeg_command(Ffmpeg, &[OsStr::new("-version")], true).is_err() { return false; } true } #[derive(Debug, Clone, Copy)] enum FfmpegCommandName { Ffprobe, Ffmpeg, } impl FfmpegCommandName { pub fn as_os_str(&self) -> &'static OsStr { match self { Self::Ffprobe => OsStr::new("ffprobe"), Self::Ffmpeg => OsStr::new("ffmpeg"), } } } fn spawn_ffmpeg_command( name: FfmpegCommandName, args: &[&OsStr], stderr_null: bool, ) -> Result { use FfmpegErrorKind::*; let stderr_cfg = if stderr_null { Stdio::null() } else { Stdio::piped() }; let mut command = Command::new(name.as_os_str()); command .args(args) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(stderr_cfg); //do not spawn a command window on windows when when in a gui application #[cfg(target_family = "windows")] command.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW); command.spawn().map_err(|e| match e.kind() { //shell failed to execute the command. Separate out FileNotFound from all other errors //as by far the most likely cause is ffmpeg is not installed. std::io::ErrorKind::NotFound => FfmpegNotFound, _ => Io(format!("{:?}", e.kind())), }) } struct FfmpegOutput { _stderr: Vec, stdout: Vec, } type FfmpegCmdResult = Result; fn run_ffmpeg_command( name: FfmpegCommandName, args: &[&OsStr], stderr_null: bool, ) -> FfmpegCmdResult { fn truncate_ffmpeg_err_msg(stderr: Vec) -> FfmpegErrorKind { match std::str::from_utf8(&stderr) { Ok(error_text) => FfmpegInternal(error_text.chars().take(500).collect::()), Err(_) => Utf8Conversion, } } //Wait for the ffmpeg operation to complete FFMPEG_TIMEOUT_SECS let mut child = spawn_ffmpeg_command(name, args, stderr_null)?; //Accumulators for output let mut stdout = child.stdout.take().expect("Failed to obtain stdout"); let mut stderr = (!stderr_null).then(|| child.stderr.take().expect("Failed to obtain stderr")); let mut timeout_counter_secs = 0; //We will assume that ffmpeg/ffprobe will usually complete in the first 1 sec. To keep this program responsive we will check for results at a rate of 100hz. //Then we will switch to checking at 1 Hz. let thread = std::thread::spawn(move || -> std::io::Result { let max_initial_fast_counts = 100; let mut initial_fast_counts = 0; let mut maybe_status; while timeout_counter_secs < FFPROBE_TIMEOUT_SECS { maybe_status = child.try_wait(); match maybe_status { Err(e) => return Err(e), Ok(None) => { if initial_fast_counts < max_initial_fast_counts { std::thread::sleep(Duration::from_millis(10)); initial_fast_counts += 1; if initial_fast_counts == max_initial_fast_counts { timeout_counter_secs += 1; } } else { std::thread::sleep(Duration::from_millis(1_000)); timeout_counter_secs += 1; } } Ok(Some(s)) => return Ok(s), } } //timed out Err(std::io::Error::from(std::io::ErrorKind::TimedOut)) }); //read from stdout and stderr let mut stdout_done = false; let mut stderr_done = stderr_null; //Buffer for stdout and stderr let mut read_buf = [0u8; 4096]; let mut stdout_acc = vec![]; let mut stderr_acc = vec![]; while !(stdout_done && stderr_done) { if !stdout_done { match stdout.read(&mut read_buf) { Err(_) | Ok(0) => stdout_done = true, Ok(amount) => { stdout_acc .write_all(&read_buf[..amount]) .expect("failed to append to string"); } } } if !stderr_done { match stderr.as_mut().unwrap().read(&mut read_buf) { Err(_) | Ok(0) => stderr_done = true, Ok(amount) => { stderr_acc .write_all(&read_buf[..amount]) .expect("failed to append to string"); } } } } let exit_status = thread.join().expect("thread couldn't join"); match exit_status { Err(e) => match e.kind() { std::io::ErrorKind::NotFound => Err(FfmpegNotFound), _ => Err(Io(format!("{:?}", e.kind()))), }, //The shell successfully executed it, but maybe it returned an error code Ok(status) => { if status.success() { Ok(FfmpegOutput { stdout: stdout_acc, _stderr: stderr_acc, }) } else { //sometimes ffmpeg creates very long error messages. Limit them to the first 500 characters Err(truncate_ffmpeg_err_msg(stderr_acc)) } } } } ffmpeg_cmdline_utils-0.1.3/src/ffmpeg_stats.rs000064400000000000000000000171321046102023000176270ustar 00000000000000use std::path::Path; use serde::{Deserialize, Serialize}; use thiserror::Error; use crate::*; #[derive(Debug, Deserialize, Serialize, Clone, Error)] pub enum VideoInfoError { #[error("Error parsing stats: {0}")] JsonError(String), #[error("Error parsing stats: {0}")] ParseIntError(String), #[error("Error parsing stats: {0}")] ParseFloatError(String), } impl From for VideoInfoError { fn from(e: serde_json::Error) -> Self { VideoInfoError::JsonError(format!("{}", e)) } } impl From for VideoInfoError { fn from(e: std::num::ParseIntError) -> Self { VideoInfoError::ParseIntError(format!("{}", e)) } } impl From for VideoInfoError { fn from(e: std::num::ParseFloatError) -> Self { VideoInfoError::ParseFloatError(format!("{}", e)) } } // There is a slighty gotcha in ffmpeg where if the video metadata declares a rotation, // raw (x, y) resolution in that metadata refers to the "unrotated" resolution. we must // therefore swap the x and y values if the rotation is 90 or 270 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Copy, Serialize, Deserialize, Hash)] enum FfmpegVideoRotation { Rot0, Rot90, Rot180, Rot270, } use FfmpegVideoRotation::*; impl Default for FfmpegVideoRotation { fn default() -> Self { Self::Rot0 } } #[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)] pub struct VideoInfo { pub duration: f64, pub size: u64, pub bit_rate: u32, pub resolution: (u32, u32), pub has_audio: bool, } impl VideoInfo { pub fn new

(src_path: P) -> Result where P: AsRef, { use serde_json::Value; let stats_string = get_video_stats(&src_path)?; let stats_parsed: Value = serde_json::from_str(&stats_string).map_err(VideoInfoError::from)?; let duration = &stats_parsed["format"]["duration"]; let duration = if let Value::String(d) = duration { d.parse().map_err(VideoInfoError::from)? } else { 0.0 }; let size = &stats_parsed["format"]["size"]; let size = if let Value::String(s) = size { s.parse().map_err(VideoInfoError::from)? } else { 0 }; let bit_rate = &stats_parsed["format"]["bit_rate"]; let bit_rate = if let Value::String(br) = bit_rate { br.parse().map_err(VideoInfoError::from)? } else { 0 }; fn streams_of_type(stats_parsed: &Value, stream_type: &str) -> Option> { if let Value::Array(streams) = &stats_parsed["streams"] { let ret = streams .iter() .filter(|s| match &s["codec_type"] { Value::String(codec_type) => codec_type == stream_type, _ => false, }) .cloned() .collect(); Some(ret) } else { None } } fn first_u32_from_video_streams(stats_parsed: &Value, field_name: &str) -> Option { let video_streams = streams_of_type(stats_parsed, "video")?; let all_matched_values = video_streams .iter() .filter_map(|stream| { if let Value::Number(v) = &stream[field_name] { Some(v.as_u64()? as u32) } else { None } }) .collect::>(); all_matched_values.iter().cloned().next() } // If the video metadata declares that a video is rotated, then FFMPEG will conveniently autorotate // each frame for us, however we will have to remember to swap around x and y axis if the rotation is // 90 or 270 let error_out = |rotation: &str| -> Result { Err(VideoInfoError::ParseIntError(format!( "ffprobe failure. Got unexpected rotation. src_path: {}, {rotation}", src_path.as_ref().display() ))) }; let rotation = { match streams_of_type(&stats_parsed, "video") { Some(video_streams) => match video_streams.as_slice() { [] => Ok(FfmpegVideoRotation::Rot0), _ => match &video_streams[0]["side_data_list"][0]["rotation"] { //rotation not found (most videos) Value::Null => Ok(FfmpegVideoRotation::Rot0), //rotation found Value::String(rotation) => { let rotation = rotation.parse::(); match rotation { Ok(0) => Ok(FfmpegVideoRotation::Rot0), Ok(90) => Ok(FfmpegVideoRotation::Rot90), Ok(180) => Ok(FfmpegVideoRotation::Rot180), Ok(-90) | Ok(270) => Ok(FfmpegVideoRotation::Rot270), Ok(bad_rot) => error_out(bad_rot.to_string().as_str()), Err(e) => Err(VideoInfoError::from(e)), } } //rotation found Value::Number(rotation) => { let rotation = rotation.as_i64(); match rotation { Some(0) => Ok(FfmpegVideoRotation::Rot0), Some(90) => Ok(FfmpegVideoRotation::Rot90), Some(180) | Some(-180) => Ok(FfmpegVideoRotation::Rot180), Some(-90) | Some(270) => Ok(FfmpegVideoRotation::Rot270), Some(bad_rot) => error_out(bad_rot.to_string().as_str()), None => error_out(""), } } _ => Err(VideoInfoError::JsonError( "Failed to parse JSON".to_string(), )), }, }, None => Ok(FfmpegVideoRotation::Rot0), } }?; //println!("{:#?}: {}", rotation, src_path.as_ref().display()); let first_width = first_u32_from_video_streams(&stats_parsed, "width").unwrap_or(0); let first_height = first_u32_from_video_streams(&stats_parsed, "height").unwrap_or(0); let resolution = if matches!(rotation, Rot0 | Rot180) { (first_width, first_height) } else { (first_height, first_width) }; let audio_streams = streams_of_type(&stats_parsed, "audio"); let has_audio = match audio_streams { None => false, Some(audio_streams) => audio_streams.iter().any(|stream| match &stream["codec_type"] { Value::String(codec_type) => codec_type == "audio", _ => false, }), }; Ok(VideoInfo { duration, size, bit_rate, resolution, has_audio, }) } pub fn duration(&self) -> f64 { self.duration } pub fn size(&self) -> u64 { self.size } pub fn bit_rate(&self) -> u32 { self.bit_rate } pub fn resolution(&self) -> (u32, u32) { self.resolution } pub fn has_audio(&self) -> bool { self.has_audio } } ffmpeg_cmdline_utils-0.1.3/src/lib.rs000064400000000000000000000002641046102023000157110ustar 00000000000000mod ffmpeg_error_kind; mod ffmpeg_ops; mod ffmpeg_stats; mod video_frames; pub use ffmpeg_error_kind::*; pub use ffmpeg_ops::*; pub use ffmpeg_stats::*; pub use video_frames::*; ffmpeg_cmdline_utils-0.1.3/src/video_frames.rs000064400000000000000000000176551046102023000176220ustar 00000000000000use image::{ imageops::{resize, FilterType::Lanczos3}, GenericImageView, GrayImage, RgbImage, }; #[derive(Debug, Clone)] pub struct VideoFrames { frames: Vec, } impl VideoFrames { pub fn from_images(images: &[RgbImage]) -> Self { Self { frames: images.to_vec(), } } pub fn without_letterbox(&self) -> Self { type RgbView<'a> = image::SubImage<&'a RgbImage>; enum LetterboxColour { BlackWhite(u32), _AnyColour(u32), } use LetterboxColour::*; let cfg: LetterboxColour = BlackWhite(16); enum Side { Left, Right, Top, Bottom, } use Side::*; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] struct Crop { orig_res: (u32, u32), left: u32, right: u32, top: u32, bottom: u32, } impl Crop { pub fn new(orig_res: (u32, u32), left: u32, right: u32, top: u32, bottom: u32) -> Self { //validate that the crop actually leaves some pixels. For now don't return an Err, just //replace with a crop of 0. Self { orig_res, left, right, top, bottom, } .validate_or_default() } pub fn union(&self, other: &Self) -> Self { use std::cmp::min; Crop::new( self.orig_res, min(self.left, other.left), min(self.right, other.right), min(self.top, other.top), min(self.bottom, other.bottom), ) } pub fn as_view_args(&self) -> (u32, u32, u32, u32) { let (orig_width, orig_height) = self.orig_res; let coord_x = self.left; let coord_y = self.top; let width = orig_width - (self.left + self.right); let height = orig_height - (self.top + self.bottom); (coord_x, coord_y, width, height) } fn validate_or_default(self) -> Self { let (width, height) = self.orig_res; let valid = self.left + self.right < width && self.top + self.bottom < height; if valid { self } else { Crop::new(self.orig_res, 0, 0, 0, 0) } } } fn measure_frame(frame: &RgbView, colour: &LetterboxColour) -> Crop { let (width, height) = frame.dimensions(); let measure_side = |side: Side| -> u32 { //get the window of pixels representing the next row/column to be checked let pixel_window = |idx: u32| -> RgbView { #[rustfmt::skip] let ret = match side { // x y width height Left => frame.view(idx, 0, 1, height), Right => frame.view(width - idx - 1, 0, 1, height), Top => frame.view(0, idx, width, 1), Bottom => frame.view(0, height - idx - 1, width, 1), }; ret }; let is_letterbox = |strip: &RgbView| -> bool { match colour { BlackWhite(tol) => strip.pixels().all(|(_x, _y, image::Rgb::([r, g, b]))| { let black_enough = r as u32 + g as u32 + b as u32 <= tol * 3; let white_enough = r as u32 + g as u32 + b as u32 >= (u8::MAX as u32 - tol) * 3; black_enough || white_enough }), _AnyColour(tol) => { //calculate range let (mut min_r, mut min_g, mut min_b) = (u8::MAX, u8::MAX, u8::MAX); let (mut max_r, mut max_g, mut max_b) = (u8::MIN, u8::MIN, u8::MIN); for (_x, _y, image::Rgb::([ref r, ref g, ref b])) in strip.pixels() { #[rustfmt::skip] { if r < &min_r {min_r = *r} if r > &max_r {max_r = *r} if g < &min_g {min_g = *g} if g > &max_g {max_g = *g} if b < &min_b {min_b = *b} if b > &max_b {max_b = *b} }; } let (range_r, range_g, range_b) = ( max_r.saturating_sub(min_r) as u32, max_g.saturating_sub(min_g) as u32, max_b.saturating_sub(min_b) as u32, ); range_r + range_g + range_b <= tol * 3 } } }; let pix_range = match side { Left | Right => 0..width, Top | Bottom => 0..height, }; pix_range.map(pixel_window).take_while(is_letterbox).count() as u32 }; Crop::new( (width, height), measure_side(Left), measure_side(Right), measure_side(Top), measure_side(Bottom), ) } let crop = self .frames .iter() .map(|frame| measure_frame(&frame.view(0, 0, frame.width(), frame.height()), &cfg)) .reduce(|x, y| x.union(&y)) .unwrap(); let (x, y, width, height) = crop.as_view_args(); let cropped_frames = self .frames .iter() .map(|frame| frame.view(x, y, width, height).to_image()) .collect(); Self { frames: cropped_frames } } pub fn resize(&self, width: u32, height: u32) -> Self { let resized_frames = self .frames .iter() .map(|frame| resize(frame, width, height, Lanczos3)) .collect(); Self { frames: resized_frames } } pub fn into_inner(self) -> Vec { self.frames } pub fn len(&self) -> usize { self.frames.len() } pub fn is_empty(&self) -> bool { self.frames.is_empty() } pub fn png_size(&self) -> u32 { //force resize to ensure that different resolutions are normalized let width = 1024; let height = 1024; //encode each frame as png and get its size self.frames .iter() .map(|frame| { let resized = resize(frame, width, height, Lanczos3); let mut buf = std::io::Cursor::new(vec![]); resized .write_to(&mut buf, image::ImageOutputFormat::Png) .map(|()| buf.into_inner().len() as u32) .unwrap_or_default() }) .sum() } } pub struct GrayFramifiedVideo { frames: Vec, } impl From for GrayFramifiedVideo { fn from(rgb: VideoFrames) -> Self { let images_gray = rgb .frames .into_iter() .map(|img| { let grey_buf: GrayImage = image::buffer::ConvertBuffer::convert(&img); grey_buf }) .collect::>(); Self { frames: images_gray } } } impl GrayFramifiedVideo { pub fn into_inner(self) -> Vec { self.frames } }