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
use crate::{
TranscodeError,
TranscodeResult,
};
use std::{
ffi::{
OsStr,
OsString,
},
iter::once,
os::windows::ffi::{
OsStrExt,
OsStringExt,
},
path::Path,
};
use winapi::{
shared::minwindef::MAX_PATH,
um::fileapi::GetFullPathNameW,
};
pub use windows_media_transcoding_bindings::windows::storage::{
CreationCollisionOption,
StorageFile,
StorageFolder,
};
pub fn normalize_path(path: &str) -> TranscodeResult<String> {
let path = OsStr::new(path)
.encode_wide()
.chain(once(0))
.collect::<Vec<u16>>();
let path = unsafe {
let mut ret = [0; MAX_PATH + 1];
GetFullPathNameW(
path.as_ptr(),
ret.len() as u32,
ret.as_mut_ptr(),
std::ptr::null_mut(),
);
let end = ret.iter().position(|el| *el == 0).unwrap_or(MAX_PATH);
OsString::from_wide(&ret[..end])
};
let path = path.to_str().ok_or(TranscodeError::NonUtf8Path)?;
Ok(path.to_string())
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)]
pub enum CreationOptions {
CreateUniqueName,
Overwrite,
Fail,
Open,
}
impl Default for CreationOptions {
fn default() -> Self {
Self::Overwrite
}
}
impl Into<CreationCollisionOption> for CreationOptions {
fn into(self) -> CreationCollisionOption {
match self {
Self::CreateUniqueName => CreationCollisionOption::GenerateUniqueName,
Self::Overwrite => CreationCollisionOption::ReplaceExisting,
Self::Fail => CreationCollisionOption::FailIfExists,
Self::Open => CreationCollisionOption::OpenIfExists,
}
}
}
#[derive(Debug, Clone)]
pub struct File {
pub(crate) file: StorageFile,
}
impl File {
pub async fn open(path: &str) -> TranscodeResult<Self> {
let path = normalize_path(path)?;
let file = StorageFile::get_file_from_path_async(path)?.await?;
Ok(File { file })
}
pub async fn create(path: &str, options: CreationOptions) -> TranscodeResult<Self> {
let path = normalize_path(path)?;
let path = Path::new(&path);
let folder_path = path
.parent()
.expect("Directory Parent")
.to_str()
.ok_or(TranscodeError::NonUtf8Path)?;
let folder = StorageFolder::get_folder_from_path_async(folder_path)?.await?;
let file_name = Path::new(path)
.file_name()
.expect("File Name")
.to_str()
.ok_or(TranscodeError::NonUtf8Path)?;
let file = folder.create_file_async(file_name, options.into())?.await?;
Ok(Self { file })
}
pub fn as_storage_file(&self) -> &StorageFile {
&self.file
}
}