Never been to CodeSnippets 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!)

MPlayer on Mac OS X

# MPlayer OSX Extended, http://mplayerosx.sttz.ch

cd ~/Desktop

curl -L -O http://mplayerosx.sttz.ch/downloads/MPlayer-OSX-Extended_rev7.dmg

hdiutil mount ~/Desktop/MPlayer-OSX-Extended_rev7.dmg

# test
open '/Volumes/MPlayerOSX Extended/MPlayer OSX Extended.app'
open -a '/Volumes/MPlayerOSX Extended/MPlayer OSX Extended.app' /Applications/iCal.app/Contents/Resources/alarmclock.mov


cd '/Volumes/MPlayerOSX Extended'
/usr/bin/sudo /bin/cp -R 'MPlayer OSX Extended.app' /Applications

hdiutil unmount '/Volumes/MPlayerOSX Extended'


ls -ld '/Applications/MPlayer OSX Extended.app'
ls -Rl '/Applications/MPlayer OSX Extended.app'
find '/Applications/MPlayer OSX Extended.app' -ls | nl


/usr/bin/sudo /bin/ln -is '/Applications/MPlayer OSX Extended.app/Contents/Resources/External_Binaries/mplayer.app/Contents/MacOS/mplayer' /usr/local/bin/mplayer

mplayer --help
mplayer -vo help
mplayer -pphelp


# cf. http://www.selflinux.org/selflinux/html/mplayer.html
mplayer -input keylist
mplayer -input cmdlist


ls -l /usr/local/bin/mplayer
otool -L /usr/local/bin/mplayer
otool -L /usr/local/bin/mplayer | egrep -i 'aa[lib]*'


# cf. Watch Videos in ASCII Art, http://oreilly.com/pub/h/4441
# (requires mplayer to be compiled with AAlib support)
# mplayer -vo aa video.avi

# http://www.apple.com/trailers/
mplayer -fs -monitoraspect 4:3 'http://movies.apple.com...mov'

# cf. http://www.linuxtutorialblog.com/post/tutorial-playing-around-with-mplayer
mplayer -fs -monitoraspect 4:3 -cache 8192 -cache-min 25 -channels 6 'http://movies.apple.com...mov'


# one-file-per-line format for playlist file
# cf. http://www.mplayerhq.hu/DOCS/man/en/mplayer.1.html

mplayer -playlist ~/Desktop/playlist -fs -monitoraspect 4:3 -really-quiet -fixed-vo -colorkey 0x000000



#-------------------------------------------------------------------------



# Unoffical MPlayer OS X SVN Builds, http://www.haque.net/software/mplayer/mplayerosx/builds/
# cf. http://www.mplayerhq.hu/design7/dload.html and http://www.mplayerhq.hu/DOCS/HTML/en/macos.html

export IFS=$' \t\n'

export PATH=/opt/local/bin:/opt/local/sbin:/opt/local/lib:/opt/local/include:\
/opt/local/man:/usr/local/bin:/usr/local/sbin:/usr/local/lib:/usr/local/include:/usr/bin:/bin:/usr/sbin:/sbin

alias sudo=/usr/bin/sudo


cd ~/Desktop
curl -L -O http://www.haque.net/software/mplayer/mplayerosx/builds/MPlayer-dev-SVN-latest.dmg
hdiutil mount ~/Desktop/MPlayer-dev-SVN-latest.dmg
cd /Volumes/MPlayer
/usr/bin/sudo /bin/cp -R 'MPlayer OSX.app' /Applications
hdiutil unmount /Volumes/MPlayer
cd


# test
open '/Applications/MPlayer OSX.app'
open '/Applications/MPlayer OSX.app' /Applications/iCal.app/Contents/Resources/alarmclock.mov


# create /usr/X11
# after installing MacPorts (includes X11)
# cf. http://trac.macports.org/wiki/InstallingMacPorts

sudo ln -s /usr/X11R6 /usr/X11


# freetype

sudo port install freetype
sudo mv /usr/X11R6/lib/libfreetype.6.dylib /usr/X11R6/lib/libfreetype.6.dylib.old
sudo ln -s /opt/local/lib/libfreetype.6.dylib /usr/X11R6/lib/libfreetype.6.dylib


