#!/usr/bin/python

# strip_wave_silence.py
#       --copyright--                   Copyright 2009 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       August 4, 2009          bar
#       May 27, 2012            bar     doxygen namespace
#       --eodstamps--
##      \file
#       \namespace              tzpython.strip_wave_silence
#
#
#       Strip silence from the ends of .wav files.
#
#       This script is stand-alone so that the unpack bug doesn't eat memory.
#
#       TODO:
#
#           tz_wave read/write of wav files causes a big memory leak. See it for info.
#
#

import  os

import  replace_file
import  tz_wave


def strip_beginning_silence(wavs, sw) :
    ss      = 400
    if  sw == 1 :
        ss  = 8

    se      = len(wavs[0])
    # print "ss", ss, se, [ wa[0] for wa in wavs ]

    for wa in wavs :
        for si in xrange(se) :
            if  abs(wa[si]) >= ss :
                se  = si
                break
            pass
        pass
    if  se :
        # print se
        wavs    = [ wa[se:] for wa in wavs ]

    return(wavs)


def strip_silence_from_ends(fn, ofile_name = None) :
    ( wavs, sr, sw )    = tz_wave.read_wave(fn)             # Note: there is a leak in struct.unpack() in python 2.5.2, (and others?) apparently. I could not "fix" it with del()'s and such. And a test program does not have the problem.

    ln      = len(wavs[0])

    wavs    = strip_beginning_silence(wavs, sw)
    for si in xrange(len(wavs)) :
        wavs[si].reverse()
    wavs    = strip_beginning_silence(wavs, sw)
    for si in xrange(len(wavs)) :
        wavs[si].reverse()

    ofile_name  = ofile_name or fn
    if  (ln    != len(wavs[0])) or (ofile_name != fn) :
        tfn     = ofile_name + ".tmp"
        tz_wave.write_wave(tfn, wavs, sr, sw)

        replace_file.replace_file(ofile_name, tfn, ofile_name + ".bak")

    pass



if  __name__ == '__main__' :

    import  sys

    import  TZCommandLineAtFile
    import  tzlib


    help_str    = """
%s (options)

    I strip silence from both ends of a .wav file - in place.

Options:

    --out       file_name       Set next output file name (default: next input file name)

    """ % ( os.path.basename(sys.argv[0]) )

    program_name    = sys.argv.pop(0)
    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)


    while True :
        oi  = tzlib.array_find(sys.argv, [ "--help", "-h", "-?", "/?", "/h" ] )
        if  oi < 0 :    break
        del sys.argv[oi]
        print help_str
        sys.exit(254)

    ofile_name  = None
    while sys.argv :
        fn  = sys.argv.pop(0)
        if  tzlib.array_find( [ fn ], [ "--out", "-o" ] ) >= 0 :
            ofile_name  = sys.argv.pop(0)
        else :
            strip_silence_from_ends(fn, ofile_name)
            ofile_name  = None
        pass
    pass


#
#
# eof
