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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use ::internal_prelude::works_everywhere::*;
extern crate threadpool;
use Context;
use Job;
use JsonResponse;
use ::ffi::*;
use std::sync::mpsc::channel;
#[derive(Copy,Clone, Debug)]
pub enum ConstraintMode {
Max,
Distort,
}
#[derive(Copy,Clone, Debug)]
pub enum ImageFormat {
Jpeg = 4,
Png = 2,
Png24 = 9,
}
impl FromStr for ImageFormat {
type Err = &'static str;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s {
"jpeg" | "jpg" => Ok(ImageFormat::Jpeg),
"png" => Ok(ImageFormat::Png),
"png24" => Ok(ImageFormat::Png24),
_ => Err("no match"),
}
}
}
impl FromStr for ConstraintMode {
type Err = &'static str;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s {
"max" => Ok(ConstraintMode::Max),
"distort" => Ok(ConstraintMode::Distort),
_ => Err("no match"),
}
}
}
#[derive(Copy,Clone, Debug)]
pub struct BoringCommands {
pub fit: ConstraintMode,
pub w: Option<i32>,
pub h: Option<i32>,
pub precise_scaling_ratio: f32,
pub luma_correct: bool,
pub jpeg_quality: i32,
pub format: ImageFormat,
pub sharpen: f32,
pub down_filter: Filter,
pub up_filter: Filter,
}
pub fn process_image_by_paths(input_path: PathBuf,
output_path: PathBuf,
commands: BoringCommands)
-> std::result::Result<(), String> {
process_image(commands,
|c: &Context| {
let input_io =
c.create_io_from_filename(input_path.as_path().as_os_str().to_str().unwrap(), ::IoDirection::In).unwrap();
let output_io = c.create_io_from_filename(output_path.as_path().as_os_str().to_str().unwrap(), ::IoDirection::Out).unwrap();
vec![IoResource {
io: input_io,
direction: IoDirection::In,
},
IoResource {
io: output_io,
direction: IoDirection::Out,
}]
},
|_, _| Ok(()))
}
pub struct BenchmarkOptions {
pub input_path: PathBuf,
pub commands: BoringCommands,
pub thread_count: usize,
pub run_count: usize,
}
#[derive(Debug, Clone)]
pub struct BenchmarkResult {
result: std::result::Result<(), String>,
wall_nanoseconds: i64,
}
#[derive(Debug, Clone)]
pub struct BenchmarkResults {
list: Vec<BenchmarkResult>,
wall_nanoseconds: i64,
threads: usize,
count: usize,
}
impl BenchmarkResults {
pub fn to_json_string(&self) -> String {
let mut list = Vec::new();
for i in &self.list {
let mut map = serde_json::Map::new();
map.insert(String::from("ns"),
serde_json::Value::Number(serde_json::Number::from(i.wall_nanoseconds)));
let ms_str = format!("{:?}ms",
time::Duration::nanoseconds(i.wall_nanoseconds)
.num_milliseconds());
map.insert(String::from("wall_ms"), serde_json::Value::String(ms_str));
list.push(serde_json::Value::Object(map));
}
let mut root = serde_json::Map::new();
root.insert("runs".to_owned(), serde_json::Value::Array(list));
root.insert("wall_ns".to_owned(), serde_json::Value::Number(serde_json::Number::from(self.wall_nanoseconds)));
let ms_str = format!("{:?}ms",
time::Duration::nanoseconds(self.wall_nanoseconds).num_milliseconds());
let avg_str = format!("{:?}ms",
time::Duration::nanoseconds(self.wall_nanoseconds /
(self.count as i64))
.num_milliseconds());
root.insert("wall_ms".to_owned(), serde_json::Value::String(ms_str));
root.insert("avg_ms".to_owned(), serde_json::Value::String(avg_str));
serde_json::to_string(&root).unwrap()
}
}
fn benchmark_op(cmds: BoringCommands, mem: *mut u8, len: usize) -> BenchmarkResult {
let begin_at = time::precise_time_ns();
let result = process_image(cmds,
|c: &Context| {
unsafe {
vec![IoResource {
io: c.create_io_from_slice(std::slice::from_raw_parts(mem, len)).unwrap(),
direction: IoDirection::In,
},
IoResource {
io: c.create_io_output_buffer().unwrap(),
direction: IoDirection::Out,
}]
}
},
|_, _| Ok(()));
let end_at = time::precise_time_ns();
BenchmarkResult {
result: result,
wall_nanoseconds: (end_at - begin_at) as i64,
}
}
pub fn benchmark(bench: BenchmarkOptions) -> std::result::Result<BenchmarkResults, String> {
let mut f = File::open(bench.input_path).unwrap();
let mut buffer = Vec::new();
f.read_to_end(&mut buffer).unwrap();
let len = buffer.len();
let mem = buffer.as_mut_ptr();
let cap = buffer.capacity();
mem::forget(buffer);
let pool = threadpool::ThreadPool::new(bench.thread_count);
let (tx, rx) = channel();
let begin_at = time::precise_time_ns();
for _ in 0..bench.run_count {
let tx = tx.clone();
let m = mem as i64;
let l = len;
let cmds = bench.commands;
pool.execute(move || {
tx.send(benchmark_op(cmds, m as *mut u8, l)).unwrap();
});
}
let mut res_list = Vec::new();
let result_iterator = rx.iter().take(bench.run_count as usize);
for i in result_iterator {
match i.result {
Ok(_) => {
res_list.push(i);
}
Err(e) => {
return Err(e);
}
}
}
let end_at = time::precise_time_ns();
unsafe {
let _ = Vec::from_raw_parts(mem, len, cap);
}
Ok(BenchmarkResults {
list: res_list,
wall_nanoseconds: (end_at - begin_at) as i64,
threads: bench.thread_count,
count: bench.run_count,
})
}
pub struct IoResource {
pub io: *mut ImageflowJobIo,
pub direction: IoDirection,
}
fn constrain(original_width: i32,
original_height: i32,
constrain: ConstraintMode,
constrain_w: Option<i32>,
constrain_h: Option<i32>)
-> (usize, usize) {
let natural_ratio = (original_width as f32) / (original_height as f32);
let final_w;
let final_h;
if constrain_h.is_none() && constrain_w.is_none() {
final_w = original_width as usize;
final_h = original_height as usize;
} else {
let w = match constrain_w {
Some(w) => w,
None => (constrain_h.unwrap() as f32 * natural_ratio).round() as i32,
};
let h = match constrain_h {
Some(h) => h,
None => (constrain_w.unwrap() as f32 / natural_ratio).round() as i32,
};
match constrain {
ConstraintMode::Max => {
if original_width > w || original_height > h {
let constraint_ratio = (w as f32) / (h as f32);
if constraint_ratio > natural_ratio {
final_h = h as usize;
final_w = (h as f32 * natural_ratio).round() as usize;
} else {
final_w = w as usize;
final_h = (w as f32 / natural_ratio).round() as usize;
}
} else {
final_w = original_width as usize;
final_h = original_height as usize;
}
}
ConstraintMode::Distort => {
final_h = h as usize;
final_w = w as usize;
}
};
}
(final_w, final_h)
}
#[test]
fn test_constraining() {
assert_eq!((100, 50),
constrain(200, 100, ConstraintMode::Max, Some(100), None));
assert_eq!((400, 200),
constrain(200, 100, ConstraintMode::Distort, Some(400), None));
}
pub fn create_framewise(original_width: i32,
original_height: i32,
commands: BoringCommands)
-> std::result::Result<(s::Framewise, (i32, i32)), String> {
let (final_w, final_h) = constrain(original_width,
original_height,
commands.fit,
commands.w,
commands.h);
let trigger_ratio = if 1.0f32 > commands.precise_scaling_ratio {
3.0f32
} else {
commands.precise_scaling_ratio
};
let pre_w = ((final_w as f32) * trigger_ratio).round() as i32;
let pre_h = ((final_h as f32) * trigger_ratio).round() as i32;
let encoder_preset = match commands.format {
ImageFormat::Jpeg => {
s::EncoderPreset::LibjpegTurbo { quality: Some(commands.jpeg_quality) }
}
ImageFormat::Png => {
s::EncoderPreset::Libpng {
zlib_compression: None,
matte: None,
depth: Some(s::PngBitDepth::Png32),
}
}
ImageFormat::Png24 => {
s::EncoderPreset::Libpng {
zlib_compression: None,
matte: Some(s::Color::Black),
depth: Some(s::PngBitDepth::Png24),
}
}
};
let steps = vec![s::Node::Decode {
io_id: 0,
commands:
Some(vec![s::DecoderCommand::JpegDownscaleHints(s::JpegIDCTDownscaleHints {
width: pre_w as i64,
height: pre_h as i64,
scale_luma_spatially: Some(commands.luma_correct),
gamma_correct_for_srgb_during_spatial_luma_scaling:
Some(commands.luma_correct),
})]),
},
s::Node::Resample2D {
w: final_w,
h: final_h,
down_filter: Some(commands.down_filter),
up_filter: Some(commands.up_filter),
hints: Some(s::ResampleHints {
sharpen_percent: Some(commands.sharpen),
prefer_1d_twice: None,
}),
},
s::Node::Encode {
io_id: 1,
preset: encoder_preset,
}];
Ok((s::Framewise::Steps(steps), (pre_w, pre_h)))
}
pub fn process_image<F, C, R>(commands: BoringCommands,
io_provider: F,
cleanup: C)
-> std::result::Result<R, String>
where F: Fn(&Context) -> Vec<IoResource>,
C: Fn(&Context, &Job) -> std::result::Result<R, String>
{
let context = Context::create().unwrap();
let result;
{
let mut job = context.create_job();
let inputs: Vec<IoResource> = io_provider(&context);
for (index, input) in inputs.iter().enumerate() {
let dir = input.direction;
let io = input.io;
unsafe {
job.add_io(io, index as i32, dir).unwrap();
}
}
let info_blob: JsonResponse =
job.message("v0.1/get_image_info", b"{\"io_id\": 0}").unwrap();
let info_response: s::Response001 =
serde_json::from_slice(info_blob.response_json.as_ref()).unwrap();
if !info_response.success {
panic!("get_image_info failed: {:?}", info_response);
}
let (image_width, image_height) = match info_response.data {
s::ResponsePayload::ImageInfo(info) => (info.image_width, info.image_height),
_ => panic!(""),
};
let (framewise, (pre_w, pre_h)) = create_framewise(image_width, image_height, commands)
.unwrap();
if pre_w < image_width && pre_h < image_height {
let send_hints = s::TellDecoder001 {
io_id: 0,
command: s::DecoderCommand::JpegDownscaleHints(s::JpegIDCTDownscaleHints {
height: pre_h as i64,
width: pre_w as i64,
scale_luma_spatially: Some(commands.luma_correct),
gamma_correct_for_srgb_during_spatial_luma_scaling: Some(commands.luma_correct),
}),
};
let send_hints_str = serde_json::to_string_pretty(&send_hints).unwrap();
job.message("v0.1/tell_decoder", send_hints_str.as_bytes()).unwrap().assert_ok();
}
let send_execute = s::Execute001 {
framewise: framewise,
graph_recording: None,
no_gamma_correction: Some(!commands.luma_correct),
};
let send_execute_str = serde_json::to_string_pretty(&send_execute).unwrap();
job.message("v0.1/execute", send_execute_str.as_bytes()).unwrap().assert_ok();
result = cleanup(&context, &*job);
}
context.destroy_allowing_panics();
result
}