# fontconfig

sudo port install fontconfig
sudo mv /usr/X11R6/lib/libfontconfig.1.dylib /usr/X11R6/lib/libfontconfig.1.dylib.old
sudo ln -s /opt/local/lib/libfontconfig.1.dylib /usr/X11R6/lib/libfontconfig.1.dylib


find /usr/X11R6/lib -name "*.old" -ls

# test
open '/Applications/MPlayer OSX.app'
open '/Applications/MPlayer OSX.app' /Applications/iCal.app/Contents/Resources/alarmclock.mov


sudo ln -is /Applications/MPlayer\ OSX.app/Contents/Resources/External_Binaries/mplayer.app/Contents/MacOS/mplayer /usr/local/bin/mplayer

mplayer --help



# undo ln commands above

sudo rm /usr/X11

sudo rm /usr/X11R6/lib/libfreetype.6.dylib
sudo mv /usr/X11R6/lib/libfreetype.6.dylib.old /usr/X11R6/lib/libfreetype.6.dylib

sudo rm /usr/X11R6/lib/libfontconfig.1.dylib
sudo mv /usr/X11R6/lib/libfontconfig.1.dylib.old /usr/X11R6/lib/libfontconfig.1.dylib

sudo rm /usr/local/bin/mplayer


#--------------------------------------------------------------


function playurl() {

   declare website="" mp4_url=""


#   mp4_url="$(/usr/bin/curl -s "$@" | /usr/bin/sed -E -n -e '/video_id=.*\&fmt_map=\&t=/{s/^.*(video_id=[^\&]+).*\&fmt_map=(\&t=[^\&]+).*$/http:\/\/www.youtube.com\/get_video\?fmt\=18\&\1\2/p;q;}')"

#   mp4_url="$(/usr/bin/curl -L -s --max-time 10 "${lines[${i}]}" | /usr/bin/egrep -o -m 1 'video_id=.+\&fmt_map=\&t=[^\&]+' | \
#            /usr/bin/sed -E -n -e 's/^(video_id=[^\&]+).*\&fmt_map=(\&t=[^\&]+)$/http:\/\/www.youtube.com\/get_video\?fmt\=18\&\1\2/p')"


   # for "printf ... 2>/dev/null | ..." see:  "Why does bash sometimes say 'Broken pipe'?",
   # http://www.unixguide.net/unix/bash/E2.shtml

   # video_id=...&fmt_map=...&t=...
   mp4_url="$(printf "%s\n" "${website}" 2>/dev/null | /usr/bin/egrep -o -m 1 'video_id=.+\&fmt_map=.*\&t=[^\&]+' | \
            /usr/bin/sed -E -n -e 's/^(video_id=[^\&]+).*\&fmt_map=.*(\&t=[^\&]+)$/http:\/\/www.youtube.com\/get_video\?fmt\=18\&\1\2/p')"

   # fmt_map=...&t=...&video_id=...
   if [[ -z "$mp4_url" ]]; then
      mp4_url="$(printf "%s\n" "${website}" 2>/dev/null | /usr/bin/egrep -o -m 1 'fmt_map=.+\&t=.+video_id=[^\&]+' | \
               /usr/bin/sed -E -n -e 's/^fmt_map=.+(\&t=[^\&]+).+(video_id=[^\&]+)$/http:\/\/www.youtube.com\/get_video\?fmt\=18\&\2\1/p')"
   fi


   /usr/local/bin/mplayer -fs -monitoraspect 4:3 -cache 8192 -cache-min 25 -channels 6 "$mp4_url"
   #/usr/local/bin/mplayer -fs -monitoraspect 4:3 -cache 8192 -cache-min 60 -channels 6 -af volnorm -pp 6 "$mp4_url"

   return 0
}


playurl 'http://www.youtube.com/watch?v=xxxxxxxxxxx'


#--------------------------------------------------------------


# scripting YouTube with Bash & mplayer

