#!/usr/pkg/bin/python2.7
#----------------------------------------------------------------------------
# Project Name: MOSS
# File Name: fileinfo.py
# Description: Get file information.
#
# Created: 2004. 06. 24
# RCS-ID: $Id: fileinfo.py,v 1.13 2004/10/06 14:58:25 myunggoni Exp $
# Copyright: (c) 2004 by myunggoni
# License: GNU General Public License
# Author: Myung-Gon Park <myunggoni@users.kldp.net>
#----------------------------------------------------------------------------

import types
import random
import struct
import string
import sys
import os

try:
	import ogg.vorbis
	ogg_support = "yes"
except ImportError:
	ogg_support = "no"

bitrates = [
	[ # MPEG-2 & 2.5
		[0,32,48,56, 64, 80, 96,112,128,144,160,176,192,224,256,None], # Layer 1
		[0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160,None], # Layer 2
		[0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160,None]  # Layer 3
	],

	[ # MPEG-1
		[0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,None], # Layer 1
		[0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,None], # Layer 2
		[0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,None]  # Layer 3
	]
]

samplerates = [
	[ 11025, 12000,  8000, None], # MPEG-2.5
	[  None,  None,  None, None], # Reserved
	[ 22050, 24000, 16000, None], # MPEG-2
	[ 44100, 48000, 32000, None], # MPEG-1
]																												
																												  
modes = [ "stereo", "joint stereo", "dual channel", "mono" ]

mode_extensions = [
	[ "4-31", "8-31", "12-31", "16-31" ],
	[ "4-31", "8-31", "12-31", "16-31" ],
	[		  "",		"IS",		 "MS", "IS+MS" ]
]

emphases = [ "none", "50/15 ms", "reserved", "CCIT J.17" ]


MP3_HEADER_SEEK_LIMIT = 500000

try:
	string_types = [ types.StringType, types.UnicodeType ]
except AttributeError:				  # if no unicode support

	string_types = [ types.StringType ]

def lengthen(string, num_spaces):
	string = string[:num_spaces]
	return string + (' ' * (num_spaces - len(string)))

def strip_padding(s):
	while len(s) > 0 and s[-1] in string.whitespace + "\0":
		s = s[:-1]

	return s

