#!/bin/sh
# Cassette recorder for the library Mac (TAPES.md). In Terminal, with the approved capture folder:
#   sh ~/Downloads/Tape.sh check [FOLDER] [--listen 10]     what this Mac offers; changes nothing
#   sh ~/Downloads/Tape.sh record TAPE SIDE [FOLDER] [--side-minutes 45] [--keep-blank] [--dry-run]
#   sh ~/Downloads/Tape.sh stop [FOLDER]                    end the running recording from elsewhere
#   sh ~/Downloads/Tape.sh name TAPE SIDE [FOLDER]          file name for an Audacity export (clipboard)
#   sh ~/Downloads/Tape.sh finish FILE                      check an exported side and mark it for upload
# record writes TAPE-SIDE-YYYY-MM-DD.wav from the Sound > Input device with macOS's own
# AVFoundation recorder (osascript), stops when the side has ended (sustained silence after
# sound) or at a time limit, then writes NAME.ready.json as Mark-Finished.sh does. Control-C
# stops early and still finishes the side. Uses only perl, osascript and lsof from macOS 10.12
# onward: no installation, admin rights or changed settings. A blank side (nothing above
# -60 dB in its first 3 minutes) stops by itself and is removed, so checking side B is cheap.
if ! command -v perl >/dev/null 2>&1 || ! command -v osascript >/dev/null 2>&1; then
  echo 'This Mac lacks perl or osascript. Record in Audacity and use "Add completed files" instead.' >&2
  exit 1
fi
exec perl -x "$0" "$@"
#!perl
use strict;
use warnings;
use Cwd qw(abs_path);
use File::Basename qw(basename dirname);
use Getopt::Long qw(GetOptionsFromArray);
use POSIX qw(strftime floor);
use Time::HiRes qw(time sleep stat);

$| = 1;
my $LOGDIR = '.tape-log';    # hidden, so Mark-Finished.sh and the uploader skip it

