Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
23 total  XML / RSS feed 

Interactive LAME-ifyer to convert WAV or AIFF files to MP3

I wrote this as a bash script because I wanted to accomplish two things that I didn't find in any of the prebuilt GUI tools I've seen for OS X: First, I wanted to enable accurate ReplayGain, and second, I wanted to avoid clipping in the output, which requires iteratively encoding to home in on the best scale factor to avoid clipping while keeping the audio otherwise at its highest fidelity. I present what I call semilame   semiautomatic LAME:

#!/usr/local/bin/bash

SDIR=$PWD                       # Assumes xxx/Artist/Album hierarchy
TDIR=${PWD}/../../Out           # Assumes xxx/Out hierarchy
CUT="/usr/bin/cut"              # Set the correct path
LAME="/usr/local/bin/lame"      # Set the correct path

for fn in $(/bin/ls -1 *.aif *.aiff *.aifc 2>/dev/null); do
    clear   # Start with a clear screen, for goodness sake
    # First try to parse the filename; set other defaults appropriately
     FName="${fn/\.aifc/}"
     g_Track=$(echo $FName | $CUT - -f 1)
     g_Artist=${u_Artist:=$(echo $FName | $CUT - -f 2 | sed -e 's,_,\ ,g')}
     g_Title=$(echo $FName | $CUT - -f 3 | sed -e 's,_,\ ,g')
        # N.B. Expected format: TRACK÷Artist÷Title.aifc 
        #      with spaces converted to underscores.
        #      Album name is picked up from $PWD.
        #      Adjust to your needs!
     g_Album=${u_Album:=$(pwd | sed -E -e 's,(.*)/(.*)$,\2,')}
     g_Scale="1"
     if [[ $u_Qual ]]; then
        g_Qual=$u_Qual
        # Keep what we had from the last encoding
     else
        g_Qual="2"
     fi

     # Now prompt for user input for corrections
     BOLD="\033[1m"     # Set to "" if your term doesn't support bold
     NORM="\033[0m"     # Set to "" if your term doesn't support bold

     echo -e "${BOLD}FILENAME: ${NORM}====== « ${BOLD}$fn${NORM} »\n"
     echo -e "${BOLD}Track:           ${NORM}[${BOLD}${g_Track}${NORM}]: \c"
          read u_Track
     echo -e "${BOLD}Total Tracks:    ${NORM}[${BOLD}${g_Total}${NORM}]: \c"
          read u_Total
     echo -e "${BOLD}Artist:          ${NORM}[${BOLD}${g_Artist}${NORM}]: \c"
          read u_Artist
     echo -e "${BOLD}Title:           ${NORM}[${BOLD}${g_Title}${NORM}]: \c"
          read u_Title
     echo -e "${BOLD}Album:           ${NORM}[${BOLD}${g_Album}${NORM}]: \c"
          read u_Album
     echo -e "${BOLD}Year:            ${NORM}[${BOLD}${g_Year}${NORM}]: \c"
          read u_Year
     echo -e "${BOLD}Quality Level:   ${NORM}[${BOLD}${g_Qual}${NORM}]: \c"
        read u_Qual
         # Compare u_* values with g_* values
     if [[ -z $u_Track ]]; then
          u_Track=$g_Track
     fi
     if [[ -z $u_Total ]]; then
          u_Total=$g_Total
     elif [[ -z $g_Total ]]; then
          g_Total=$u_Total
     fi
     if [[ -z $u_Artist ]]; then
          u_Artist=$g_Artist
     fi
     if [[ -z $u_Title ]]; then
          u_Title=$g_Title
     fi
     if [[ -z $u_Album ]]; then
          u_Album=$g_Album
     fi
     if [[ -z $u_Year ]]; then
          u_Year=$g_Year
     elif [[ -z $g_Year ]]; then 
          g_Year=$u_Year
     fi
     if [[ -z $u_Qual ]]; then
          u_Qual=$g_Qual
     elif [[ -z $g_Qual ]]; then
          g_Qual=$u_Qual
     fi

     u_Scale=$g_Scale
     # while loop = each interation through the track
     while [[ $u_Scale != "0" ]]; do
          echo -e "${BOLD}Scale:           ${NORM}[${BOLD}${g_Scale}${NORM}]: \c"
              read u_Scale

          if [[ $u_Scale == "0" ]]; then
              g_Scale=1
              continue
          fi
          if [[ -z $u_Scale ]]; then
              u_Scale=$g_Scale
          elif [[ -z $g_Scale ]]; then
              g_Scale=$u_Scale
          fi
          g_Scale=$u_Scale
     
          # At this point, the real values should all be in the u_* variables. 
          # The g_* variables are simply placeholders for the next round 
          # through the loop, for the ones that aren't auto guessed.
     
          # Construct the lame command and run it. Adjust to your liking.
          LAMEOPTS="--replaygain-accurate