declare PLAYLIST="${HOME}/Movies/playlist.txt"
declare PLAYLIST_URLS_WEBSITE="${HOME}/Movies/playlisturls-website.txt"
declare PLAYLIST_URLS_FILE="${HOME}/Movies/playlisturls-file.txt"

declare website="" mp4_url=""


/bin/cat > "$PLAYLIST_URLS_WEBSITE" <<-'EOF'
http://www.youtube.com/watch?v=xxxxxxxxxx1
http://www.youtube.com/watch?v=xxxxxxxxxx2
http://www.youtube.com/watch?v=xxxxxxxxxx3
EOF


# cf. http://www.apple.com/trailers/

/bin/cat > "$PLAYLIST_URLS_FILE" <<-'EOF'
http://movies.apple.com...1_mov
http://movies.apple.com...2_mov
http://movies.apple.com...3_mov
EOF


open -e "$PLAYLIST_URLS_WEBSITE" "$PLAYLIST_URLS_FILE"


# read file into array
declare -a lines
OIFS=$IFS
IFS=$'\n'
lines=( $(< "$PLAYLIST_URLS_WEBSITE" ) )

#echo "${#lines[@]}"
#echo "${lines[@]}"


declare -a playurls

for ((i=0; i < "${#lines[@]}"; i++)); do 

#   mp4_url="$(/usr/bin/curl -L -s --max-time 10 "${lines[${i}]}" | /usr/bin/sed -E -n -e '/video_id=.*\&fmt_map=\&t=/{s/^.*(video_id=[^\&]+).*\&fmt_map=(\&t=[^\&]+).*$/http:\/\/www.youtube.com\/get_video\?fmt\=18\&\1\2/p;q;}')"

#   mp4_url="$(/usr/bin/curl -L -s --max-time 10 "${lines[${i}]}" | /usr/bin/egrep -o -m 1 'video_id=.+\&fmt_map=\&t=[^\&]+' | \
#            /usr/bin/sed -E -n -e 's/^(video_id=[^\&]+).*\&fmt_map=(\&t=[^\&]+)$/http:\/\/www.youtube.com\/get_video\?fmt\=18\&\1\2/p')"


   website="$(/usr/bin/curl -L -s --max-time 10 "${lines[${i}]}")"

   # video_id=...&fmt_map=...&t=...
   mp4_url="$(printf "%s" "${website}" 2>/dev/null | /usr/bin/egrep -o -m 1 'video_id=.+\&fmt_map=.*\&t=[^\&]+' | \
            /usr/bin/sed -E -n -e 's/^(video_id=[^\&]+).*\&fmt_map=.*(\&t=[^\&]+)$/http:\/\/www.youtube.com\/get_video\?fmt\=18\&\1\2/p')"

   # fmt_map=...&t=...&video_id=...
   if [[ -z "$mp4_url" ]]; then
      mp4_url="$(printf "%s" "${website}" 2>/dev/null | /usr/bin/egrep -o -m 1 'fmt_map=.+\&t=.+video_id=[^\&]+' | \
               /usr/bin/sed -E -n -e 's/^fmt_map=.+(\&t=[^\&]+).+(video_id=[^\&]+)$/http:\/\/www.youtube.com\/get_video\?fmt\=18\&\2\1/p')"
   fi


   playurls[${i}]="${mp4_url}"

done

#printf "%s\n" "${playurls[@]}"

# read file into array
declare -a playfiles
playfiles=( $(< "$PLAYLIST_URLS_FILE" ) )


IFS=$OIFS


printf "%s\n" "${playurls[@]}" > "$PLAYLIST"
printf "%s\n" "${playfiles[@]}" >> "$PLAYLIST"

open -e "$PLAYLIST"

/usr/local/bin/mplayer -playlist "$PLAYLIST" -fs -monitoraspect 4:3 -channels 6 -fixed-vo -colorkey 0x000000 -cache 8192 -cache-min 60

/usr/local/bin/mplayer -playlist "$PLAYLIST" -fs -monitoraspect 4:3 -really-quiet -channels 6 -fixed-vo -colorkey 0x000000 -cache 8192 -cache-min 30

/usr/local/bin/mplayer -playlist "$PLAYLIST" -fs -monitoraspect 4:3 -really-quiet -channels 6 -fixed-vo -colorkey 0x000000 -cache 8192 -cache-min 30 -af volnorm -pp 6


