#!/bin/bash

# Script for Allen & Heath USB Record.

# This script first decreases the Disk Cache Write Latency from default of 30 seconds, to 10 seconds.
# This helps with old USB Keys, as the recorded wav cache is flushed more frequently in smaller chunks.
# This should help avoid buffer overruns, as pdflush will lock the buffers for less time.

# The Reocrd process also has in internal buffer which is set to max (256K).

# If buffer overruns persist, finding a way to increase this buffer beyound max may help.

# AB. 20/01/12

# Consts
DISK_BUFFER_CACHE_TUNABLE=/proc/sys/vm/dirty_expire_centisecs
DEFAULT_DISK_CACHE_WRITE_LATENCY=3000
RECORD_DISK_CACHE_WRITE_LATENCY=1000
RECORD_PRIORITY=-10
RECORD_BUFFER_SIZE=500000
PROGNAME=$(basename $0)

# This function is called from the trap below
function CleanUp  {
  # We kill our child process arecord, which is given to us by the env $!
  sudo kill $! > /dev/null 2>&1
  # Put the Disk write latency back to default
  sudo /bin/sh -c "echo -n $DEFAULT_DISK_CACHE_WRITE_LATENCY >> $DISK_BUFFER_CACHE_TUNABLE"
}

# Just incase anyone envokes this from a prompt.
function Usage {
  echo "Usage: $PROGNAME file" 1>&2
}

# This traps SIG_INT AKA Quit and redirects it to CleanUp.
# This is necessary as QProcess calling us will only kill our pid, not our children.
trap CleanUp 15

# Check the number of args, if wrong exit.
if [ $# != "1" ]; then
  Usage
  echo "Please provide a filename to record"
  exit -1
fi

# Providing the number of args were correct, lets alter the cache write latency
sudo sudo /bin/sh -c "echo -n $RECORD_DISK_CACHE_WRITE_LATENCY >> $DISK_BUFFER_CACHE_TUNABLE"
# Start the Record
sudo nice -n $RECORD_PRIORITY arecord -f dat --buffer-size=$RECORD_BUFFER_SIZE > $1 &
# The above process forks, we need to wait for it, ready to perform a cleanup of our child pid, if someone sends us a SIG_INT (3)
wait