sub usage {
    open(my $self, '<', $0) or die "$0: $!\n";
    my @lines = grep { /^# / } (<$self>)[1 .. 6];
    print STDERR map { s/^# //; $_ } @lines;
    exit 2;
}

sub clock {    # 1234.5 seconds -> "20:34"
    my $s = floor(shift);
    return sprintf('%d:%02d:%02d', $s / 3600, ($s / 60) % 60, $s % 60) if $s >= 3600;
    return sprintf('%d:%02d', $s / 60, $s % 60);
}

sub free_bytes {
    my $dir = shift;
    my @df = `/bin/df -k "$dir" 2>/dev/null`;
    return undef unless @df >= 2 && $df[-1] =~ /^\S.*?\s+\d+\s+\d+\s+(\d+)\s+\d+%/;
    return $1 * 1024;
}

sub folder_arg {
    my $folder = shift;
    $folder = '.' unless defined $folder;
    die "Not a folder: $folder\n" unless -d $folder;
    die "Cannot write in $folder\n" unless -w $folder;
    return abs_path($folder);
}

sub tape_name {
    my ($tape, $side) = @_;
    die "TAPE must be letters, digits or _ (up to 24), e.g. T0007\n"
      unless defined $tape && $tape =~ /^[A-Za-z0-9][A-Za-z0-9_]{0,23}$/;
    die "SIDE must be A or B\n" unless defined $side && $side =~ /^[AaBb]$/;
    return uc($tape) . '-' . uc($side) . '-' . strftime('%Y-%m-%d', localtime);
}

sub unused_path {    # FOLDER/NAME.wav, or NAME-take2.wav ... when a take already exists
    my ($folder, $name) = @_;
    my $path = "$folder/$name.wav";
    my $take = 1;
    $path = "$folder/$name-take" . ++$take . '.wav' while -e $path || -e "$path.ready.json";
    return $path;
}

# Walk the RIFF chunks; returns {channels, rate, bits, format, data, seconds} or dies with why.
sub wav_info {
    my $path = shift;
    open(my $in, '<:raw', $path) or die "Cannot read $path: $!\n";
    my $size = -s $in;
    read($in, my $head, 12) == 12 or die "Too short to be a WAV file\n";
    my ($riff, $riff_size, $wave) = unpack('a4 V a4', $head);
    die "Not a WAV file (no RIFF/WAVE header)\n" unless $riff eq 'RIFF' && $wave eq 'WAVE';
    my (%info, $pos);
    $pos = 12;
    while ($pos + 8 <= $size) {
        seek($in, $pos, 0);
        read($in, my $chunk, 8) == 8 or last;
        my ($id, $len) = unpack('a4 V', $chunk);
        if ($id eq 'fmt ') {
            read($in, my $fmt, 16) == 16 or die "Damaged fmt chunk\n";
            @info{qw(format channels rate bytes_per_second block bits)} = unpack('v v V V v v', $fmt);
        } elsif ($id eq 'data') {
            die "The recording was not closed properly (data size missing)\n" if $len == 0 || $len == 0xFFFFFFFF;
            die "The recording is shorter than its header says (" . ($size - $pos - 8) . " of $len bytes)\n"
              if $pos + 8 + $len > $size;
            $info{data} = $len;
            last;
        }
        $pos += 8 + $len + ($len % 2);
    }
    die "No audio format chunk\n" unless $info{rate} && $info{block};
    die "No audio data chunk\n" unless defined $info{data};
    die "Unexpected RIFF size; the file may be cut short\n" if $riff_size + 8 > $size + 1;
    $info{seconds} = $info{data} / $info{block} / $info{rate};
    return \%info;
}

sub open_by_anyone {    # 1 open, 0 closed, undef unknown
    my $path = shift;
    return undef unless -x '/usr/sbin/lsof';
    system('/usr/sbin/lsof', '-w', '-t', '--', $path);    # prints PIDs; exits 1 when none
    my $code = $? >> 8;
    return $? & 127 ? undef : $code == 0 ? 1 : $code == 1 ? 0 : undef;
}

sub mark_finished {    # same marker as Mark-Finished.sh: exact size and mtime in milliseconds
    my $path = shift;
    my @st = stat $path or die "Cannot stat $path: $!\n";
    my $marker = "$path.ready.json";
    open(my $out, '>', "$marker.tmp") or die "Cannot write $marker: $!\n";
    print $out '{"size":' . $st[7] . ',"modified":' . int($st[9] * 1000) . '}';
    close $out or die "Cannot write $marker: $!\n";
    rename "$marker.tmp", $marker or die "Cannot write $marker: $!\n";
}

sub jxa_file {
    my $js = join '', <DATA>;
    my $dir = $ENV{TMPDIR} || '/tmp';
    my $file = "$dir/tape-recorder-$$.js";
    open(my $out, '>', $file) or die "Cannot write $file: $!\n";
    print $out $js;
    close $out;
    return $file;
}

# The recorder is the embedded JXA script (or TAPE_RECORDER, a stand-in used by the tests).
# It runs in its own process group so Control-C reaches only this script, which then asks the
# recorder to stop through the stop file and lets it close the WAV properly.
sub start_recorder {
    my ($out, $stop, $rate, $bits, $channels, $max, $mode) = @_;
    my @cmd = $ENV{TAPE_RECORDER} ? ($ENV{TAPE_RECORDER}) : ('/usr/bin/osascript', '-l', 'JavaScript', jxa_file());
    my $pid = open(my $from, '-|');
    die "Cannot start the recorder: $!\n" unless defined $pid;
    if (!$pid) {
        setpgrp(0, 0);
        open(STDERR, '>&', \*STDOUT);
        exec(@cmd, $out, $stop, $rate, $bits, $channels, $max, $mode || 'record') or exit 127;
    }
    return ($pid, $from);
}

sub cleanup_jxa { unlink "@{[$ENV{TMPDIR} || '/tmp']}/tape-recorder-$$.js" }

sub cmd_check {
    my @args = @_;
    my $listen = 0;
    GetOptionsFromArray(\@args, 'listen=i' => \$listen) or usage();
    my $folder = folder_arg($args[0]);
    chomp(my $os = `/usr/bin/sw_vers -productVersion 2>/dev/null` || 'unknown');
    print "macOS $os, perl $^V\n";
    my $free = free_bytes($folder);
    printf "Folder %s: %.1f GiB free (a 45-minute side at 48 kHz/24-bit is about 0.8 GiB)\n",
      $folder, ($free || 0) / 1024**3;
    my $probe = "$folder/$LOGDIR-probe-$$.wav";
    my ($pid, $from) = start_recorder($probe, "$probe.stop", 48000, 24, 2, 5, 'prepare');
    my $answer = join '', <$from>;
    close $from;
    unlink $probe;
    cleanup_jxa();
    print $answer =~ /^prepared/m ? "Built-in recorder (AVFoundation through osascript): ready\n"
                                  : "Built-in recorder: NOT available ($answer)\n";
    my ($device, $input);
    for (`/usr/sbin/system_profiler SPAudioDataType 2>/dev/null`) {
        $device = $1 if /^ {8}(\S.*):$/;
        $input = $device if /Default Input Device: Yes/;
    }
    print 'Sound > Input (what record uses): ', ($input || 'unknown'), "\n";
    for my $app ('/Applications/Audacity.app', "$ENV{HOME}/Applications/Audacity.app") {
        next unless -d $app;
        chomp(my $version = `/usr/bin/defaults read "$app/Contents/Info" CFBundleShortVersionString 2>/dev/null` || '?');
        my $module = (glob("$app/Contents/modules/mod-script-pipe*"))[0];
        my $cfg = "$ENV{HOME}/Library/Application Support/audacity/audacity.cfg";
        my $enabled = 'not set';
        if (open(my $in, '<', $cfg)) {
            local $/;
            my $text = <$in>;
            $enabled = $1 if $text =~ /^mod-script-pipe=(\d)/m;
        }
        my $pipe = -p "/tmp/audacity_script_pipe.to.$<" ? 'open' : 'not open';
        print "Audacity $version at $app; mod-script-pipe ", ($module ? 'bundled' : 'not bundled'),
          ", enabled=$enabled, pipe $pipe\n";
        my @macros = glob("'$ENV{HOME}/Library/Application Support/audacity/Macros/'*.txt");
        print '  Audacity macros: ', (@macros ? join(', ', map { basename($_, '.txt') } @macros) : 'none'), "\n";
    }
    if ($listen > 0) {
        print "Listening for $listen seconds (nothing is kept)...\n";
        my ($pid, $from) = start_recorder($probe, "$probe.stop", 48000, 24, 2, $listen, 'record');
        my ($avg, $peak) = (-160, -160);
        while (my $line = <$from>) {
            if ($line =~ /^level\s+\S+\s+(\S+)\s+(\S+)/) {
                $avg = $1 if $1 > $avg;
                $peak = $2 if $2 > $peak;
            } elsif ($line =~ /^error/) { print $line }
        }
        close $from;
        unlink $probe, "$probe.stop";
        cleanup_jxa();
        printf "Loudest level %.1f dB, peak %.1f dB%s\n", $avg, $peak,
          $peak >= -0.5 ? ' - CLIPPING: lower the input level' : $avg < -50 ? ' - very quiet: is the deck playing into this input?' : '';
    }
    return 0;
}

sub cmd_record {
    my @args = @_;
    my %o = (rate => 48000, bits => 24, channels => 2, quiet => -60, silence => undef,
             wait => 3, max => undef, side => undef, dry => 0, reserve => 300, keep_blank => 0);
    GetOptionsFromArray(\@args, 'side-minutes=f' => \$o{side}, 'max-minutes=f' => \$o{max},
                        'silence-seconds=f' => \$o{silence}, 'quiet-db=f' => \$o{quiet},
                        'wait-minutes=f' => \$o{wait}, 'rate=i' => \$o{rate}, 'bits=i' => \$o{bits},
                        'channels=i' => \$o{channels}, 'reserve-mib=i' => \$o{reserve},
                        'keep-blank' => \$o{keep_blank}, 'dry-run' => \$o{dry}) or usage();
    my ($tape, $side, $folder) = @args;
    my $name = tape_name($tape, $side);
    $folder = folder_arg($folder);
    die "--bits must be 16 or 24\n" unless $o{bits} == 16 || $o{bits} == 24;
    die "--channels must be 1 or 2\n" unless $o{channels} == 1 || $o{channels} == 2;
    # With a known side length, silence counts only near its end, so a blank stretch mid-side
    # cannot end the recording early; without one, the silence must last three minutes.
    my $min = 0;
    if (defined $o{side}) {
        $min = $o{side} * 60 - 120;
        $min = 0 if $min < 0;
        $o{max} = $o{side} + 5 unless defined $o{max};
    }
    $o{silence} = defined $o{side} ? 60 : 180 unless defined $o{silence};
    $o{max} = 65 unless defined $o{max};
    die "--silence-seconds must be at least 5\n" if $o{silence} < 5;
    die "--max-minutes must be more than 0\n" unless $o{max} > 0;
    my $max = $o{max} * 60;
    my $path = unused_path($folder, $name);
    my $file = basename($path);
    my $rate_bytes = $o{rate} * $o{bits} / 8 * $o{channels};
    my $free = free_bytes($folder);
    my @plan = (
        "Recording $file in $folder",
        sprintf('%d Hz, %d-bit, %s WAV from the Sound > Input device (%.0f MB per minute)',
                $o{rate}, $o{bits}, $o{channels} == 2 ? 'stereo' : 'mono', $rate_bytes * 60 / 1e6),
        sprintf('Stops after %ds below %.0f dB once sound has been heard%s, or at %s.', $o{silence}, $o{quiet},
                $min ? ' and ' . clock($min) . ' has passed' : '', clock($max)),
        sprintf('Gives up if nothing is heard in %s; stops if free space falls under %d MiB.', clock($o{wait} * 60), $o{reserve}),
    );
    print "$_\n" for @plan;
    if (defined $free) {
        printf "Free space: %.1f GiB; this side needs up to %.1f GiB.\n", $free / 1024**3, $rate_bytes * $max / 1024**3;
        print "WARNING: not enough room for the whole time limit; uploads must clear space as it records.\n"
          if $free - $rate_bytes * $max < $o{reserve} * 1024**2;
    }
    if ($o{dry}) {
        print "Dry run: nothing recorded, nothing written.\n";
        return 0;
    }
    mkdir "$folder/$LOGDIR";
    my $stop = "$folder/$LOGDIR/" . basename($path, '.wav') . '.stop';
    unlink $stop;
    open(my $log, '>>', "$folder/$LOGDIR/" . basename($path, '.wav') . '.log') or die "Cannot write the log: $!\n";
    $log->autoflush(1);
    my $say = sub { my $line = strftime('%H:%M:%S ', localtime) . shift; print $log "$line\n"; print "$line\n" };
    $say->($_) for @plan;
    open(my $active, '>', "$folder/$LOGDIR/recording") or die "Cannot write in $folder/$LOGDIR: $!\n";
    print $active "$stop\n";
    close $active;

    my $ask_stop = sub {
        my $s;
        close $s if open($s, ">", $stop);
    };
    local $SIG{INT} = sub { $say->('Control-C: finishing this side'); $ask_stop->() };
    local $SIG{TERM} = $SIG{INT};
    local $SIG{HUP} = $SIG{INT};
    my ($pid, $from) = start_recorder($path, $stop, $o{rate}, $o{bits}, $o{channels}, $max);
    my ($t, $heard, $quiet_since, $last_status, $last_disk, $reason) = (0, 0, undef, -1e9, 0, 'stopped');
    my ($clips, $clip_until, $avg, $peak) = (0, -1, -160, -160);
    my ($loud_avg, $loud_peak) = (-160, -160);
    my $started = 0;
    while (defined(my $line = <$from>)) {
        if ($line =~ /^started/) {
            $started = 1;
            $say->('Recording. Start the tape now if it is not playing. Control-C ends this side early.');
        } elsif ($line =~ /^level\s+(\S+)\s+(\S+)\s+(\S+)/) {
            my $dt = $1 - $t;
            ($t, $avg, $peak) = ($1, $2, $3);
            $loud_avg = $avg if $avg > $loud_avg;
            $loud_peak = $peak if $peak > $loud_peak;
            if ($avg > $o{quiet}) {
                $heard += $dt;
                $quiet_since = undef;
            } else {
                $quiet_since = $t - $dt unless defined $quiet_since;
            }
            if ($peak >= -0.5) {
                if ($t > $clip_until) {
                    $clips++;
                    $say->('CLIPPING at ' . clock($t) . ' - lower the input level (or re-record this side)') if $clips <= 5;
                    $say->('More clipping; counting it quietly from here') if $clips == 6;
                }
                $clip_until = $t + 1;
            }
            next if -e $stop;
            if ($heard < 2 && $t >= $o{wait} * 60) {
                $reason = 'no sound';
                $say->('Nothing heard for ' . clock($t) . ': this side is blank, or the deck or Sound > Input is not playing. Stopping.');
                $ask_stop->();
            } elsif ($heard >= 2 && defined $quiet_since && $t - $quiet_since >= $o{silence} && $t >= $min) {
                $reason = 'end of side';
                $say->(sprintf('Silent since %s: the side has ended. Stopping.', clock($quiet_since)));
                $ask_stop->();
            }
            if (time - $last_disk >= 10) {
                $last_disk = time;
                my $left = free_bytes($folder);
                if (defined $left && $left < $o{reserve} * 1024**2) {
                    $reason = 'disk full';
                    $say->(sprintf('Only %.0f MiB free: stopping to protect the recording.', $left / 1024**2));
                    $ask_stop->();
                }
            }
            if ($t - $last_status >= 30) {
                $last_status = $t;
                my $bar = '#' x (($avg + 60) / 3 > 0 ? int(($avg + 60) / 3) : 0);
                $say->(sprintf('%s  level %5.1f dB  peak %5.1f dB  %-20s %s', clock($t), $avg, $peak, $bar,
                               $heard >= 2 ? (defined $quiet_since ? 'quiet ' . clock($t - $quiet_since) : 'sound') : 'waiting for sound'));
            }
        } elsif ($line =~ /^stopped\s+(\S+)\s+(\S+)/) {
            $t = $1 if $1 > $t;
            $reason = 'time limit' if $2 eq 'limit' && $reason eq 'stopped';
        } elsif ($line =~ /^error\s*(.*)/) {
            $say->("Recorder error: $1");
            $reason = 'error';
        } elsif ($line =~ /\S/) {
            print $log $line;
        }
    }
    close $from;
    cleanup_jxa();
    unlink $stop, "$folder/$LOGDIR/recording";
    if (!-e $path) {
        $say->('No recording was made' . ($started ? '' : ' (the recorder did not start: is another app using the input?)'));
        return 1;
    }
    my $info = eval { wav_info($path) };
    if (!$info) {
        $say->("$file is damaged: $@" . 'Keep it; do not mark it. Try: sh Tape.sh finish FILE after checking it in Audacity.');
        return 1;
    }
    $say->(sprintf('Stopped (%s) at %s: %s, %s, %.0f MB. Loudest %.1f dB, peak %.1f dB, %d clipping moment%s.',
                   $reason, clock($t), $file, clock($info->{seconds}), (-s $path) / 1e6, $loud_avg, $loud_peak,
                   $clips, $clips == 1 ? '' : 's'));
    my $again = sub { 'sh ~/Downloads/Tape.sh record ' . join(' ', @_) . " $folder" . (defined $o{side} ? " --side-minutes $o{side}" : '') };
    my $next_tape = $again->('NEXT_TAPE', 'A');
    # Most tapes are recorded on one side: a blank side leaves nothing behind, so checking
    # side B costs only the wait. Anything louder than tape hiss is kept for Aidan to judge.
    if ($reason eq 'no sound' && $loud_avg <= $o{quiet} && $loud_peak < -40 && !$o{keep_blank}) {
        unlink $path;
        $say->(sprintf('Side %s is blank (loudest %.1f dB, peak %.1f dB): removed the empty take; nothing uploads.',
                       uc($side), $loud_avg, $loud_peak));
        $say->(uc($side) eq 'A' ? 'If the tape is recorded on side B, flip it: ' . $again->(uc($tape), 'B')
                                : "Next tape: $next_tape");
        return 0;
    }
    if ($reason eq 'no sound' || $reason eq 'error') {
        if ($reason eq 'no sound') {
            $say->($o{keep_blank} && $loud_peak < -40 ? "Kept the blank take $file (--keep-blank); not marked for upload."
                   : "Not marked for upload: $file has only faint sound. Listen to it, then fix the input or record again.");
        }
        $say->("Not marked for upload. Check $file in Audacity before using it.") if $reason eq 'error';
        return 1;
    }
    mark_finished($path);
    $say->("Marked finished: $file. The uploader sends it; check it says Verified on server.");
    if (uc($side) eq 'A') {
        $say->('Side B: flip the tape and run: ' . $again->(uc($tape), 'B'));
        $say->('  (a blank side B stops after ' . clock($o{wait} * 60) . " and leaves nothing). Or next tape: $next_tape");
    } else {
        $say->("Next tape: $next_tape");
    }
    return 0;
}

sub cmd_stop {
    my $folder = folder_arg(shift);
    open(my $in, '<', "$folder/$LOGDIR/recording") or die "No recording is running in $folder\n";
    chomp(my $stop = <$in>);
    open(my $s, '>', $stop) or die "Cannot write $stop: $!\n";
    close $s;
    print "Asked the recording to stop; it finishes and marks the side within a second or two.\n";
    return 0;
}

sub cmd_name {
    my ($tape, $side, $folder) = @_;
    my $path = unused_path(folder_arg($folder), tape_name($tape, $side));
    my $base = basename($path, '.wav');
    if (open(my $clip, '|-', '/usr/bin/pbcopy')) { print $clip $base; close $clip }
    print "$path\n(name copied: paste it in Audacity's export or Timer Record dialog, WAV, 24-bit)\n";
    print "When the export is closed: sh ~/Downloads/Tape.sh finish '$path'\n";
    return 0;
}

sub cmd_finish {
    my $path = shift;
    die "Usage: sh Tape.sh finish FILE\n" unless defined $path && -f $path;
    my $file = basename($path);
    warn "Note: $file does not follow TAPE-SIDE-YYYY-MM-DD; the server makes listening copies only for that pattern.\n"
      unless $file =~ /^[A-Z0-9][A-Z0-9_]{0,23}-[AB]-\d{4}-\d\d-\d\d(?:-take\d+)?\.(?:wav|flac|aiff?)$/i;
    my $open = open_by_anyone($path);
    die "$file is still open in another program; finish the export first.\n" if $open;
    die "lsof could not tell whether $file is still being written; not marked.\n" unless defined $open;
    if ($file =~ /\.wav$/i) {
        my $info = eval { wav_info($path) } or die "$file is not a complete WAV: $@";
        printf "%s: %s, %d Hz, %d-bit, %d channel%s\n", $file, clock($info->{seconds}), $info->{rate},
          $info->{bits}, $info->{channels}, $info->{channels} == 1 ? '' : 's';
    } else {
        die "$file is empty\n" unless -s $path;
    }
    mark_finished($path);
    print "Marked finished: $file\n";
    return 0;
}

my $command = shift @ARGV;
usage() unless defined $command;
my %commands = (check => \&cmd_check, record => \&cmd_record, stop => \&cmd_stop, name => \&cmd_name, finish => \&cmd_finish);
usage() unless $commands{$command};
my $code = eval { $commands{$command}->(@ARGV) };
if (!defined $code) {
    print STDERR $@;
    exit 1;
}
exit $code;

__DATA__
// Recorder: AVAudioRecorder writing linear PCM WAV, with Apple's level meters.
// argv: OUT STOP_FILE RATE BITS CHANNELS MAX_SECONDS MODE(record|prepare)
ObjC.import('AVFoundation');
function say(line) { console.log(line); }
function run(argv) {
  var out = argv[0], stop = argv[1], rate = +argv[2], bits = +argv[3], channels = +argv[4];
  var max = +argv[5], mode = argv[6];
  var settings = $.NSMutableDictionary.alloc.init;
  settings.setObjectForKey($.NSNumber.numberWithUnsignedInt(1819304813), $.AVFormatIDKey);  // 'lpcm'
  settings.setObjectForKey($.NSNumber.numberWithDouble(rate), $.AVSampleRateKey);
  settings.setObjectForKey($.NSNumber.numberWithInt(channels), $.AVNumberOfChannelsKey);
  settings.setObjectForKey($.NSNumber.numberWithInt(bits), $.AVLinearPCMBitDepthKey);
  settings.setObjectForKey($.NSNumber.numberWithBool(false), $.AVLinearPCMIsFloatKey);
  settings.setObjectForKey($.NSNumber.numberWithBool(false), $.AVLinearPCMIsBigEndianKey);
  var error = Ref();
  var recorder = $.AVAudioRecorder.alloc.initWithURLSettingsError($.NSURL.fileURLWithPath(out), settings, error);
  if (recorder.isNil()) { say('error ' + ObjC.unwrap(error[0].localizedDescription)); return; }
  recorder.meteringEnabled = true;
  if (!recorder.prepareToRecord) { say('error could not prepare the recording file'); return; }
  if (mode === 'prepare') { recorder.deleteRecording; say('prepared'); return; }
  if (!recorder.recordForDuration(max)) { say('error could not start recording: is the input in use?'); return; }
  say('started');
  var files = $.NSFileManager.defaultManager, reason = 'limit', t = 0;
  while (true) {
    $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.25));
    if (!recorder.recording) break;
    if (files.fileExistsAtPath(stop)) { reason = 'stop'; break; }
    recorder.updateMeters;
    var avg = -160, peak = -160;
    for (var c = 0; c < channels; c++) {
      avg = Math.max(avg, recorder.averagePowerForChannel(c));
      peak = Math.max(peak, recorder.peakPowerForChannel(c));
    }
    t = recorder.currentTime;
    say('level ' + t.toFixed(2) + ' ' + avg.toFixed(1) + ' ' + peak.toFixed(1));
  }
  recorder.stop;
  say('stopped ' + t.toFixed(2) + ' ' + reason);
}