--clipdetect
--big-endian
--nohist
--id3v2-only
--vbr-new
-V
$u_Qual
-q
$u_Qual
--temporal-masking
1
--ignore-tag-errors
"

# LAMEARGS is constructed separately because it changes with each file.

         LAMEARGS="--tt
$u_Title
--tl
$u_Album"
        if [[ -n $u_Artist ]]; then
            LAMEARGS="$LAMEARGS
--ta
${u_Artist}"
        fi
         if [[ -n $u_Total ]]; then
              LAMEARGS="$LAMEARGS
--tn
${u_Track}/${u_Total}"
         else
              LAMEARGS="$LAMEARGS
--tn
${u_Track}"
         fi
         if [[ -n $u_Year ]]; then
              LAMEARGS="$LAMEARGS
--ty
$u_Year"
         fi
        if [[ -n $u_Scale ]]; then
            LAMEARGS="$LAMEARGS
--scale
$u_Scale"
        fi  
        OLDIFS=$IFS
        IFS='
'
        LAMELINE="${LAME}
${LAMEOPTS}
${LAMEARGS}
$fn
${TDIR}/${fn/aifc/mp3}"
        $LAMELINE
        
        # Restore IFS
        IFS=$OLDIFS
        
        echo -e "Set Scale to ${BOLD}0${NORM} to continue.\n"
    done 
done

Webdav upload utility

Command line utility to upload files to a webdav server.

Requires net_digest_auth.rb (snippet)

NB: Does not handle MKCOL, so the directory where you place the file must already exist.

Usage

$ ruby upload.rb cert.yml source destination


where cert.yml is a file of the form

username: USERNAME
password: PASSWORD


source is the path to the file to upload

destination is the URL of a directory on a webdav server to upload to.

# upload.rb
# Command line webdav upload script. Based off of 
# http://theexciter.com/articles/bingo

require 'net_digest_auth'
require 'yaml'
require 'uri'

abort("Usage: #{$0}    ") unless ARGV.size==3

auth = YAML.load_file(ARGV[0])
username = auth['username']
password = auth['password']

src = ARGV[1]
dst = ARGV[2]

if File.exists?(src)
  url = URI.parse(dst)
  Net::HTTP.start(url.host) do |http|
    res = http.put(url.request_uri, 'hello') # try putting something so
                                             # the server will return a
                                             # www-authenticate header
    req = Net::HTTP::Put.new("#{url.path}#{File.basename(src)}")
    req.digest_auth(username, password, res)
    response = http.request(req, File.open(src).read)
    puts response.code + " " + response.message
  end
else
  puts "No such file #{src.inspect}"
end

sort ip addresses


just alias this to something like ipsort
sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4

disable built-in isight

sudo chmod a-rx /System/Library/QuickTime/QuickTimeUSBVDCDigitizer.component/Con
tents/MacOS/QuickTimeUSBVDCDigitizer

and to restore:
sudo chmod a+rx /System/Library/QuickTime/QuickTimeUSBVDCDigitizer.component/Con
tents/MacOS/QuickTimeUSBVDCDigitizer

fast user switch from the command line

#!/bin/sh  
MENUEXTRAS="/System/Library/CoreServices/Menu Extras"
CGSESSION="$MENUEXTRAS/User.menu/Contents/Resources/CGSession"
if [[ -z $1 ]]; then
    "$CGSESSION" -suspend
else  
    USERID=`id -u $1`;
    if [[ -z $USERID ]]; then
        exit -1;
    fi;
    "$CGSESSION" -switchToUserID $USERID
fi;

power off the displays

this really powers off the displays, unlike other solutions which just put them to the dimmest setting
#!/bin/sh
  
MAGIC_NUMBER=107374183
PMSET=/usr/bin/pmset
GREP=/usr/bin/grep
AWK=/usr/bin/awk
SLEEP=/bin/sleep
    
$PMSET force -a displaysleep $MAGIC_NUMBER
$SLEEP 1
$PMSET force -a displaysleep `$PMSET -g | $GREP displaysleep | $AWK '{print $2}'`
$SLEEP 1

/etc/sysctl.conf

