vapoursynth 0.1.2

Safe Rust wrapper for VapourSynth and VSScript.
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
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
// This is a mostly drop-in reimplementation of vspipe.
// The main difference is what the errors look like.
#![allow(unused)]
#[macro_use]
extern crate failure;

use failure::{err_msg, Error, ResultExt};

#[cfg(all(feature = "vsscript-functions",
          any(feature = "vapoursynth-functions", feature = "gte-vsscript-api-32")))]
mod inner {
    #![cfg_attr(feature = "cargo-clippy", allow(cast_lossless))]
    #![cfg_attr(feature = "cargo-clippy", allow(mutex_atomic))]
    extern crate clap;
    extern crate num_rational;
    extern crate vapoursynth;

    use std::cmp;
    use std::collections::HashMap;
    use std::ffi::OsStr;
    use std::fmt::Debug;
    use std::fs::File;
    use std::io::{self, stdout, Stdout, Write};
    use std::sync::{Arc, Condvar, Mutex};
    use std::time::Instant;

    use self::clap::{App, Arg};
    use self::num_rational::Ratio;
    use self::vapoursynth::prelude::*;
    use super::*;

    enum OutputTarget {
        File(File),
        Stdout(Stdout),
        Empty,
    }

    struct OutputParameters {
        node: Node,
        alpha_node: Option<Node>,
        start_frame: usize,
        end_frame: usize,
        requests: usize,
        y4m: bool,
        progress: bool,
    }

    struct OutputState {
        output_target: OutputTarget,
        timecodes_file: Option<File>,
        error: Option<(usize, Error)>,
        reorder_map: HashMap<usize, (Option<Frame>, Option<Frame>)>,
        last_requested_frame: usize,
        next_output_frame: usize,
        current_timecode: Ratio<i64>,
        callbacks_fired: usize,
        callbacks_fired_alpha: usize,
        last_fps_report_time: Instant,
        last_fps_report_frames: usize,
        fps: Option<f64>,
    }

    struct SharedData {
        output_done_pair: (Mutex<bool>, Condvar),
        output_parameters: OutputParameters,
        output_state: Mutex<OutputState>,
    }

    impl Write for OutputTarget {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            match *self {
                OutputTarget::File(ref mut file) => file.write(buf),
                OutputTarget::Stdout(ref mut out) => out.write(buf),
                OutputTarget::Empty => Ok(buf.len()),
            }
        }