# no full-screen mode
/usr/local/bin/mplayer -playlist "$PLAYLIST" -monitoraspect 4:3 -channels 6 -fixed-vo -colorkey 0x000000 -cache 8192 -cache-min 60

# you may blacken your desktop background with:
# - doodim, http://www.lachoseinteractive.net/en/products/doodim/
# - MenuShade, http://www.nullriver.com/products
# - Cursorcerer, http://doomlaser.com/cursorcerer-hide-your-cursor-at-will/

Watch YouTube videos with QuickTime

Requires SIMBL and GreaseKit. Tested on Safari.
# YouTube in MP4 via QuickTime Plugin!
# http://www.joeyhagedorn.com/2008/04/16/youtube-in-mp4-via-quicktime-plugin

open -a Safari http://www.joeyhagedorn.com/media/downloads/youtubeQT.user.js


# Download YouTube Videos as MP4 Files
# http://googlesystem.blogspot.com/2008/04/download-youtube-videos-as-mp4-files.html

open -a Safari http://members.optusnet.com.au/lbramsay/youtube_mp4.user.js


1. Youtube QT (http://www.joeyhagedorn.com/media/downloads/youtubeQT.user.js)
// ==UserScript==
// @name           Youtube QT
// @namespace      userscripts.org
// @description    Plays the high-resolution YouTube video in an embedded Quicktime player 
// @version        0.1
// @include        http://youtube.com/watch?*
// @include        http://www.youtube.com/watch?*
// @include        http://*.youtube.com/watch?*
// ==/UserScript==
	
var video_id = null;
var video_hash = null;
var video_player = document.getElementById('movie_player');

if (video_player) {var flash_variables=video_player.attributes.getNamedItem('flashvars');
	if (flash_variables) {var flash_values=flash_variables.value;
		if (flash_values) {var video_id_match=flash_values.match(/video_id=([^(\&|$)]*)/);
			if (video_id_match!=null) video_id=video_id_match[1];
				var video_hash_match=flash_values.match(/t=([^(\&|$)]*)/);
				if (video_hash_match!=null) video_hash=video_hash_match[1];
		}
	}
}

if (video_id==null || video_hash==null) {var args=unsafeWindow.swfArgs;
	if (args) {video_id=args['video_id'];
		video_hash=args['t'];
	}
}

if (video_id==null || video_hash==null) return;

var yt_mp4_path = 'http://www.youtube.com/get_video?fmt=18&video_id='+video_id+'&t='+video_hash;
var div_embed=document.getElementById('watch-player-div');

if (div_embed) {div_embed.innerHTML='<embed src=\''+yt_mp4_path+'\' type="video/mp4" width=480 height=400 scale=\'aspect\'></embed>';
};


2. Download YouTube Videos as MP4 (http://members.optusnet.com.au/lbramsay/youtube_mp4.user.js)
// ==UserScript==
// @name           Download YouTube Videos as MP4
// @description    Adds an option to download YouTube videos.
// @namespace      http://googlesystem.blogspot.com
// @include        http://*.youtube.com/watch?*
// @include        http://youtube.com/watch?*
// @version        0.4
// ==/UserScript==

if ( navigator.userAgent.indexOf("AppleWebKit") != -1 ) {
      if (document.getElementById('download-youtube-video')) return;
    
      var video_id = null;
      var video_hash = null;
      var video_player = document.getElementById('movie_player');
      
      if (video_player) {
        var flash_variables = video_player.attributes.getNamedItem('flashvars');  
        if (flash_variables) {
          var flash_values = flash_variables.value;
          if (flash_values) {
            var video_id_match = flash_values.match(/video_id=([^(\&|$)]*)/);
            if (video_id_match!=null) video_id = video_id_match[1];
            var video_hash_match = flash_values.match(/t=([^(\&|$)]*)/);
            if (video_hash_match!=null) video_hash = video_hash_match[1];        
          }
        }
      }
      
      if (video_id==null || video_hash==null) {
        var args = window.swfArgs;
        if (args) {
          video_id = args['video_id'];
          video_hash = args['t'];  
        }
      }
      
      if (video_id==null || video_hash==null) return;
     
       var yt_mp4_path ='http://www.youtube.com/get_video?fmt=18&amp;video_id='+video_id+'&amp;t='+video_hash; 
       var div_embed = document.getElementById('watch-embed-div');
       if (div_embed) {
          div_embed.innerHTML = div_embed.innerHTML + '<br /> <span id=\'download-youtube-video\'> <a href=\''+yt_mp4_path+'\'>Download as MP4</a> '+ ((navigator.userAgent.indexOf('Safari')!=-1)?'(control-click and select <i>Download linked file as</i>)' : ('(right-click and select <i>Save '+ (navigator.appName=='Microsoft Internet Explorer'?'target':'link') +' as</i>)')) + '</span>';
      }

} else {
    (function () {
    
      if (document.getElementById('download-youtube-video')) return;
    
      var video_id = null;
      var video_hash = null;
      var video_player = document.getElementById('movie_player');
      
      if (video_player) {
        var flash_variables = video_player.attributes.getNamedItem('flashvars');  
        if (flash_variables) {
          var flash_values = flash_variables.value;
          if (flash_values) {
            var video_id_match = flash_values.match(/video_id=([^(\&|$)]*)/);
            if (video_id_match!=null) video_id = video_id_match[1];
            var video_hash_match = flash_values.match(/t=([^(\&|$)]*)/);
            if (video_hash_match!=null) video_hash = video_hash_match[1];        
          }
        }
      }
      
      if (video_id==null || video_hash==null) {
        var args = unsafeWindow.swfArgs;
        if (args) {
          video_id = args['video_id'];
          video_hash = args['t'];  
        }
      }
      
      if (video_id==null || video_hash==null) return;
     
       var yt_mp4_path ='http://www.youtube.com/get_video?fmt=18&amp;video_id='+video_id+'&amp;t='+video_hash; 
       var div_embed = document.getElementById('watch-embed-div');
       if (div_embed) {
          div_embed.innerHTML = div_embed.innerHTML + '<br /> <span id=\'download-youtube-video\'> <a href=\''+yt_mp4_path+'\'>Download as MP4</a> '+ ((navigator.userAgent.indexOf('Safari')!=-1)?'(control-click and select <i>Download linked file as</i>)' : ('(right-click and select <i>Save '+ (navigator.appName=='Microsoft Internet Explorer'?'target':'link') +' as</i>)')) + '</span>';
      }
      
    })();
}

Scrape YouTube thumbnails

// fun with mechanize
// more @ http://tramchase.com/scrape-myspace-youtube-torrents-for-fun-and-profit

agent = WWW::Mechanize.new
url = "http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed" # all time
page = agent.get(url)
# parse again w/ Hpcricot for some XML convenience
doc = Hpricot.parse(page.body)
# pp (doc/:entry) # like "search"; cool division overload
images = (doc/'media:thumbnail') # use strings instead of symbols for namespaces
FileUtils.mkdir_p 'youtube-images' # make the images dir
urls = images.map { |i| i[:url] }
urls.each_with_index do |file,index|
  puts "Saving image #{file}"
  agent.get(file).save_as("youtube-images/vid#{index}_#{File.basename file}")
end

Ruby: Conform Sequence Files to Final Cut Pro XML (BETA)


#! /usr/bin/env ruby

# Tested with Apple XML Interchange Format Vr. 4
# The program infers the location of the seq. files by using the offline MOV's name.
# 1. It first looks for subfolders in the location of the MOV file. If a subfolder is found to have the same name as
# the file itself, then the whole folder is treated as a mirror of itself.
# 2. If no matching folders are found, it will use the first non-matching folder it comes across, and then assume
# that the files contained within it are prefixed with a name similar to its own.
# 3. Offline MOVs must run at the same framerate as your editing timebase in FCP! No putting a 24fps MOV into a 30fps timeline!

require 'rubygems'
require 'hpricot'

class Range

def length
  to_a.size
end

end

class Fixnum

def pad(n=8)
  x = to_s
  pad = n - x.length
  x.insert(0,"#{'0'*pad}")
  x
end

end

class Editor

attr_reader :edl

def initialize(file)

  @masters = {}
  @edits = []
  @edl = []
  @doc = Hpricot(open(file))

  find_masters()
  breakdown()

end

def find_masters

@doc.search("//file/pathurl").each do |elem| 
  
  base = File.basename(elem.inner_html).gsub!(/\....$/,'')
  path = abspath(elem.inner_html)

  folders = `ls #{path}`.split("\n").delete_if { |f| f =~ /\..../ }

  if folders.index(base).nil?
    @masters[elem.parent.attributes['id']] = path + "/" + folders.first + "/" + base + "."
  else
    @masters[elem.parent.attributes['id']] = path + "/" + base + "/"
  end

end

end

def breakdown

  @edits = @doc.search("//clipitem/file").each do |elem| 

    cut = []
    file_id = elem.attributes['id']
    seq_location = @masters[file_id]
    places = getpad(seq_location)

    cutin = (elem.parent/"in").inner_html.to_i.pad(places)
    cutout = (elem.parent/"out").inner_html.to_i.pad(places)

    cut.push(Range.new(cutin.succ!,cutout)) # Compensate for off-by-one count in IN-point from XML
    cut.push(seq_location)

    @edl.push(cut)

  end

end

def getpad(path)

  if path =~ /\.$/
    f = `ls #{path}*`.split("\n")[1]
  else
    f = `ls #{path}`.split("\n")[1]
  end
  
  return f.match(/(.+\.)?(.+)\..../).to_a.last.length

end

def abspath(path)

  path.gsub!(/file:\/\/localhost/,'')
  path.gsub!(/%20/,'\ ')

  return File.dirname(path)

end

def print_edl
  @edl.each_with_index do |cut,i|
    puts i.pad(4).succ + "|" + cut[0].first + " -- " + cut[0].last + " ++ " + cut[1]
  end
end

end

class Manager

def initialize

  @subroll = '00'
  @maxslots = 0
  @current_directory = ""
  @current_frame = "00000001"

  refresh_current

end

def refresh_current
  @subroll.succ!
  @maxslots = FRAMES_PER_ROLL
  @current_directory = "#{TARGET}/#{BIGROLL}_#{@subroll}"
  `mkdir -p #{@current_directory}`
  puts "NEW ROLL! #{@current_directory}"
  sleep 5
end

def assemble(cut)

  seq, source = cut[0], cut[1]

  if seq.length+1 > @maxslots
    refresh_current()
  end

  puts "Copying files to temporary folder..."

  seq.each do |frame|
    if source =~ /\/$/
      `cp #{source}/*.#{frame}.dpx #{TEMP}/`
    else
      `cp #{source}#{frame}.dpx #{TEMP}/`
    end
  end

  Dir.chdir(TEMP)
  
  list = Dir.entries(TEMP).delete_if { |x| x =~ /^\./ }
  
  list.map! { |f| File.rename(f,f + "x") ; f + "x" }

  puts "Moving files into roll #{@subroll}"

  list.each do |f|

    `mv -i #{f} #{@current_directory}/`

    Dir.chdir(@current_directory)
    
    `mv -i #{f} #{BIGROLL}_#{@subroll}.#{@current_frame}.dpx`

    puts "Moved #{f}"

    Dir.chdir(TEMP)
    
    @current_frame.succ!
    @maxslots -= 1
    
  end

end

end

## SETUP ##

FRAMES_PER_ROLL = 80
BIGROLL = '03'
TEMP = "/Volumes/Offline/Cache/Rubycut"
TARGET = "/Volumes/Offline/REEL3RC2"
FCP_XML = "/Users/anak/Desktop/edl.xml"

## MAIN ##

editor = Editor.new(FCP_XML)

editor.print_edl

puts "Press ENTER to continue..."

gets

manager = Manager.new

editor.edl.each_with_index do |cut,i|
  
  puts "Assembling #{(i+1).pad(4)} | #{cut[0]} > #{cut[1]}"
  
  manager.assemble(cut)
  
end

puts "CONFORMED: #{FCP_XML}"