ffmpegx 0.2.3

Rust bindings for FFmpeg, providing common features such as frame sequence decoding and PCM data encoding/decoding.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use chrono::Local;
use std::fs;
use std::io::Error as IoError;
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub enum FileError {
    Io(String),
    NotFound(String),
    InvalidFileName(String),
    DirectoryCreation(String),
    UnsupportedType(String),
    ReadError(String),
    WriteError(String),
    CopyError(String),
    RemoveError(String),
}
impl From<IoError> for FileError {
    fn from(err: IoError) -> Self {
        FileError::Io(err.to_string())
    }
}
pub type FileResult<T> = Result<T, FileError>;
pub struct FileUtils;
impl FileUtils {
    pub fn ensure_dir(path: &Path) -> FileResult<()> {
        if !path.exists() {
            fs::create_dir_all(path)
                .map_err(|e| FileError::DirectoryCreation(format!("{}: {}", path.display(), e)))?;
        }
        Ok(())
    }
    pub fn ensure_dir_str(path: &str) -> FileResult<()> {
        Self::ensure_dir(Path::new(path))
    }
    pub fn file_exists(path: &Path) -> bool {
        path.exists() && path.is_file()
    }
    pub fn file_exists_str(path: &str) -> bool {
        Self::file_exists(Path::new(path))
    }
    pub fn path_exists(path: &Path) -> bool {
        path.exists()
    }
    pub fn path_exists_str(path: &str) -> bool {
        Self::path_exists(Path::new(path))
    }
    pub fn get_file_name(path: &Path) -> FileResult<String> {
        path.file_name()
            .and_then(|n| n.to_str())
            .map(|s| s.to_string())
            .ok_or_else(|| FileError::InvalidFileName(path.display().to_string()))
    }
    pub fn get_file_stem(path: &Path) -> FileResult<String> {
        path.file_stem()
            .and_then(|n| n.to_str())
            .map(|s| s.to_string())
            .ok_or_else(|| FileError::InvalidFileName(path.display().to_string()))
    }
    pub fn get_file_extension(path: &Path) -> Option<String> {
        path.extension()
            .and_then(|e| e.to_str())
            .map(|s| s.to_string())
    }
    pub fn read_file(path: &Path) -> FileResult<Vec<u8>> {
        fs::read(path).map_err(|e| FileError::ReadError(format!("{}: {}", path.display(), e)))
    }
    pub fn read_file_str(path: &str) -> FileResult<Vec<u8>> {
        Self::read_file(Path::new(path))
    }
    pub fn read_file_to_string(path: &Path) -> FileResult<String> {
        fs::read_to_string(path)
            .map_err(|e| FileError::ReadError(format!("{}: {}", path.display(), e)))
    }
    pub fn read_file_to_string_str(path: &str) -> FileResult<String> {
        Self::read_file_to_string(Path::new(path))
    }
    pub fn write_file(path: &Path, contents: &[u8]) -> FileResult<()> {
        if let Some(parent) = path.parent() {
            let _ = Self::ensure_dir(parent);
        }
        fs::write(path, contents)
            .map_err(|e| FileError::WriteError(format!("{}: {}", path.display(), e)))
    }
    pub fn write_file_str(path: &str, contents: &[u8]) -> FileResult<()> {
        Self::write_file(Path::new(path), contents)
    }
    pub fn write_file_string(path: &Path, contents: &str) -> FileResult<()> {
        Self::write_file(path, contents.as_bytes())
    }
    pub fn write_file_string_str(path: &str, contents: &str) -> FileResult<()> {
        Self::write_file_string(Path::new(path), contents)
    }
    pub fn copy_file(source: &Path, dest: &Path) -> FileResult<u64> {
        if let Some(parent) = dest.parent() {
            let _ = Self::ensure_dir(parent);
        }
        fs::copy(source, dest).map_err(|e| {
            FileError::CopyError(format!("{} -> {}: {}", source.display(), dest.display(), e))
        })
    }
    pub fn copy_file_str(source: &str, dest: &str) -> FileResult<u64> {
        Self::copy_file(Path::new(source), Path::new(dest))
    }
    pub fn copy_file_with_unique_name(source: &Path, target_dir: &Path) -> FileResult<PathBuf> {
        if !Self::file_exists(source) {
            return Err(FileError::NotFound(source.display().to_string()));
        }
        Self::ensure_dir(target_dir)?;
        let file_name = Self::get_file_name(source)?;
        let target_path = target_dir.join(&file_name);
        let final_path = if target_path.exists() {
            let stem = Self::get_file_stem(source)?;
            let ext = Self::get_file_extension(source)
                .map(|e| format!(".{}", e))
                .unwrap_or_default();
            let timestamp = Local::now().timestamp();
            let new_name = format!("{}_{}{}", stem, timestamp, ext);
            target_dir.join(new_name)
        } else {
            target_path
        };
        Self::copy_file(source, &final_path)?;
        Ok(final_path)
    }
    pub fn get_file_size(path: &Path) -> FileResult<u64> {
        let metadata = fs::metadata(path)?;
        Ok(metadata.len())
    }
    pub fn get_file_size_str(path: &str) -> FileResult<u64> {
        Self::get_file_size(Path::new(path))
    }
    pub fn remove_file(path: &Path) -> FileResult<()> {
        fs::remove_file(path)
            .map_err(|e| FileError::RemoveError(format!("{}: {}", path.display(), e)))
    }
    pub fn remove_file_str(path: &str) -> FileResult<()> {
        Self::remove_file(Path::new(path))
    }
    pub fn remove_dir_all(path: &Path) -> FileResult<()> {
        fs::remove_dir_all(path)
            .map_err(|e| FileError::RemoveError(format!("{}: {}", path.display(), e)))
    }
    pub fn remove_dir_all_str(path: &str) -> FileResult<()> {
        Self::remove_dir_all(Path::new(path))
    }
    pub fn remove_dir_all_force(path: &Path) -> FileResult<()> {
        if !path.exists() {
            return Ok(());
        }
        let path_str = path.to_string_lossy().to_string();
        if Self::remove_dir_all(path).is_ok() {
            if !path.exists() {
                return Ok(());
            }
        }
        #[cfg(target_os = "windows")]
        {
            let _ = crate::hidden_cmd("cmd")
                .args(&["/c", "rmdir", "/s", "/q", &path_str])
                .output();
            if path.exists() {
                let _ = crate::hidden_cmd("powershell")
                    .args(&[
                        "-Command",
                        &format!(
                            "Remove-Item -Path '{}' -Recurse -Force -ErrorAction SilentlyContinue",
                            path_str
                        ),
                    ])
                    .output();
            }
        }
        #[cfg(any(target_os = "macos", target_os = "linux"))]
        {
            let _ = crate::hidden_cmd("rm").args(&["-rf", &path_str]).output();
            if path.exists() {
                let _ = crate::hidden_cmd("chflags")
                    .args(&["-R", "nouchg", &path_str])
                    .output();
                let _ = crate::hidden_cmd("rm").args(&["-rf", &path_str]).output();
            }
        }
        if path.exists() {
            return Err(FileError::RemoveError(format!(
                "Failed to remove directory: {}",
                path_str
            )));
        }
        Ok(())
    }
    pub fn read_dir(path: &Path) -> FileResult<Vec<PathBuf>> {
        let mut entries = Vec::new();
        if !path.exists() {
            return Ok(entries);
        }
        for entry in fs::read_dir(path).map_err(|e| {
            FileError::Io(format!(
                "Failed to read directory {}: {}",
                path.display(),
                e
            ))
        })? {
            let entry = entry.map_err(|e| FileError::Io(format!("Failed to read entry: {}", e)))?;
            entries.push(entry.path());
        }
        Ok(entries)
    }
    pub fn read_dir_str(path: &str) -> FileResult<Vec<PathBuf>> {
        Self::read_dir(Path::new(path))
    }
    pub fn read_dir_entries(path: &Path) -> FileResult<Vec<fs::DirEntry>> {
        let mut entries = Vec::new();
        if !path.exists() {
            return Ok(entries);
        }
        for entry in fs::read_dir(path).map_err(|e| {
            FileError::Io(format!(
                "Failed to read directory {}: {}",
                path.display(),
                e
            ))
        })? {
            entries.push(entry.map_err(|e| FileError::Io(format!("Failed to read entry: {}", e)))?);
        }
        Ok(entries)
    }
    pub fn is_video_file(path: &Path) -> bool {
        let video_extensions = [
            "mp4", "mov", "mkv", "avi", "webm", "flv", "wmv", "m4v", "mpeg", "mpg",
        ];
        Self::get_file_extension(path)
            .map(|ext| video_extensions.contains(&ext.to_lowercase().as_str()))
            .unwrap_or(false)
    }
    pub fn is_audio_file(path: &Path) -> bool {
        let audio_extensions = ["mp3", "wav", "flac", "aac", "ogg", "m4a", "wma", "aiff"];
        Self::get_file_extension(path)
            .map(|ext| audio_extensions.contains(&ext.to_lowercase().as_str()))
            .unwrap_or(false)
    }
    pub fn is_image_file(path: &Path) -> bool {
        let image_extensions = [
            "png", "jpg", "jpeg", "gif", "bmp", "webp", "svg", "tiff", "ico",
        ];
        Self::get_file_extension(path)
            .map(|ext| image_extensions.contains(&ext.to_lowercase().as_str()))
            .unwrap_or(false)
    }
    pub fn is_text_file(path: &Path) -> bool {
        let text_extensions = [
            "txt", "md", "csv", "json", "xml", "html", "css", "js", "ts", "rs", "py", "go", "java",
            "c", "cpp", "h", "hpp",
        ];
        Self::get_file_extension(path)
            .map(|ext| text_extensions.contains(&ext.to_lowercase().as_str()))
            .unwrap_or(false)
    }
    pub fn is_gif_file(path: &Path) -> bool {
        Self::get_file_extension(path)
            .map(|ext| ext.to_lowercase() == "gif")
            .unwrap_or(false)
    }
    pub fn is_gif_file_name(file_name: &str) -> bool {
        file_name.to_lowercase().ends_with(".gif")
    }
    pub fn detect_material_type(path: &Path) -> Option<String> {
        if Self::is_video_file(path) {
            Some("video".to_string())
        } else if Self::is_audio_file(path) {
            Some("audio".to_string())
        } else if Self::is_image_file(path) {
            Some("image".to_string())
        } else if Self::is_text_file(path) {
            Some("text".to_string())
        } else {
            None
        }
    }
    pub fn read_text_file(path: &Path) -> FileResult<String> {
        let content = fs::read_to_string(path)?;
        Ok(content)
    }
    pub fn read_text_file_str(path: &str) -> FileResult<String> {
        Self::read_text_file(Path::new(path))
    }
    pub fn get_modified_time(path: &Path) -> FileResult<i64> {
        let metadata = fs::metadata(path)?;
        let modified = metadata
            .modified()
            .map_err(|e| FileError::Io(e.to_string()))?;
        let duration = modified
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|e| FileError::Io(e.to_string()))?;
        Ok(duration.as_secs() as i64)
    }
    pub fn force_delete_file(path: &Path) -> FileResult<()> {
        let path_str = path.to_string_lossy().to_string();
        if Self::remove_file(path).is_ok() {
            if !path.exists() {
                return Ok(());
            }
        }
        #[cfg(target_os = "windows")]
        {
            let _ = crate::hidden_cmd("cmd")
                .args(&["/c", "del", "/f", "/q", &path_str])
                .output();
            if path.exists() {
                let _ = crate::hidden_cmd("powershell")
                    .args(&[
                        "-Command",
                        &format!(
                            "Remove-Item -Path '{}' -Force -ErrorAction SilentlyContinue",
                            path_str
                        ),
                    ])
                    .output();
            }
        }
        #[cfg(any(target_os = "macos", target_os = "linux"))]
        {
            let _ = crate::hidden_cmd("rm").args(&["-f", &path_str]).output();
            if path.exists() {
                let _ = crate::hidden_cmd("chflags")
                    .args(&["-R", "nouchg", &path_str])
                    .output();
                let _ = crate::hidden_cmd("rm").args(&["-f", &path_str]).output();
            }
        }
        if path.exists() {
            return Err(FileError::Io(
                "Failed to delete file even with force".to_string(),
            ));
        }
        Ok(())
    }
    pub fn delete_cache_files(cache_dir: &Path, file_name: &str) -> FileResult<()> {
        if !cache_dir.exists() {
            return Ok(());
        }
        let _ = fs::read_dir(cache_dir).map(|entries| {
            for entry in entries {
                if let Ok(entry) = entry {
                    let name = entry.file_name();
                    let name_str = name.to_string_lossy();
                    if name_str.contains(file_name) {
                        let _ = fs::remove_file(entry.path());
                    }
                }
            }
        });
        Ok(())
    }
    pub fn get_parent(path: &Path) -> Option<PathBuf> {
        path.parent().map(|p| p.to_path_buf())
    }
    pub fn join_path(parent: &Path, child: &str) -> PathBuf {
        parent.join(child)
    }
    pub fn to_string_lossy(path: &Path) -> String {
        path.to_string_lossy().to_string()
    }
    pub fn get_metadata(path: &Path) -> FileResult<fs::Metadata> {
        fs::metadata(path).map_err(|e| FileError::Io(format!("{}: {}", path.display(), e)))
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::env::temp_dir;
    #[test]
    fn test_is_video_file() {
        assert!(FileUtils::is_video_file(Path::new("video.mp4")));
        assert!(FileUtils::is_video_file(Path::new("video.MOV")));
        assert!(!FileUtils::is_video_file(Path::new("audio.mp3")));
    }
    #[test]
    fn test_is_audio_file() {
        assert!(FileUtils::is_audio_file(Path::new("audio.mp3")));
        assert!(FileUtils::is_audio_file(Path::new("audio.wav")));
        assert!(!FileUtils::is_audio_file(Path::new("video.mp4")));
    }
    #[test]
    fn test_is_image_file() {
        assert!(FileUtils::is_image_file(Path::new("image.png")));
        assert!(FileUtils::is_image_file(Path::new("image.JPG")));
        assert!(!FileUtils::is_image_file(Path::new("video.mp4")));
    }
    #[test]
    fn test_detect_material_type() {
        assert_eq!(
            FileUtils::detect_material_type(Path::new("video.mp4")),
            Some("video".to_string())
        );
        assert_eq!(
            FileUtils::detect_material_type(Path::new("audio.mp3")),
            Some("audio".to_string())
        );
        assert_eq!(
            FileUtils::detect_material_type(Path::new("image.png")),
            Some("image".to_string())
        );
        assert_eq!(
            FileUtils::detect_material_type(Path::new("text.txt")),
            Some("text".to_string())
        );
        assert_eq!(
            FileUtils::detect_material_type(Path::new("unknown.xyz")),
            None
        );
    }
}