-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathprogress.rs
More file actions
287 lines (251 loc) · 8.88 KB
/
progress.rs
File metadata and controls
287 lines (251 loc) · 8.88 KB
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
// Copyright 2024 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.
// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.
//! Example demonstrating the progress/cancel API.
//!
//! With no arguments it runs against embedded test fixtures:
//! - reads `CA.jpg` and signs it to `target/progress_output.jpg`
//!
//! With one argument it performs a read-only pass:
//! - `cargo run --example progress -- input.jpg`
//!
//! With two arguments it reads and signs:
//! - `cargo run --example progress -- input.jpg output.jpg`
//!
//! Progress lines are printed to stdout. Press Enter at any time to cancel.
use std::{
env,
fs::{self, OpenOptions},
io::{BufReader, Cursor},
path::PathBuf,
sync::{Arc, Mutex},
time::Instant,
};
#[cfg(not(target_arch = "wasm32"))]
use std::{io, thread};
use anyhow::{Context as _, Result};
use c2pa::{Builder, BuilderIntent, Context, Error, ProgressPhase, Reader, Settings};
use serde_json::json;
const SOURCE_IMAGE: &[u8] = include_bytes!("../tests/fixtures/CA.jpg");
const DEFAULT_FORMAT: &str = "image/jpeg";
/// Infer the MIME type from a file's extension, falling back to JPEG.
fn format_for_path(path: &std::path::Path) -> String {
c2pa::format_from_path(path).unwrap_or_else(|| DEFAULT_FORMAT.to_string())
}
fn default_output_path() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target/progress_output.jpg")
}
fn manifest_def(title: &str, format: &str) -> String {
json!({
"title": title,
"format": format,
"claim_generator_info": [{
"name": "c2pa progress example",
"version": env!("CARGO_PKG_VERSION")
}]
})
.to_string()
}
fn print_progress(phase: ProgressPhase, step: u32, total: u32, elapsed_ms: f64) {
if total == 0 {
println!("[{elapsed_ms:>8.3}ms] {phase:?} {step}/?");
} else {
println!("[{elapsed_ms:>8.3}ms] {phase:?} {step}/{total}");
}
}
fn main() -> Result<()> {
let args: Vec<String> = env::args().collect();
let (input_path, output_path): (Option<PathBuf>, Option<PathBuf>) = match args.len() {
1 => (None, Some(default_output_path())),
2 => (Some(PathBuf::from(&args[1])), None),
_ => (Some(PathBuf::from(&args[1])), Some(PathBuf::from(&args[2]))),
};
let settings =
Settings::new().with_json(include_str!("../tests/fixtures/test_settings.json"))?;
let timer: Arc<Mutex<Instant>> = Arc::new(Mutex::new(Instant::now()));
let timer_cb = timer.clone();
let context = Context::new()
.with_settings(settings)?
.with_progress_callback(move |phase, step, total| {
let elapsed_ms = timer_cb.lock().unwrap().elapsed().as_secs_f64() * 1000.0;
print_progress(phase, step, total, elapsed_ms);
true
})
.into_shared();
// Spawn a thread that cancels the operation when the user presses Enter.
// If stdin is not a terminal (e.g. redirected from /dev/null) we ignore
// the immediate EOF and leave the operation to complete normally.
// Not available on WASM targets (no threads or stdin).
#[cfg(not(target_arch = "wasm32"))]
{
let cancel_ctx = context.clone();
thread::spawn(move || {
eprintln!("(press Enter to cancel)");
let mut buf = String::new();
if io::stdin().read_line(&mut buf).unwrap_or(0) > 0 {
eprintln!("Cancelling...");
cancel_ctx.cancel();
}
});
}
let result = if let Some(ref out_path) = output_path {
run_sign(&context, &timer, input_path.as_deref(), out_path)
} else {
run_read(&context, &timer, input_path.as_deref())
};
match result {
Ok(()) => {}
Err(ref e) if is_cancelled(e) => {
eprintln!("Operation cancelled.");
}
Err(e) => return Err(e),
}
Ok(())
}
fn run_read(
context: &Arc<Context>,
timer: &Arc<Mutex<Instant>>,
input: Option<&std::path::Path>,
) -> Result<()> {
eprintln!(
"Reading: {}",
input
.map(|p| p.display().to_string())
.unwrap_or_else(|| "CA.jpg (embedded)".into())
);
*timer.lock().unwrap() = Instant::now();
match input {
Some(path) => {
let format = format_for_path(path);
let mut f = BufReader::new(
std::fs::File::open(path).with_context(|| format!("opening {}", path.display()))?,
);
Reader::from_shared_context(context).with_stream(&format, &mut f)?;
}
None => {
let mut src = Cursor::new(SOURCE_IMAGE);
Reader::from_shared_context(context).with_stream(DEFAULT_FORMAT, &mut src)?;
}
}
eprintln!("Read complete.");
Ok(())
}
fn run_sign(
context: &Arc<Context>,
timer: &Arc<Mutex<Instant>>,
input: Option<&std::path::Path>,
output: &std::path::Path,
) -> Result<()> {
eprintln!(
"Signing: {} -> {}",
input
.map(|p| p.display().to_string())
.unwrap_or_else(|| "CA.jpg (embedded)".into()),
output.display()
);
if let Some(parent) = output.parent() {
fs::create_dir_all(parent)?;
}
let input_format = input
.map(format_for_path)
.unwrap_or_else(|| DEFAULT_FORMAT.to_string());
let mut builder = Builder::from_shared_context(context)
.with_definition(manifest_def("Progress Example", &input_format))?;
// Edit intent: the source asset is treated as the parent ingredient.
match input {
Some(path) => {
let format = format_for_path(path);
let mut f = BufReader::new(
std::fs::File::open(path).with_context(|| format!("opening {}", path.display()))?,
);
builder.add_ingredient_from_stream(
json!({ "title": path.file_name().unwrap_or_default().to_string_lossy(), "relationship": "parentOf" })
.to_string(),
&format,
&mut f,
)?;
}
None => {
let mut src = Cursor::new(SOURCE_IMAGE);
builder.add_ingredient_from_stream(
json!({ "title": "CA.jpg", "relationship": "parentOf" }).to_string(),
DEFAULT_FORMAT,
&mut src,
)?;
}
}
builder.set_intent(BuilderIntent::Edit);
*timer.lock().unwrap() = Instant::now();
// dest must be readable and seekable for in-place embedding.
let mut dest = OpenOptions::new()
.create(true)
.write(true)
.read(true)
.truncate(true)
.open(output)
.with_context(|| format!("creating {}", output.display()))?;
let sign_result = match input {
Some(path) => {
let format = format_for_path(path);
let mut source = BufReader::new(
std::fs::File::open(path).with_context(|| format!("opening {}", path.display()))?,
);
builder.save_to_stream(&format, &mut source, &mut dest)
}
None => {
let mut source = Cursor::new(SOURCE_IMAGE);
builder.save_to_stream(DEFAULT_FORMAT, &mut source, &mut dest)
}
};
if let Err(e) = sign_result {
drop(dest);
if let Err(remove_err) = fs::remove_file(output) {
eprintln!(
"Warning: could not remove partial output {}: {remove_err}",
output.display()
);
}
return Err(e.into());
}
eprintln!("Signed. Output: {}", output.display());
Ok(())
}
/// Returns true if the error (or any of its chain) is `Error::OperationCancelled`.
fn is_cancelled(e: &anyhow::Error) -> bool {
e.chain().any(|cause| {
cause
.downcast_ref::<Error>()
.map(|e| matches!(e, Error::OperationCancelled))
.unwrap_or(false)
})
}
#[cfg(test)]
mod tests {
use c2pa_macros::c2pa_test_async;
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
use wasm_bindgen_test::*;
use super::*;
#[c2pa_test_async]
async fn test_progress_sign() -> Result<()> {
let out = default_output_path();
run_sign(
&Context::new()
.with_settings(
Settings::new()
.with_json(include_str!("../tests/fixtures/test_settings.json"))?,
)?
.into_shared(),
&Arc::new(Mutex::new(Instant::now())),
None,
&out,
)
}
}