class ID3:

	genres = [ 
		"Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", 
		"Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", 
		"Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", 
		"Alternative", "Ska", "Death Metal", "Pranks", "Soundtrack", 
		"Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", 
		"Trance", "Classical", "Instrumental", "Acid", "House", "Game", 
		"Sound Clip", "Gospel", "Noise", "Alt. Rock", "Bass", "Soul", 
		"Punk", "Space", "Meditative", "Instrum. Pop", "Instrum. Rock", 
		"Ethnic", "Gothic", "Darkwave", "Techno-Indust.", "Electronic", 
		"Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", 
		"Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", 
		"Native American", "Cabaret", "New Wave", "Psychadelic", "Rave", 
		"Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", 
		"Polka", "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", 
		"Folk/Rock", "National Folk", "Swing", "Fusion", "Bebob", "Latin", 
		"Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", 
		"Progress. Rock", "Psychadel. Rock", "Symphonic Rock", "Slow Rock", 
		"Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", 
		"Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", 
		"Booty Bass", "Primus", "Porn Groove", "Satire", "Slow Jam", 
		"Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", 
		"Rhythmic Soul", "Freestyle", "Duet", "Punk Rock", "Drum Solo", 
		"A Capella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass", 
		"Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", 
		"Polsk Punk", "Beat", "Christian Gangsta Rap", "Heavy Metal", 
		"Black Metal", "Crossover", "Contemporary Christian", "Christian Rock",
		"Merengue", "Salsa", "Thrash Metal", "Anime", "Jpop", "Synthpop" 
		]

	def __init__(self, file, name = 'unknown filename', as_tuple = 0):
		if type(file) in string_types:
			self.filename = file
			self.file = open(file, 'rb')
			self.can_reopen = 1
		elif hasattr(file, 'seek'): # assume it's an open file
			if name == 'unknown filename' and hasattr(file, 'name'):
				self.filename = file.name
			else:
				self.filename = name

			self.file = file
			self.can_reopen = 0
			
		self.d = {}
		self.as_tuple = as_tuple
		self.delete_tag = 0
		self.zero()
		self.modified = 0
		self.has_tag = 0
		self.had_tag = 0
		
		try:
			self.file.seek(-128, 2)

		except IOError, msg:
			self.modified = 0
			raise InvalidFileException

		try:
			if self.file.read(3) == 'TAG':
				self.has_tag = 1
				self.had_tag = 1
				self.title = self.file.read(30)
				self.artist = self.file.read(30)
				self.album = self.file.read(30)
				self.year = self.file.read(4)
				self.comment = self.file.read(30)

				if ord(self.comment[-2]) == 0 and ord(self.comment[-1]) != 0:
					self.track = ord(self.comment[-1])
					self.comment = self.comment[:-2]
				else:
					self.track = None

				self.genre = ord(self.file.read(1))

				self.title = strip_padding(self.title)
				self.artist = strip_padding(self.artist)
				self.album = strip_padding(self.album)
				self.year = strip_padding(self.year)
				self.comment = strip_padding(self.comment)

				self.setup_dict()

		except IOError, msg:
			self.modified = 0
			raise InvalidFileException
		
		self.modified = 0

	def setup_dict(self):
		self.d = {}
		
		if self.title: self.d["TITLE"] = self.tupleize(self.title)
		if self.artist: self.d["ARTIST"] = self.tupleize(self.artist)
		if self.album: self.d["ALBUM"] = self.tupleize(self.album)
		if self.year: self.d["YEAR"] = self.tupleize(self.year)
		if self.comment: self.d["COMMENT"] = self.tupleize(self.comment)
		if self.legal_genre(self.genre):
			self.d["GENRE"] = self.tupleize(self.genres[self.genre])
		else:
			self.d["GENRE"] = self.tupleize("Unknown Genre")
		
		if self.track: self.d["TRACKNUMBER"] = self.tupleize(str(self.track))

	def delete(self):
		self.zero()
		self.delete_tag = 1
		self.has_tag = 0

	def zero(self):
		self.title = ''
		self.artist = ''
		self.album = ''
		self.year = ''
		self.comment = ''
		self.track = None
		self.genre = 255 # 'unknown', not 'blues'
		self.setup_dict()
		
	def tupleize(self, s):
		if self.as_tuple and type(s) is not types.TupleType:
			return (s, )
		else:
			return s

	def find_genre(self, genre_to_find):
		i = 0
		find_me = string.lower(genre_to_find)

		for genre in self.genres:
			if string.lower(genre) == find_me:
				break
			i = i + 1

		if i == len(self.genres):
			return -1
		else:
			return i

	def legal_genre(self, genre):
		if type(genre) is types.IntType and 0 <= genre < len(self.genres):
			return 1
		else:
			return 0

	def write(self):
		if self.modified:
			try:
				# We see if we can re-open in r+ mode now, as we need to write
				if self.can_reopen:
					self.file = open(self.filename, 'r+b')

				if self.had_tag:
					self.file.seek(-128, 2)
				else:
					self.file.seek(0, 2) # a new tag is appended at the end

				if self.delete_tag and self.had_tag:
					self.file.truncate()
					self.had_tag = 0
				elif self.has_tag:
					go_on = 1
					
					if self.had_tag:
						if self.file.read(3) == "TAG":
							self.file.seek(-128, 2)
						else:
							# someone has changed the file in the mean time
							go_on = 0
							raise IOError("File has been modified, losing tag changes")
					if go_on:
						self.file.write('TAG')
						self.file.write(lengthen(self.title, 30))
						self.file.write(lengthen(self.artist, 30))
						self.file.write(lengthen(self.album, 30))
						self.file.write(lengthen(self.year, 4))

						comment = lengthen(self.comment, 30)

						if self.track < 0 or self.track > 255:
							self.track = None

						if self.track != None:
							comment = comment[:-2] + "\0" + chr(self.track)

						self.file.write(comment)

						if self.genre < 0 or self.genre > 255:
							self.genre = 255
						self.file.write(chr(self.genre))
						self.had_tag = 1
				self.file.flush()
			except IOError, msg:
				raise InvalidFileException
			else:
				self.modified = 0

	def as_dict(self):
		return self.d

	def items(self):
		return map(None, self.keys(), self.values())

	def keys(self):
		return self.d.keys()

	def values(self):
		if self.as_tuple:
			return map(lambda x: x[0], self.d.values())
		else:
			return self.d.values()

	def has_key(self, k):
		return self.d.has_key(k)

	def get(self, k, x = None):
		if self.d.has_key(k):
			return self.d[k]
		else:
			return x

	def __getitem__(self, k):
		return self.d[k]

	def __setitem__(self, k, v):
		key = k
		
		if not key in ['TITLE', 'ARTIST', 'ALBUM', 'YEAR', 'COMMENT',
					   'TRACKNUMBER', 'GENRE']:
			return
		
		if k == 'TRACKNUMBER':
			if type(v) is types.IntType:
				self.track = v
			else:
				self.track = string.atoi(v)
			self.d[k] = self.tupleize(str(v))
		elif k == 'GENRE':
			if type(v) is types.IntType:
				if self.legal_genre(v):
					self.genre = v
					self.d[k] = self.tupleize(self.genres[v])
				else:
					self.genre = v
					self.d[k] = self.tupleize("Unknown Genre")
			else:
				self.genre = self.find_genre(str(v))
			
				if self.genre == -1:
					print v, "not found"
					self.genre = 255
					self.d[k] = self.tupleize("Unknown Genre")
				else:
					print self.genre, v
					self.d[k] = self.tupleize(str(v))
		else:
			self.__dict__[string.lower(key)] = v
			self.d[k] = self.tupleize(v)
		self.__dict__['modified'] = 1
		self.__dict__['has_tag'] = 1

	def __del__(self):
		self.write()

	def __str__(self):
		if self.has_tag:
			if self.genre != None and self.genre >= 0 and \
				   self.genre < len(self.genres):
				genre = self.genres[self.genre]
			else:
				genre = 'Unknown'

			if self.track != None:
				track = str(self.track)
			else:
				track = 'Unknown'

			return "File   : %s\nTitle  : %-30.30s  Artist: %-30.30s\nAlbum  : %-30.30s  Track : %s  Year: %-4.4s\nComment: %-30.30s  Genre : %s (%i)" % (self.filename, self.title, self.artist, self.album, track, self.year, self.comment, genre, self.genre)
		else:
			return "%s: No ID3 tag." % self.filename

	# intercept setting of attributes to set self.modified
	def __setattr__(self, name, value):
		if name in ['title', 'artist', 'album', 'year', 'comment',
					'track', 'genre']:
			self.__dict__['modified'] = 1
			self.__dict__['has_tag'] = 1
			
			if name == 'track':
				self.__dict__['d']['TRACKNUMBER'] = self.tupleize(str(value))
			elif name == 'genre':
				if self.legal_genre(value):
					self.__dict__['d']['GENRE'] = self.tupleize(self.genres[value])
				else:
					self.__dict__['d']['GENRE'] = self.tupleize('Unknown Genre')
			else:
				self.__dict__['d'][string.upper(name)] = self.tupleize(value)
		self.__dict__[name] = value