        fn flush(&mut self) -> io::Result<()> {
            match *self {
                OutputTarget::File(ref mut file) => file.flush(),
                OutputTarget::Stdout(ref mut out) => out.flush(),
                OutputTarget::Empty => Ok(()),
            }
        }
    }

    fn print_version() -> Result<(), Error> {
        let environment = Environment::new().context("Couldn't create the VSScript environment")?;
        let core = environment
            .get_core()
            .context("Couldn't create the VapourSynth core")?;
        print!("{}", core.info().version_string);

        Ok(())
    }

    // Parses the --arg arguments in form of key=value.
    fn parse_arg(arg: &str) -> Result<(&str, &str), Error> {
        arg.find('=')
            .map(|index| arg.split_at(index))
            .map(|(k, v)| (k, &v[1..]))
            .ok_or_else(|| format_err!("No value specified for argument: {}", arg))
    }

    // Returns "Variable" or the value of the property passed through a function.
    fn map_or_variable<T, F>(x: &Property<T>, f: F) -> String
    where
        T: Debug + Clone + Copy + Eq + PartialEq,
        F: FnOnce(&T) -> String,
    {
        match *x {
            Property::Variable => "Variable".to_owned(),
            Property::Constant(ref x) => f(x),
        }
    }

    fn print_info(writer: &mut Write, node: &Node, alpha: Option<&Node>) -> Result<(), Error> {
        let info = node.info();

        writeln!(
            writer,
            "Width: {}",
            map_or_variable(&info.resolution, |x| format!("{}", x.width))
        )?;
        writeln!(
            writer,
            "Height: {}",
            map_or_variable(&info.resolution, |x| format!("{}", x.height))
        )?;

        #[cfg(feature = "gte-vapoursynth-api-32")]
        writeln!(writer, "Frames: {}", info.num_frames)?;

        #[cfg(not(feature = "gte-vapoursynth-api-32"))]
        writeln!(
            writer,
            "Frames: {}",
            match info.num_frames {
                Property::Variable => "Unknown".to_owned(),
                Property::Constant(x) => format!("{}", x),
            }
        )?;

        writeln!(
            writer,
            "FPS: {}",
            map_or_variable(&info.framerate, |x| format!(
                "{}/{} ({:.3} fps)",
                x.numerator,
                x.denominator,
                x.numerator as f64 / x.denominator as f64
            ))
        )?;

        match info.format {
            Property::Variable => writeln!(writer, "Format Name: Variable")?,
            Property::Constant(f) => {
                writeln!(writer, "Format Name: {}", f.name())?;
                writeln!(writer, "Color Family: {}", f.color_family())?;
                writeln!(
                    writer,
                    "Alpha: {}",
                    if alpha.is_some() { "Yes" } else { "No" }
                )?;
                writeln!(writer, "Sample Type: {}", f.sample_type())?;
                writeln!(writer, "Bits: {}", f.bits_per_sample())?;
                writeln!(writer, "SubSampling W: {}", f.sub_sampling_w())?;
                writeln!(writer, "SubSampling H: {}", f.sub_sampling_h())?;
            }
        }

        Ok(())
    }

    fn print_y4m_header<W: Write>(writer: &mut W, node: &Node) -> Result<(), Error> {
        let info = node.info();

        if let Property::Constant(format) = info.format {
            write!(writer, "YUV4MPEG2 C")?;

            match format.color_family() {
                ColorFamily::Gray => {
                    write!(writer, "mono")?;
                    if format.bits_per_sample() > 8 {
                        write!(writer, "{}", format.bits_per_sample())?;
                    }
                }
                ColorFamily::YUV => {
                    write!(
                        writer,
                        "{}",
                        match (format.sub_sampling_w(), format.sub_sampling_h()) {
                            (1, 1) => "420",
                            (1, 0) => "422",
                            (0, 0) => "444",
                            (2, 2) => "410",
                            (2, 0) => "411",
                            (0, 1) => "440",
                            _ => bail!("No y4m identifier exists for the current format"),
                        }
                    )?;

                    if format.bits_per_sample() > 8 && format.sample_type() == SampleType::Integer {
                        write!(writer, "p{}", format.bits_per_sample())?;
                    } else if format.sample_type() == SampleType::Float {
                        write!(
                            writer,
                            "p{}",
                            match format.bits_per_sample() {
                                16 => "h",
                                32 => "s",
                                64 => "d",
                                _ => unreachable!(),
                            }
                        )?;
                    }
                }
                _ => bail!("No y4m identifier exists for the current format"),
            }

            if let Property::Constant(resolution) = info.resolution {
                write!(writer, " W{} H{}", resolution.width, resolution.height)?;
            } else {
                unreachable!();
            }

            if let Property::Constant(framerate) = info.framerate {
                write!(
                    writer,
                    " F{}:{}",
                    framerate.numerator, framerate.denominator
                )?;
            } else {
                unreachable!();
            }

            #[cfg(feature = "gte-vapoursynth-api-32")]
            let num_frames = info.num_frames;

            #[cfg(not(feature = "gte-vapoursynth-api-32"))]
            let num_frames = {
                if let Property::Constant(num_frames) = info.num_frames {
                    num_frames
                } else {
                    unreachable!();
                }
            };

            write!(writer, " Ip A0:0 XLENGTH={}\n", num_frames)?;

            Ok(())
        } else {
            unreachable!();
        }
    }

    // Checks if the frame is completed, that is, we have the frame and, if needed, its alpha part.
    fn is_completed(entry: &(Option<Frame>, Option<Frame>), have_alpha: bool) -> bool {
        entry.0.is_some() && (!have_alpha || entry.1.is_some())
    }

    fn print_frame<W: Write>(writer: &mut W, frame: &Frame) -> Result<(), Error> {
        const RGB_REMAP: [usize; 3] = [1, 2, 0];

        let format = frame.format();
        #[cfg_attr(feature = "cargo-clippy", allow(needless_range_loop))]
        for plane in 0..format.plane_count() {
            let plane = if format.color_family() == ColorFamily::RGB {
                RGB_REMAP[plane]
            } else {
                plane
            };

            if let Ok(data) = frame.data(plane) {
                writer.write_all(data)?;
            } else {
                for row in 0..frame.height(plane) {
                    writer.write_all(frame.data_row(plane, row))?;
                }
            }
        }

        Ok(())
    }

    fn print_frames<W: Write>(
        writer: &mut W,
        parameters: &OutputParameters,
        frame: &Frame,
        alpha_frame: Option<&Frame>,
    ) -> Result<(), Error> {
        if parameters.y4m {
            write!(writer, "FRAME\n").context("Couldn't output the frame header")?;
        }

        print_frame(writer, frame).context("Couldn't output the frame")?;
        if let Some(alpha_frame) = alpha_frame {
            print_frame(writer, alpha_frame).context("Couldn't output the alpha frame")?;
        }

        Ok(())
    }

    fn update_timecodes(frame: &Frame, state: &mut OutputState) -> Result<(), Error> {
        let props = frame.props();
        let duration_num = props
            .get_int("_DurationNum")
            .context("Couldn't get the duration numerator")?;
        let duration_den = props
            .get_int("_DurationDen")
            .context("Couldn't get the duration denominator")?;

        if duration_den == 0 {
            bail!("The duration denominator is zero");
        }

        state.current_timecode += Ratio::new(duration_num, duration_den);

        Ok(())
    }

    fn frame_done_callback(
        frame: Result<Frame, GetFrameError>,
        n: usize,
        _node: &Node,
        shared_data: &Arc<SharedData>,
        alpha: bool,
    ) {
        let parameters = &shared_data.output_parameters;
        let mut state = shared_data.output_state.lock().unwrap();

        // Increase the progress counter.
        if !alpha {
            state.callbacks_fired += 1;
            if parameters.alpha_node.is_none() {
                state.callbacks_fired_alpha += 1;
            }
        } else {
            state.callbacks_fired_alpha += 1;
        }

        // Figure out the FPS.
        if parameters.progress {
            let current = Instant::now();
            let elapsed = current.duration_since(state.last_fps_report_time);
            let elapsed_seconds = elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 * 1e-9;

            if elapsed.as_secs() > 10 {
                state.fps = Some(
                    (state.callbacks_fired - state.last_fps_report_frames) as f64 / elapsed_seconds,
                );
                state.last_fps_report_time = current;
                state.last_fps_report_frames = state.callbacks_fired;
            }
        }

        match frame {
            Err(error) => {
                if state.error.is_none() {
                    state.error = Some((
                        n,
                        err_msg(error.into_inner().to_string_lossy().into_owned()),
                    ))
                }
            }
            Ok(frame) => {
                // Store the frame in the reorder map.
                {
                    let entry = state.reorder_map.entry(n).or_insert((None, None));
                    if alpha {
                        entry.1 = Some(frame);
                    } else {
                        entry.0 = Some(frame);
                    }
                }

                // If we got both a frame and its alpha frame, request one more.
                if is_completed(&state.reorder_map[&n], parameters.alpha_node.is_some())
                    && state.last_requested_frame < parameters.end_frame
                    && state.error.is_none()
                {
                    let shared_data_2 = shared_data.clone();
                    parameters.node.get_frame_async(
                        state.last_requested_frame + 1,
                        move |frame, n, node| {
                            frame_done_callback(frame, n, &node, &shared_data_2, false)
                        },
                    );

                    if let Some(ref alpha_node) = parameters.alpha_node {
                        let shared_data_2 = shared_data.clone();
                        alpha_node.get_frame_async(
                            state.last_requested_frame + 1,
                            move |frame, n, node| {
                                frame_done_callback(frame, n, &node, &shared_data_2, true)
                            },
                        );
                    }

                    state.last_requested_frame += 1;
                }

                // Output all completed frames.
                while state
                    .reorder_map
                    .get(&state.next_output_frame)
                    .map(|entry| is_completed(entry, parameters.alpha_node.is_some()))
                    .unwrap_or(false)
                {
                    let next_output_frame = state.next_output_frame;
                    let (frame, alpha_frame) =
                        state.reorder_map.remove(&next_output_frame).unwrap();

                    let frame = frame.unwrap();
                    if state.error.is_none() {
                        if let Err(error) = print_frames(
                            &mut state.output_target,
                            parameters,
                            &frame,
                            alpha_frame.as_ref(),
                        ) {
                            state.error = Some((n, error));
                        }
                    }

                    if state.timecodes_file.is_some() && state.error.is_none() {
                        let timecode = (*state.current_timecode.numer() as f64 * 1000f64)
                            / *state.current_timecode.denom() as f64;
                        match writeln!(state.timecodes_file.as_mut().unwrap(), "{:.6}", timecode)
                            .context("Couldn't output the timecode")
                        {
                            Err(error) => state.error = Some((n, error.into())),
                            Ok(()) => if let Err(error) = update_timecodes(&frame, &mut state)
                                .context("Couldn't update the timecodes")
                            {
                                state.error = Some((n, error.into()));
                            },
                        }
                    }

                    state.next_output_frame += 1;
                }
            }
        }

        // Output the progress info.
        if parameters.progress {
            eprint!(
                "Frame: {}/{}",
                state.callbacks_fired,
                parameters.end_frame - parameters.start_frame + 1
            );

            if let Some(fps) = state.fps {
                eprint!(" ({:.2} fps)", fps);
            }

            eprint!("\r");
        }

        // if state.next_output_frame == parameters.end_frame + 1 {
        // This condition works with error handling:
        let frames_requested = state.last_requested_frame - parameters.start_frame + 1;
        if state.callbacks_fired == frames_requested
            && state.callbacks_fired_alpha == frames_requested
        {
            *shared_data.output_done_pair.0.lock().unwrap() = true;
            shared_data.output_done_pair.1.notify_one();
        }
    }

    fn output(
        mut output_target: OutputTarget,
        mut timecodes_file: Option<File>,
        parameters: OutputParameters,
    ) -> Result<(), Error> {
        // Print the y4m header.
        if parameters.y4m {
            if parameters.alpha_node.is_some() {
                bail!("Can't apply y4m headers to a clip with alpha");
            }

            print_y4m_header(&mut output_target, &parameters.node)
                .context("Couldn't write the y4m header")?;
        }

        // Print the timecodes header.
        if let Some(ref mut timecodes_file) = timecodes_file {
            writeln!(timecodes_file, "# timecode format v2")?;
        }

        let initial_requests = cmp::min(
            parameters.requests,
            parameters.end_frame - parameters.start_frame + 1,
        );

        let output_done_pair = (Mutex::new(false), Condvar::new());
        let output_state = Mutex::new(OutputState {
            output_target,
            timecodes_file,
            error: None,
            reorder_map: HashMap::new(),
            last_requested_frame: parameters.start_frame + initial_requests - 1,
            next_output_frame: 0,
            current_timecode: Ratio::from_integer(0),
            callbacks_fired: 0,
            callbacks_fired_alpha: 0,
            last_fps_report_time: Instant::now(),
            last_fps_report_frames: 0,
            fps: None,
        });
        let shared_data = Arc::new(SharedData {
            output_done_pair,
            output_parameters: parameters,
            output_state,
        });

        // Record the start time.
        let start_time = Instant::now();

        // Start off by requesting some frames.
        {
            let parameters = &shared_data.output_parameters;
            for n in 0..initial_requests {
                let shared_data_2 = shared_data.clone();
                parameters.node.get_frame_async(n, move |frame, n, node| {
                    frame_done_callback(frame, n, &node, &shared_data_2, false)
                });

                if let Some(ref alpha_node) = parameters.alpha_node {
                    let shared_data_2 = shared_data.clone();
                    alpha_node.get_frame_async(n, move |frame, n, node| {
                        frame_done_callback(frame, n, &node, &shared_data_2, true)
                    });
                }
            }
        }

        let &(ref lock, ref cvar) = &shared_data.output_done_pair;
        let mut done = lock.lock().unwrap();
        while !*done {
            done = cvar.wait(done).unwrap();
        }

        let elapsed = start_time.elapsed();
        let elapsed_seconds = elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 * 1e-9;

        let mut state = shared_data.output_state.lock().unwrap();
        eprintln!(
            "Output {} frames in {:.2} seconds ({:.2} fps)",
            state.next_output_frame,
            elapsed_seconds,
            state.next_output_frame as f64 / elapsed_seconds
        );

        if let Some((n, ref msg)) = state.error {
            bail!("Failed to retrieve frame {} with error: {}", n, msg);
        }

        // Flush the output file.
        state
            .output_target
            .flush()
            .context("Failed to flush the output file")?;

        Ok(())
    }

    pub fn run() -> Result<(), Error> {
        let matches = App::new("vspipe-rs")
            .about("A Rust implementation of vspipe")
            .author("Ivan M. <yalterz@gmail.com>")
            .arg(
                Arg::with_name("arg")
                    .short("a")
                    .long("arg")
                    .takes_value(true)
                    .multiple(true)
                    .number_of_values(1)
                    .value_name("key=value")
                    .display_order(1)
                    .help("Argument to pass to the script environment")
                    .long_help(
                        "Argument to pass to the script environment, \
                         a key with this name and value (bytes typed) \
                         will be set in the globals dict",
                    ),
            )
            .arg(
                Arg::with_name("start")
                    .short("s")
                    .long("start")
                    .takes_value(true)
                    .value_name("N")
                    .display_order(2)
                    .help("First frame to output"),
            )
            .arg(
                Arg::with_name("end")
                    .short("e")
                    .long("end")
                    .takes_value(true)
                    .value_name("N")
                    .display_order(3)
                    .help("Last frame to output"),
            )
            .arg(
                Arg::with_name("outputindex")
                    .short("o")
                    .long("outputindex")
                    .takes_value(true)
                    .value_name("N")
                    .display_order(4)
                    .help("Output index"),
            )
            .arg(
                Arg::with_name("requests")
                    .short("r")
                    .long("requests")
                    .takes_value(true)
                    .value_name("N")
                    .display_order(5)
                    .help("Number of concurrent frame requests"),
            )
            .arg(
                Arg::with_name("y4m")
                    .short("y")
                    .long("y4m")
                    .help("Add YUV4MPEG headers to output"),
            )
            .arg(
                Arg::with_name("timecodes")
                    .short("t")
                    .long("timecodes")
                    .takes_value(true)
                    .value_name("FILE")
                    .display_order(6)
                    .help("Write timecodes v2 file"),
            )
            .arg(
                Arg::with_name("progress")
                    .short("p")
                    .long("progress")
                    .help("Print progress to stderr"),
            )
            .arg(
                Arg::with_name("info")
                    .short("i")
                    .long("info")
                    .help("Show video info and exit"),
            )
            .arg(
                Arg::with_name("version")
                    .short("v")
                    .long("version")
                    .help("Show version info and exit")
                    .conflicts_with_all(&[
                        "info",
                        "progress",
                        "y4m",
                        "arg",
                        "start",
                        "end",
                        "outputindex",
                        "requests",
                        "timecodes",
                        "script",
                        "outfile",
                    ]),
            )
            .arg(
                Arg::with_name("script")
                    .required_unless("version")
                    .index(1)
                    .help("Input .vpy file"),
            )
            .arg(
                Arg::with_name("outfile")
                    .required_unless("version")
                    .index(2)
                    .help("Output file")
                    .long_help(
                        "Output file, use hyphen `-` for stdout \
                         or dot `.` for suppressing any output",
                    ),
            )
            .get_matches();

        // Check --version.
        if matches.is_present("version") {
            return print_version();
        }

        // Open the output files.
        let mut output_target = match matches.value_of_os("outfile").unwrap() {
            x if x == OsStr::new(".") => OutputTarget::Empty,
            x if x == OsStr::new("-") => OutputTarget::Stdout(stdout()),
            path => {
                OutputTarget::File(File::create(path).context("Couldn't open the output file")?)
            }
        };

        let timecodes_file = match matches.value_of_os("timecodes") {
            Some(path) => {
                Some(File::create(path).context("Couldn't open the timecodes output file")?)
            }
            None => None,
        };

        // Create a new VSScript environment.
        let mut environment =
            Environment::new().context("Couldn't create the VSScript environment")?;

        // Parse and set the --arg arguments.
        if let Some(args) = matches.values_of("arg") {
            let mut args_map = OwnedMap::new(API::get().unwrap());

            for arg in args.map(parse_arg) {
                let (name, value) = arg.context("Couldn't parse an argument")?;
                args_map
                    .append_data(name, value.as_bytes())
                    .context("Couldn't append an argument value")?;
            }

            environment
                .set_variables(&args_map)
                .context("Couldn't set arguments")?;
        }

        // Start time more similar to vspipe's.
        let start_time = Instant::now();

        // Evaluate the script.
        environment
            .eval_file(
                matches.value_of("script").unwrap(),
                EvalFlags::SetWorkingDir,
            )
            .context("Script evaluation failed")?;

        // Get the output node.
        let output_index = matches
            .value_of("outputindex")
            .map(str::parse)
            .unwrap_or(Ok(0))
            .context("Couldn't convert the output index to an integer")?;

        #[cfg(feature = "gte-vsscript-api-31")]
        let (node, alpha_node) = environment.get_output(output_index).context(format!(
            "Couldn't get the output node at index {}",
            output_index
        ))?;
        #[cfg(not(feature = "gte-vsscript-api-31"))]
        let (node, alpha_node) = (
            environment.get_output(output_index).context(format!(
                "Couldn't get the output node at index {}",
                output_index
            ))?,
            None::<Node>,
        );

        if matches.is_present("info") {
            print_info(&mut output_target, &node, alpha_node.as_ref())
                .context("Couldn't print info to the output file")?;

            output_target
                .flush()
                .context("Couldn't flush the output file")?;
        } else {
            let num_frames = {
                let info = node.info();

                if let Property::Variable = info.format {
                    bail!("Cannot output clips with varying format");
                }
                if let Property::Variable = info.resolution {
                    bail!("Cannot output clips with varying dimensions");
                }
                if let Property::Variable = info.framerate {
                    bail!("Cannot output clips with varying framerate");
                }

                #[cfg(feature = "gte-vapoursynth-api-32")]
                let num_frames = info.num_frames;

                #[cfg(not(feature = "gte-vapoursynth-api-32"))]
                let num_frames = {
                    match info.num_frames {
                        Property::Variable => {
                            // TODO: make it possible?
                            bail!("Cannot output clips with unknown length");
                        }
                        Property::Constant(x) => x,
                    }
                };

                num_frames
            };

            let start_frame = matches
                .value_of("start")
                .map(str::parse::<i32>)
                .unwrap_or(Ok(0))
                .context("Couldn't convert the start frame to an integer")?;
            let end_frame = matches
                .value_of("end")
                .map(str::parse::<i32>)
                .unwrap_or_else(|| Ok(num_frames as i32 - 1))
                .context("Couldn't convert the end frame to an integer")?;

            // Check if the input start and end frames make sense.
            if start_frame < 0 || end_frame < start_frame || end_frame as usize >= num_frames {
                bail!(
                    "Invalid range of frames to output specified:\n\
                     first: {}\n\
                     last: {}\n\
                     clip length: {}\n\
                     frames to output: {}",
                    start_frame,
                    end_frame,
                    num_frames,
                    end_frame
                        .checked_sub(start_frame)
                        .and_then(|x| x.checked_add(1))
                        .map(|x| format!("{}", x))
                        .unwrap_or_else(|| "<overflow>".to_owned())
                );
            }

            let requests = {
                let requests = matches
                    .value_of("requests")
                    .map(str::parse::<usize>)
                    .unwrap_or(Ok(0))
                    .context("Couldn't convert the request count to an unsigned integer")?;

                if requests == 0 {
                    environment.get_core().unwrap().info().num_threads
                } else {
                    requests
                }
            };

            let y4m = matches.is_present("y4m");
            let progress = matches.is_present("progress");

            output(
                output_target,
                timecodes_file,
                OutputParameters {
                    node,
                    alpha_node,
                    start_frame: start_frame as usize,
                    end_frame: end_frame as usize,
                    requests,
                    y4m,
                    progress,
                },
            ).context("Couldn't output the frames")?;

            // This is still not a very valid comparison since vspipe does all argument validation
            // before it starts the time.
            let elapsed = start_time.elapsed();
            let elapsed_seconds = elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 * 1e-9;
            eprintln!("vspipe time: {:.2} seconds", elapsed_seconds);
        }

        Ok(())
    }
}

#[cfg(not(all(feature = "vsscript-functions",
              any(feature = "vapoursynth-functions", feature = "gte-vsscript-api-32"))))]
mod inner {
    use super::*;

    pub fn run() -> Result<(), Error> {
        bail!(
            "This example requires the `vsscript-functions` and either `vapoursynth-functions` or \
             `vsscript-api-32` features."
        )
    }
}

fn main() {
    if let Err(err) = inner::run() {
        eprintln!("Error: {}", err.cause());

        for cause in err.causes().skip(1) {
            eprintln!("Caused by: {}", cause);
        }

        eprintln!("{}", err.backtrace());
    }
}