Feat: Support command-line arguments for input video path

This commit is contained in:
2026-02-25 17:24:44 +08:00
parent 6f1354a5c0
commit 8b46d876bb

View File

@@ -3,21 +3,37 @@ use ffmpeg::format::{input, Pixel};
use ffmpeg::media::Type; use ffmpeg::media::Type;
use ffmpeg::codec::{context::Context, decoder}; use ffmpeg::codec::{context::Context, decoder};
use std::path::Path; use std::path::Path;
use std::env; // 引入 env 模組來獲取命令行參數
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
// 初始化 FFmpeg
ffmpeg::init()?; ffmpeg::init()?;
let input_path = "test.mp4"; // --- 新增:獲取命令行參數 ---
let args: Vec<String> = env::args().collect();
let input_path = if args.len() > 1 {
// 如果用戶提供了參數,使用第一個參數作為路徑
&args[1]
} else {
// 如果沒有提供參數,顯示使用說明並退出
eprintln!("Usage: {} <video_file_path>", args[0]);
eprintln!("Example: {} ./my_movie.mp4", args[0]);
eprintln!(" {} /Volumes/Drive/Videos/test.mkv", args[0]);
return Ok(());
};
// -------------------------
if !Path::new(input_path).exists() { if !Path::new(input_path).exists() {
eprintln!("錯誤:找不到檔案 '{}'", input_path); eprintln!("錯誤:找不到檔案 '{}'", input_path);
eprintln!("請將一個視頻文件重命名為 'test.mp4' 並放在專案根目錄。");
return Ok(()); return Ok(());
} }
// 打開輸入檔案 (不再需要 mut除非我們要讀取 packet)
let ictx = input(&input_path)?; let ictx = input(&input_path)?;
println!("=== 檔案基本資訊 ==="); println!("=== 檔案基本資訊 ===");
println!("檔案路徑: {}", input_path); // 顯示當前分析的文件
println!("格式名稱 (Format): {}", ictx.format().name()); println!("格式名稱 (Format): {}", ictx.format().name());
println!("長描述: {}", ictx.format().description()); println!("長描述: {}", ictx.format().description());
@@ -70,9 +86,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}, },
Type::Audio => { Type::Audio => {
let sample_rate = (*ptr).sample_rate; let sample_rate = (*ptr).sample_rate;
// 新版本使用 ch_layout.nb_channels 獲取聲道數
// 【關鍵修復】新版本使用 ch_layout.nb_channels 獲取聲道數
// ch_layout 是一個 AVChannelLayout 結構體
let channels = (*ptr).ch_layout.nb_channels; let channels = (*ptr).ch_layout.nb_channels;
let sample_fmt_val = (*ptr).sample_fmt; let sample_fmt_val = (*ptr).sample_fmt;
@@ -82,22 +96,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!(" 聲道數: {}", channels); println!(" 聲道數: {}", channels);
println!(" 音訊格式: {:?}", format); println!(" 音訊格式: {:?}", format);
// 可選:打印聲道佈局描述 (例如 "stereo", "5.1")
// 需要引入 ffi 來調用 av_channel_layout_describe
/*
let mut buf = vec![0u8; 1024];
let ret = ffmpeg::ffi::av_channel_layout_describe(
&(*ptr).ch_layout,
buf.as_mut_ptr() as *mut i8,
buf.len() as i32
);
if ret >= 0 {
if let Ok(layout_str) = std::ffi::CStr::from_bytes_until_nul(&buf) {
println!(" 聲道佈局: {}", layout_str.to_string_lossy());
}
}
*/
if let Some(codec_name) = context.codec() { if let Some(codec_name) = context.codec() {
println!(" 編碼器名稱: {}", codec_name.name()); println!(" 編碼器名稱: {}", codec_name.name());
} }