class MPEG:
	def __init__(self, file, seeklimit = MP3_HEADER_SEEK_LIMIT, seekstart = 0):
		try:
			file = open(file, "rb")
		except IOError:
			raise InvalidFileException
		
		self.valid = 0

		file.seek(0, 2)
		self.filesize = file.tell()
		self.filesize2 = round(float(self.filesize / 1024 / 1024), 2)

		self.version = 0
		self.layer = 0
		self.protection = 0
		self.bitrate = 0
		self.is_vbr = 0
		self.samplerate = 0
		self.padding = 0
		self.private = 0
		self.mode = ""
		self.mode_extension = ""
		self.copyright = 0
		self.original = 0
		self.emphasis = ""
		self.length = 0
		self.length_minutes = 0
		self.length_seconds = 0

		test_pos = int(random.uniform(0.25,0.75) * self.filesize)

		offset, header = self.find_header(file, seeklimit = 4616, seekstart = test_pos, check_next_header = 2)
		
		if offset == -1 or header is None:
			raise InvalidFileException
			
		offset, header = self.find_header(file, seeklimit, seekstart)
		
		if offset == -1 or header is None:
			raise InvalidFileException

		if not self.valid:
			raise InvalidFileException

		self.parse_xing(file, seekstart, seeklimit)

		self.length_minutes = int(self.length / 60)
		self.length_seconds = int(round(self.length % 60))

	def find_header(self, file, seeklimit = MP3_HEADER_SEEK_LIMIT,
					 seekstart = 0, check_next_header = 1):
		amt = 5120  
		cur_pos = 0
		read_more = 0 

		file.seek(seekstart, 0)
		header = file.read(min(amt,seeklimit + 4))
		
		while cur_pos <= seeklimit:				
			offset = string.find(header, chr(255), cur_pos)
			
			if offset == -1:
				cur_pos = len(header)		
				read_more = 1 
			
			elif offset + 4 > len(header):
				cur_pos = offset  
				read_more = 1 
			elif ord(header[offset + 1]) & 0xE0 == 0xE0:

				if check_next_header == 0:
					return seekstart + offset, header[offset:offset + 4]

				self.parse_header(header[offset:offset + 4])
					
				if self.valid:

					file_pos = file.tell()
					
					next_off, next_header = \
					self.find_header(file, seeklimit = 0, seekstart = seekstart + offset
								+ self.framelength, check_next_header = check_next_header - 1)

					file.seek(file_pos, 0)
					
					if next_off != -1:
						return seekstart + offset, header[offset:offset + 4]
					else:
						cur_pos = offset + 2
				else:
					cur_pos = offset + 2
					
			else:
				cur_pos = offset + 2

			if read_more and cur_pos <= seeklimit:
				chunk = file.read(amt)
				if len(chunk) == 0:
					return -1, None
				else:
					header += chunk
		
		return -1, None

	def parse_header(self, header):
		self.valid = 0 
		
		(bytes, ) = struct.unpack('>i', header)
		mpeg_version = (bytes >> 19) & 3  
		layer =	(bytes >> 17) & 3 
		protection_bit = (bytes >> 16) & 1  
		bitrate = (bytes >> 12) & 15
		samplerate = (bytes >> 10) & 3 
		padding_bit = (bytes >> 9) & 1 
		private_bit = (bytes >> 8) & 1
		mode = (bytes >> 6) & 3  
		mode_extension =  (bytes >> 4) & 3  
		copyright = (bytes >> 3) & 1 
		original = (bytes >> 2)	& 1
		emphasis = (bytes >> 0)	& 3

		if mpeg_version == 0:
			self.version = 2.5
		elif mpeg_version == 2:
			self.version = 2
		elif mpeg_version == 3:
			self.version = 1
		else:
			return

		if layer > 0:
			self.layer = 4 - layer
		else:
			return

		self.protection = protection_bit

		self.bitrate = bitrates[mpeg_version & 1][self.layer - 1][bitrate]
		self.samplerate = samplerates[mpeg_version][samplerate]
		
		if self.bitrate is None or self.samplerate is None:
			return

		self.padding = padding_bit
		self.private = private_bit
		self.mode = modes[mode]
		self.mode_extension = mode_extensions[self.layer - 1][mode_extension]
		self.copyright = copyright
		self.original = original
		self.emphasis = emphases[emphasis]

		try:
			if self.layer == 1:
				self.framelength = (12000 * self.bitrate / self.samplerate + padding_bit) * 4
				self.samplesperframe = 384.0
			elif self.layer == 2:
				self.framelength =  144000 * self.bitrate / self.samplerate + padding_bit
				self.samplesperframe = 1152.0
			else:
				if mpeg_version == 0 or mpeg_version == 2:
					fake_samplerate = self.samplerate << 1
				else:
					fake_samplerate = self.samplerate
					
				self.framelength = 144000 * self.bitrate / fake_samplerate + padding_bit
				self.samplesperframe = 1152.0 

			self.length = int(round((self.filesize / self.framelength) * (self.samplesperframe / self.samplerate)))
		except ZeroDivisionError:
			return  

		if self.framelength < 0 or self.length < 0:
			return
		
		self.valid = 1

	def parse_xing(self, file, seekstart = 0, seeklimit = MP3_HEADER_SEEK_LIMIT):
		file.seek(seekstart, 0)
		header = file.read(seeklimit)

		try:
			i = string.find(header, 'Xing')
			if i > 0:
				header += file.read(128)
				(flags, ) = struct.unpack('>i', header[i + 4:i + 8])
				if flags & 3:
					(frames, ) = struct.unpack('>i', header[i + 8:i + 12])
					(bytes, ) = struct.unpack('>i', header[i + 12:i + 16])

					if self.samplerate:
						length = int(round(frames * self.samplesperframe / self.samplerate))
						bitrate = ((bytes * 8.0 / length) / 1000)
						self.length = length
						self.bitrate = bitrate
						self.is_vbr = 1
						return
		except ZeroDivisionError:
			pass 
		except struct.error:
			pass 

		if seekstart != 0:
			self.parse_xing(file, 0, seeklimit)
	
	def keys(self):
		return self.__dict__.keys()

	def values(self):
		return self.__dict__.values()

	def has_key(self, k):
		return self.__dict__.has_key(k)

	def items(self):
		return map(None, self.keys(), self.values())

	def get(self, k, x = None):
		if self.has_key(k):
			return self.__dict__[k]
		else:
			return x

	def __getitem__(self, k):
		return self.__dict__[k]

