#!/bin/bash

### Follow an in-progress recording and stuff it through eas-detect.
### Stop either when eas-detect returns (which it will only do if it
### detects an alert or a silence) or when the file stops growing.
### Returns the exit status of eas-detect.
###
### If the name of the input matches the regexp below, we'll supply
### different args to pcm-eas and thus to eas-detect.  The intent is
### to allow specifying different alpha and/or dB-limit values for
### different channels; this is particularly helpful for certain movie
### channels, which have quite legitimately had as much as 3.5 minutes
### of dead silence (e.g., over a closing credit roll) that is not in
### fact a reason to worry.  OTOH, for -most- channels, even 30 seconds
### of silence is almost certainly a malfunction, so we should both
### detect the malfunction (which might fix itself if we waited for
### 3.5 minutes or so), and we should do so expeditiously (so again
### we shouldn't wait many minutes to be sure).  This allows rescheduling
### to commence much earlier than if we always waited for the worst case
### seen legitimately on any channel at all.
###
### It could certainly be argued that a more-general mechanism would
### query the database for, e.g., whether this was a commercial-free
### channel, or whether a user-defined extra database row was set and,
### if so, to use the existence of that row corresponding to the chanid.
### The row could even specify additional filtering, or specify the new
### eas-detect args directly.  But I don't need that level of generality.
###
### Note that we make this determination here, and not farther down
### the call stack, because this is the last chance we have to know
### the actual name of the input file!  We ourselves call pcm-eas with
### an input of just "-", which gets propagated to pcm-quiet, pcm, and
### finally mplayer, which sees that "-" and reads from the stdin we're
### supplying via tail --follow below.  This means that no one farther
### down the stack can have any idea where the input is coming from,
### which is why it falls to us.
###
### We're currently assuming eas-detect defaults of -a = 0.003, -b = 24,
### which work well (and quickly) for the non-movie channels.

input=$1
log=$2

eas_regexp="^3(201|21[23])_|^1062_"	# Currently Sundance, IFC, TCM, or TCM on the old source.
filename="`basename $input`"
if [ "`echo $filename | grep -E $eas_regexp`" != "" ]; then
  eas_args="-a .0004 -b 30"	# Deliberately left undefined if not set here!
fi

file-being-written-p $input &

tail --pid=$! --follow --lines=+0 $input | pcm-eas - $log $eas_args

# End of file.
