forked from nathanbabcock/ffmpeg-sidecar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.rs
511 lines (439 loc) · 12.4 KB
/
test.rs
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::{sync::mpsc, thread, time::Duration};
use crate::{
command::{ffmpeg_is_installed, FfmpegCommand},
event::FfmpegEvent,
version::ffmpeg_version,
};
fn approx_eq(a: f32, b: f32, error: f32) -> bool {
(a - b).abs() < error
}
#[test]
fn test_installed() {
assert!(ffmpeg_is_installed());
}
#[test]
fn test_version() {
assert!(ffmpeg_version().is_ok());
}
#[test]
fn test_frame_count() {
let fps = 1;
let duration = 5;
let expected_frame_count = fps * duration;
let arg_string = format!(
"-f lavfi -i testsrc=duration={}:rate={} -f rawvideo -pix_fmt rgb24 -",
duration, fps
);
let iter = FfmpegCommand::new()
.args(arg_string.split(' '))
.spawn()
.unwrap()
.iter()
.unwrap();
let frame_count = iter
.filter(|event| matches!(event, FfmpegEvent::OutputFrame(_)))
.count();
assert_eq!(frame_count, expected_frame_count);
}
#[test]
fn test_output_format() {
FfmpegCommand::new()
.args("-f lavfi -i testsrc=duration=1:rate=1 -f rawvideo -pix_fmt rgb24 -".split(' '))
.spawn()
.unwrap()
.iter()
.unwrap()
.for_each(|event| {
if let FfmpegEvent::OutputFrame(frame) = event {
assert!(frame.pix_fmt == "rgb24");
assert!(frame.data.len() as u32 == frame.width * frame.height * 3);
}
});
}
/// Two inputs with the same parameters should produce the same output.
/// This might help catch off-by-one errors where buffers aren't perfectly
/// aligned with output frame boundaries.
#[test]
fn test_deterministic() {
let arg_str = "-f lavfi -i testsrc=duration=5:rate=1 -f rawvideo -pix_fmt rgb24 -";
let vec1: Vec<Vec<u8>> = FfmpegCommand::new()
.args(arg_str.split(' '))
.spawn()
.unwrap()
.iter()
.unwrap()
.filter_map(|event| match event {
FfmpegEvent::OutputFrame(frame) => Some(frame.data),
_ => None,
})
.collect();
let vec2: Vec<Vec<u8>> = FfmpegCommand::new()
.args(arg_str.split(' '))
.spawn()
.unwrap()
.iter()
.unwrap()
.filter_map(|event| match event {
FfmpegEvent::OutputFrame(frame) => Some(frame.data),
_ => None,
})
.collect();
assert!(vec1 == vec2)
}
#[test]
fn test_to_file() {
FfmpegCommand::new()
.args("-f lavfi -i testsrc=duration=5:rate=1 -y output/test.mp4".split(' '))
.spawn()
.unwrap()
.iter()
.unwrap()
.for_each(|event| match event {
FfmpegEvent::ParsedOutput(output) => assert!(!output.is_stdout()),
FfmpegEvent::OutputFrame(_) => {
panic!("Should not have received any frames when outputting to file.")
}
_ => {}
});
}
#[test]
fn test_progress() {
let mut progress_events = 0;
FfmpegCommand::new()
.args("-f lavfi -i testsrc=duration=5:rate=1 -y output/test.mp4".split(' '))
.spawn()
.unwrap()
.iter()
.unwrap()
.filter_progress()
.for_each(|_| progress_events += 1);
assert!(progress_events > 0);
}
#[test]
fn test_error() {
let errors = FfmpegCommand::new()
// output format and pix_fmt are deliberately missing, and cannot be inferred
.args("-f lavfi -i testsrc=duration=1:rate=1 -".split(' '))
.spawn()
.unwrap()
.iter()
.unwrap()
.filter_errors()
.count();
assert!(errors > 0);
}
#[test]
fn test_chunks() {
let mut chunks = 0;
let mut frames = 0;
FfmpegCommand::new()
.testsrc()
.codec_video("libx264")
.format("h264")
.pipe_stdout()
.spawn()
.unwrap()
.iter()
.unwrap()
.for_each(|e| match e {
FfmpegEvent::OutputChunk(_) => chunks += 1,
FfmpegEvent::OutputFrame(_) => frames += 1,
_ => {}
});
assert!(chunks > 0);
}
#[test]
fn test_chunks_with_audio() {
let mut chunks = 0;
let mut frames = 0;
FfmpegCommand::new()
.testsrc()
.args("-f lavfi -i sine=frequency=1000 -shortest".split(' '))
.codec_video("libx264")
.format("mpegts")
.pipe_stdout()
.spawn()
.unwrap()
.iter()
.unwrap()
.for_each(|e| match e {
FfmpegEvent::OutputChunk(_) => chunks += 1,
FfmpegEvent::OutputFrame(_) => frames += 1,
_ => {}
});
assert!(chunks > 0);
}
#[test]
fn test_duration() {
// Prepare the input file.
// TODO construct this in-memory instead of writing to disk.
FfmpegCommand::new()
.args("-f lavfi -i testsrc=duration=5:rate=1 -y output/test_duration.mp4".split(' '))
.spawn()
.unwrap()
.iter()
.unwrap()
.count();
let mut duration_received = false;
FfmpegCommand::new()
.input("output/test_duration.mp4")
.format("mpegts")
.pipe_stdout()
.spawn()
.unwrap()
.iter()
.unwrap()
.for_each(|e| {
if let FfmpegEvent::ParsedDuration(duration) = e {
match duration_received {
false => {
assert!(duration.duration == 5.0);
duration_received = true
}
true => panic!("Received multiple duration events."),
}
}
});
assert!(duration_received);
}
#[test]
fn test_metadata_duration() {
// Prepare the input file.
// TODO construct this in-memory instead of writing to disk.
FfmpegCommand::new()
.args("-f lavfi -i testsrc=duration=5:rate=1 -y output/test_metadata_duration.mp4".split(' '))
.spawn()
.unwrap()
.iter()
.unwrap()
.count();
let mut child = FfmpegCommand::new()
.input("output/test_metadata_duration.mp4")
.format("mpegts")
.pipe_stdout()
.spawn()
.unwrap();
let metadata = child.iter().unwrap().collect_metadata().unwrap();
child.kill().unwrap();
assert!(metadata.duration() == Some(5.0));
}
#[test]
fn test_kill_before_iter() {
let mut child = FfmpegCommand::new().testsrc().rawvideo().spawn().unwrap();
child.kill().unwrap();
let vec: Vec<FfmpegEvent> = child.iter().unwrap().collect();
assert!(vec.len() == 1);
assert!(vec[0] == FfmpegEvent::LogEOF);
}
#[test]
fn test_kill_after_iter() {
let mut child = FfmpegCommand::new().testsrc().rawvideo().spawn().unwrap();
let mut iter = child.iter().unwrap();
assert!(iter.next().is_some());
child.kill().unwrap();
child.as_inner_mut().wait().unwrap();
let count = iter
.filter(|e| matches!(e, FfmpegEvent::Progress(_)))
.count();
assert!(count <= 1);
}
#[test]
fn test_quit() {
let mut child = FfmpegCommand::new().testsrc().rawvideo().spawn().unwrap();
child.quit().unwrap();
let count = child.iter().unwrap().filter_progress().count();
assert!(count <= 1);
}
#[test]
fn test_frame_timestamp() {
let mut last_timestamp: Option<f32> = None;
FfmpegCommand::new()
.format("lavfi")
.input("testsrc=duration=1:rate=10")
.rawvideo()
.spawn()
.unwrap()
.iter()
.unwrap()
.filter_frames()
.for_each(|frame| {
match last_timestamp {
None => assert!(frame.timestamp == 0.0),
Some(last_timestamp) => assert!(approx_eq(frame.timestamp, last_timestamp + 0.1, 0.001)),
}
last_timestamp = Some(frame.timestamp);
});
assert!(approx_eq(last_timestamp.unwrap(), 0.9, 0.001));
}
#[test]
fn test_filter_complex() {
let num_frames = FfmpegCommand::new()
.format("lavfi")
.input("testsrc=duration=1:rate=10")
.rawvideo()
.filter_complex("fps=5")
.spawn()
.unwrap()
.iter()
.unwrap()
.filter_frames()
.count();
assert!(num_frames == 5);
}
/// Should not hang prompting for user input on overwrite
/// https://github.com/nathanbabcock/ffmpeg-sidecar/issues/35
#[test]
fn test_overwrite_fallback() -> anyhow::Result<()> {
let output_path = "output/test_overwrite_fallback.jpg";
let timeout_ms = 1000;
let write_file_with_timeout = || {
let mut command = FfmpegCommand::new();
command.testsrc().frames(1).output(output_path);
spawn_with_timeout(&mut command, timeout_ms)
};
write_file_with_timeout()?;
let time1 = std::fs::metadata(output_path)?.modified()?;
write_file_with_timeout()?;
let time2 = std::fs::metadata(output_path)?.modified()?;
assert_eq!(time1, time2);
Ok(())
}
#[test]
fn test_overwrite_nostdin() -> anyhow::Result<()> {
let output_path = "output/test_overwrite_nostdin.jpg";
let write_file = || -> anyhow::Result<_> {
FfmpegCommand::new()
.arg("-nostdin")
.testsrc()
.frames(1)
.output(output_path)
.spawn()?
.wait()
.map_err(Into::into)
};
write_file()?;
let time1 = std::fs::metadata(output_path)?.modified()?;
write_file()?;
let time2 = std::fs::metadata(output_path)?.modified()?;
assert_eq!(time1, time2);
Ok(())
}
#[test]
fn test_overwrite() -> anyhow::Result<()> {
let output_path = "output/test_overwrite.jpg";
let write_file = || -> anyhow::Result<_> {
FfmpegCommand::new()
.overwrite()
.testsrc()
.frames(1)
.output(output_path)
.spawn()?
.wait()
.map_err(Into::into)
};
write_file()?;
let time1 = std::fs::metadata(output_path)?.modified()?;
write_file()?;
let time2 = std::fs::metadata(output_path)?.modified()?;
assert_ne!(time1, time2);
Ok(())
}
#[test]
fn test_no_overwrite() -> anyhow::Result<()> {
let output_path = "output/test_no_overwrite.jpg"; // same file, ok if it exists
let write_file = || -> anyhow::Result<_> {
FfmpegCommand::new()
.no_overwrite()
.testsrc()
.frames(1)
.output(output_path)
.spawn()?
.wait()
.map_err(Into::into)
};
write_file()?;
let time1 = std::fs::metadata(output_path)?.modified()?;
write_file()?;
let time2 = std::fs::metadata(output_path)?.modified()?;
assert_eq!(time1, time2);
Ok(())
}
#[test]
#[cfg(feature = "named_pipes")]
fn test_named_pipe() -> anyhow::Result<()> {
use crate::{event::LogLevel, named_pipes::NamedPipe, pipe_name};
use std::{io::Read, thread::JoinHandle};
let pipe_name = pipe_name!("test_pipe");
// Create FFmpeg command
let mut command = FfmpegCommand::new();
command
.overwrite()
.format("lavfi")
.input("testsrc=size=320x240:rate=1:duration=1")
.frames(1)
.format("rawvideo")
.pix_fmt("rgb24")
.output(pipe_name);
// Open the named pipe
let (sender, receiver) = mpsc::channel::<bool>();
let thread: JoinHandle<Result<(), anyhow::Error>> = thread::spawn(move || {
let mut named_pipe = NamedPipe::new(pipe_name)?;
let mut buffer = [0u8; 65536];
receiver.recv()?;
let mut total_bytes_read = 0;
loop {
match named_pipe.read(&mut buffer) {
Ok(bytes_read) => {
total_bytes_read += bytes_read;
if bytes_read == 0 {
break;
}
}
Err(err) => anyhow::bail!(err),
}
}
assert!(total_bytes_read == 320 * 240 * 3);
Ok(())
});
// Start the source process
let mut ready_signal_sent = false;
command.spawn()?.iter()?.for_each(|event| match event {
FfmpegEvent::Progress(e) if !ready_signal_sent => {
println!("Progress: {:?}", e);
sender.send(true).ok();
ready_signal_sent = true;
}
FfmpegEvent::Log(LogLevel::Warning | LogLevel::Error | LogLevel::Fatal, msg) => {
eprintln!("{msg}");
}
_ => {}
});
thread.join().unwrap()?;
Ok(())
}
/// Returns `Err` if the timeout thread finishes before the FFmpeg process
fn spawn_with_timeout(command: &mut FfmpegCommand, timeout: u64) -> anyhow::Result<()> {
let (sender, receiver) = mpsc::channel();
// Thread 1: Waits for 1000ms and sends a message
let timeout_sender = sender.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(timeout));
timeout_sender.send("timeout").ok();
});
// Thread 2: Consumes the FFmpeg events and sends a message
let mut ffmpeg_child = command.spawn()?;
let iter = ffmpeg_child.iter()?;
thread::spawn(move || {
iter.for_each(|_| {});
// Note: `.wait()` would not work here, because it closes `stdin` automatically
sender.send("ffmpeg").ok();
});
// Race the two threads
let finished_first = receiver.recv()?;
ffmpeg_child.kill()?;
match finished_first {
"timeout" => anyhow::bail!("Timeout thread expired before FFmpeg"),
"ffmpeg" => Ok(()),
_ => anyhow::bail!("Unknown message received"),
}
}