class FileInfo:
	def __init__(self, fullpath):
		base, ext = os.path.splitext(fullpath)
		ext = string.lower(ext)

		if ext == ".ogg":
			if ogg_support != "yes":
				sys.stderr.write("WARNING: Ogg vorbis support disabled, cannot find file info\n")
				raise InvalidFileException
				
			try:
				vf = ogg.vorbis.VorbisFile(fullpath)
			except IOError:
				raise InvalidFileException

			vc = vf.comment()
			vi = vf.info()

			self.samplerate = vi.rate
			self.length = vf.time_total(-1)
			self.bitrate = vf.bitrate(-1) / 1024
			self.filesize = vf.raw_total(-1) / 1024 / 1024
			
			for key, val in vc.items():
				if key == 'TITLE':
					self.title = val
				elif key == 'ARTIST':
					self.artist = val
				elif key == 'ALBUM':
					self.album = val
				elif key == 'DATE':
					self.year = val
				elif key == 'GENRE':
					self.genre = val
				elif key == 'VENDOR':
					self.vendor = val
				elif key == 'TRACKNUMBER':
					self.track = val
				elif key == 'COMMENT':
					self.comment = val
				elif key == 'TRANSCODED':
					self.transcoded = val


			if self.length > 3600:
				self.duration = "%02d:%02d:%02d" % (int(self.length / 3600),
									int(self.length / 60) % 60,
									int(self.length) % 60)
			else:
				self.duration = "%02d:%02d" % (int(self.length / 60), int(self.length) % 60)
					    
		elif ext == ".mp3":
			try:
				id3info = ID3(fullpath)
			except InvalidFileException:
				id3info = None

			if id3info:
				self.title = id3info.title
				self.artist = id3info.artist
				self.album = id3info.album
				self.year = id3info.year
				self.comment = id3info.comment
				self.track = id3info.track
				self.genre = id3info.genre
		
			try:
				mpeginfo = MPEG(fullpath)
			except InvalidFileException:
				mpeginfo = None
			
			if mpeginfo:
				self.filesize = float(mpeginfo.filesize) / 1024 / 1024
				self.bitrate = mpeginfo.bitrate
				self.samplerate = mpeginfo.samplerate
				self.mode = mpeginfo.mode
				self.mode_extension = mpeginfo.mode_extension

				self.length = mpeginfo.length
				self.minutes = mpeginfo.length_minutes
				self.seconds = mpeginfo.length_seconds
				
				if mpeginfo.length > 3600:
					self.duration = "%02d:%02d:%02d" % (int(self.length / 3600),
										int(self.length / 60) % 60,
										int(self.length) % 60)
				else:
					self.duration = "%02d:%02d" % (int(self.length / 60), int(self.length) % 60)
		else:
			raise InvalidFileException
		
	def keys(self):
		return self.__dict__.keys()

	def values(self):
		return self.__dict__.values()

	def has_key(self, k):
		return self.__dict__.has_key(k)

	def items(self):
		return map(None, self.keys(), self.values())

	def get(self, k, x = None):
		if self.has_key(k):
			return self.__dict__[k]
		else:
			return x

	def __getitem__(self, k):
		return self.__dict__[k]

class InvalidFileException(Exception):
	pass