These are my settings for sysctl.conf
# Max number of incoming connections in queue
kern.ipc.somaxconn=512
# Maximum number of processes
kern.maxproc=2048
kern.maxprocperuid=1024
# Network buffers; 2K each; check current usage with `netstat -m`
kern.ipc.nmbclusters=2048
kern.ipc.maxsockets=2048
# Maximum segment size; other possible values are 1452 and 1460
net.inet.tcp.mssdflt=1440
# Window scaling is only necessary if buffers > 64K
net.inet.tcp.rfc1323=0
# Increase buffer sizes
kern.ipc.maxsockbuf=131070
net.inet.tcp.sendspace=32768
net.inet.tcp.recvspace=65535
net.inet.udp.recvspace=65535
net.inet.udp.maxdgram=57344
net.inet.raw.recvspace=65535
# Max number of ICMP "Unreachable" and also TCP RST packets per second
net.inet.icmp.icmplim=50
# Stop redirects
net.inet.icmp.drop_redirect=1
net.inet.icmp.log_redirect=1
net.inet.ip.redirect=0
# Stop source routing
net.inet.ip.sourceroute=0
net.inet.ip.accept_sourceroute=0
# Stop broadcast ECHO response
net.inet.icmp.bmcastecho=0
# Stop other broadcast probes
net.inet.icmp.maskrepl=0
# Cuts down on the number of tiny packets
net.inet.tcp.delayed_ack=1
# Turn off forwarding/routing
net.inet.ip.forwarding=0
# Defend against sequence number attacks
net.inet.tcp.strict_rfc1948=1
# Defend agains stealth simple port scans
net.inet.udp.blackhole=1
net.inet.tcp.blackhole=2
# Expire dead connections
net.inet.tcp.always_keepalive=1
net.inet.tcp.keepintvl: 1500
net.inet.tcp.keepinit: 3000
# Verbose firewall logging
net.inet.ip.fw.verbose=1
net.inet.ip.fw.verbose_limit=65535
# Prevent core dumps
kern.coredump=0

Create an ecrypted sparse disk image to store private stuff

hdiutil create Private -type SPARSE -encryption -fs HFS+J -volname Private

If you want it to be case-sensitive AND journaled, you can't simply use HFSX+J, you have to use HFSX, then issue this command:
diskutil enableJournal /Volumes/Private

Lock the keychain when idle

Lock the keychain when system sleeps or is idle for 10 minutes.
security set-keychain-settings -l -u -t 600

Boot in verbose mode

Watch startup messages.
sudo nvram boot-args=-v

check for file collisions when downgrading from HFSX to HFS

when converting from HFSX to HFS (case-sensitive to case insensitive), run this command to verify there will be no file collisions:
2>/dev/null find . -print | tr "[:upper:]" "[:lower:]"  | sort | uniq -d

repair disk permissions from the command line

sudo diskutil repairPermissions /

Download with cURL in a Loop Until Completed

From Entropy.ch:

Here’s a little terminal command I use to repeatedly attempt to download a file. This is useful if the transfer aborts frequently or if the server is busy:

The while/do/done loop keeps calling curl, with pauses of 10 seconds. curl will keep returning a failure exit code, which is what keeps the while loop going if inverted with the ! (logical not) operator. The -C - flag tells curl to continue at the last byte position.

while ! curl -C - -O 'http://download.parallels.com/GA/Parallels%20Desktop%203186%20Mac%20en.dmg'; 
do sleep 10; 
done

Zero data on a Linux disk

For use with VMWare when you don't run an X server:
cat /dev/zero > zero.dat ; sync ; sleep 1 ; sync ; rm -f zero.dat

How to ssh into Ubuntu on Parallels by hostname

this is something that strangely doesn't happen automatically on ubuntu
in Ubuntu, just add
send host-name "dapperbox";

to your /etc/dhcp3/dhclient.conf file

you might need to do a
sudo /etc/services/networking restart


On your Mac, you can now do
ssh username@dapperbox


instead of

ssh username@1.2.3.4

Generate DSA Keys

// generates SSH DSA keys in ~/.ssh/

ssh-keygen -d

rsync syntax

rsync -avz --eahfs --progress --delete /source-dir-without-trailing-slash /destination-dir-with-trailing-slash


// explanation of switches
// -a, archive mode, equivalent to -rlptgoD which does things like recurse through all the dirs, preserves times, etc.
// -v, verbose mode
// -z, compress - makes the copy go faster. doesn't actually compress into a zip file
// --eahfs - (could also use -E, I think)
// --progress - show copy status of each item
// --delete, delete files on destination that aren't on source (sync)

tar syntax

// tar:
tar -cvzf file.tar.gz inputfile1 inputfile2


// untar:
tar -xvzf file.tar.gz

Open Firefox in Safe Mode

// opens Firefox with extensions disabled. Also gives you the ability/option to reset Firefox to defaults.

// More info and code for other platforms can be found at http://kb.mozillazine.org/Safe_mode

/Applications/Firefox.app/Contents/MacOS/firefox -safe-mode

Enable svn+ssh remote logins

Installing Subversion for local use is general an easy install, but allowing remote access to your svn repository over SSH can be problomatic dependent upon your OS and the means taken to install.

For Darwinports and Fink on OS X the install location has to be added to users $PATHs, but there are extra steps outlined here for use of the svn+ssh means of access:

http://subversion.tigris.org/faq.html#ssh-svnserve-location

A much easier alternate is to sym link the svn binaries to a place on the default PATH (used by the SSH login):

#For Darwinports
ln -s /opt/local/bin/sv* /usr/bin/

#For Fink
ln -s /sw/bin/sv* /usr/bin/


This links all the binaries at once.

« Newer Snippets
Older Snippets »
23 total  XML / RSS feed