Files
flac2ogg/flac2ogg.py
T
2026-11-29 17:16:53 +01:00

585 lines
17 KiB
Python
Executable File

#!/usr/bin/env python
"""
Audio file converter.
"""
import argparse
import base64
import multiprocessing as mp
import os
import re
import subprocess as sp
import sys
import mutagen
import mutagen.easyid3
import mutagen.flac
import mutagen.id3
import mutagen.mp3
VERSION = '1.4.0'
def match_file(path):
"""Get all wav files from provided location"""
re_ = re.compile(r"^.*_\d+.wav$")
matched_files = [os.path.join(path, filename)
for filename in os.listdir(os.path.abspath(path))
if re_.match(filename)]
return sorted(matched_files)
def get_filepaths_recursively(pattern=None):
"""Gather and return files"""
if pattern and len(pattern) == 1 and pattern[0].startswith("*"):
pat = "." + pattern[0]
else:
print("Recursive option only works with simple pattern for files"
" match")
sys.exit(1)
files_ = []
for root, _, files in os.walk("."):
for filename in files:
if re.match(pat, filename):
files_.append(os.path.join(root, filename))
return files_
def encode(obj):
"""Encode files with specified command"""
obj.encode()
class CueTrack:
def __init__(self):
"""Init"""
self.performer = None
self.title = None
class CueObjectParser:
def __init__(self, cuefile):
"""Init"""
self.cuefile = cuefile
self.album_artist = None
self.album = None
self.tracks = []
self._parse_cue()
def get_track_data(self, index):
return self.tracks[index].title, self.tracks[index].performer
def _parse_cue(self):
"""Read and parse cuefile"""
with open(self.cuefile) as fobj:
content = fobj.read()
in_track = False
track = None
for line in content.split('\n'):
if not in_track:
if line.strip().upper().startswith('REM'):
continue
if line.strip().upper().startswith('PERFORMER'):
self.album_artist = line.split('"')[1]
continue
if line.strip().upper().startswith('TITLE'):
self.album = line.split('"')[1]
continue
if 'TRACK' in line.strip().upper():
in_track = True
track = CueTrack()
self.tracks.append(track)
continue
if in_track:
if line.strip().upper().startswith('PERFORMER'):
track.performer = line.split('"')[1]
continue
if line.strip().upper().startswith('TITLE'):
track.title = line.split('"')[1]
continue
class Tag:
def __init__(self, source_file, destination_file):
self.pictures = []
self.tags = {}
if destination_file.lower().endswith(".mp3"):
dest = self._tag_mp3
if (destination_file.lower().endswith(".ogg") or
destination_file.lower().endswith(".opus")):
dest = self._tag_ogg
if source_file.lower().endswith(".mp3"):
self._extract_mp3_tags(source_file)
if source_file.lower().endswith(".flac"):
self._extract_flac_tags(source_file)
if (source_file.lower().endswith(".ogg") or
source_file.lower().endswith(".opus")):
self._extract_ogg_tags(source_file)
dest(destination_file)
def _tag_mp3(self, dest):
tags = mutagen.mp3.MP3(dest, ID3=mutagen.easyid3.EasyID3)
if self.tags:
for key in ['album', 'albumartist', 'artist', 'composer',
'copyright', 'date', 'discnumber', 'encoded-by',
'genre', 'title', 'tracknumber']:
if key not in self.tags:
continue
if key == 'encoded-by':
tags['encodedby'] = self.tags[key]
else:
tags[key] = self.tags[key]
if 'tracknumber' in self.tags and 'tracktotal' in self.tags:
tags['tracknumber'] = [(f"{self.tags['tracknumber'][0]}"
f"/{self.tags['tracktotal'][0]}")]
tags.save()
tags = mutagen.id3.ID3(dest)
for key in ('contact', 'description', 'performer'):
if key not in self.tags:
continue
if key == 'contact':
tags.add(mutagen.id3.WXXX(url=self.tags[key][0]))
if key == 'description':
tags.add(mutagen.id3.COMM(text=self.tags[key]))
if key == 'performer':
tags.add(mutagen.id3.TOPE(text=self.tags[key]))
for pic in self.pictures:
tags.add(mutagen.id3.APIC(encoding=3, mime=pic.mime, type=pic.type,
desc=pic.desc, data=pic.data))
tags.save()
def _tag_ogg(self, dest):
tags = mutagen.File(dest)
if self.tags:
tags.update(self.tags)
if self.pictures:
tags['metadata_block_picture'] = [base64.b64encode(pic.write())
.decode('ascii')
for pic in self.pictures]
tags.save()
def _extract_flac_tags(self, source):
"""Extract all embedded pictures from FLAC."""
tags = mutagen.flac.FLAC(source)
self.tags = dict(tags)
self.pictures = tags.pictures
def _extract_ogg_tags(self, source):
"""Extract pictures from OGG Vorbis or OGG Opus."""
tags = mutagen.File(source)
self.tags = dict(tags)
for x in ['metadata_block_picture', 'coverart', 'coverartmime']:
if x in self.tags:
del self.tags[x]
for encoded in tags.get("metadata_block_picture", []):
try:
raw = base64.b64decode(encoded, validate=True)
picture = mutagen.flac.Picture(raw)
self.pictures.append(picture)
except (ValueError, TypeError, mutagen.flac.FLACError):
continue
# Legacy coverart convention used by some applications.
if not self.pictures:
for encoded, mime in zip(tags.get("coverart", []),
tags.get("coverartmime", [])):
try:
raw = base64.b64decode(encoded, validate=True)
picture = mutagen.flac.Picture()
picture.data = raw
picture.mime = mime or "image/jpeg"
picture.type = 3
picture.desc = ""
self.pictures.append(picture)
except (ValueError, TypeError):
continue
def _extract_mp3_tags(self, source):
"""get all mp3 tags, and store it as a unified dict"""
tags = mutagen.mp3.MP3(source, ID3=mutagen.easyid3.EasyID3)
if tags.get('tracknumber'):
if '/' in tags['tracknumber'][0]:
tn, tt = tags['tracknumber'][0].split('/')
self.tags['tracknumber'], self.tags['tracktotal'] = [tn], [tt]
else:
self.tags['tracknumber'] = tags['tracknumber']
if tags.get('encodedby'):
self.tags['encoded-by'] = tags['encodedby']
for key in ['album', 'albumartist', 'artist', 'composer', 'copyright',
'date', 'discnumber', 'genre', 'title']:
if key in tags:
self.tags[key] = tags[key]
tags = mutagen.id3.ID3(source)
if tags.get('WXXX:'):
self.tags['contact'] = [tags['WXXX:'].url]
if tags.getall('COMM'):
self.tags['description'] = tags.getall('COMM')[0].text
if tags.get('TOPE'):
self.tags['performer'] = tags['TOPE'].text
if tags is None:
return
for frame in tags.getall("APIC"):
picture = mutagen.flac.Picture()
picture.data = frame.data
picture.mime = frame.mime
picture.type = frame.type
picture.desc = frame.desc
self.pictures.append(picture)
class Encoder:
"""Encoder base class"""
EXT = ".undefined"
def __init__(self, quality=None):
self.quality = quality
self.ext = self.EXT
def encode(self, input_fname, output_fname):
"""Encode file"""
raise NotImplementedError
class OggEncoder(Encoder):
"""Vorbis encoder"""
EXT = ".ogg"
def __init__(self, quality=None):
"""Init"""
super().__init__(quality)
if self.quality is None:
self.quality = 8
def encode(self, input_fname, output_fname):
sp.check_call(["oggenc", f"-q{self.quality}", input_fname, '-o',
output_fname])
class Mp3Encoder(Encoder):
"""Mp3 encoder"""
EXT = ".mp3"
def __init__(self, quality=None):
"""Init"""
super().__init__(quality)
if self.quality is None:
self.quality = 6
def encode(self, input_fname, output_fname):
sp.check_call(["lame", f"-V{self.quality}", input_fname, output_fname])
class OpusEncoder(Encoder):
"""Opus encoder"""
EXT = ".opus"
def __init__(self, quality=None):
"""Init"""
super().__init__(quality)
if self.quality is None:
self.quality = 128
def encode(self, input_fname, output_fname):
sp.check_call(["opusenc", "--bitrate", str(self.quality), input_fname,
output_fname])
class FileType:
"""Base class for file objects"""
extensions = {'ogg': '.ogg',
'mp3': '.mp3'}
def __init__(self, filename, encoder):
self.filename = filename
self.encoder = encoder
self.out_fname = None
self.base, self.ext = os.path.splitext(filename)
self.ext = self.ext.lower()
self.wav = self.base + ".wav"
self.tmp_wav_remove = True
self.album = None
self.album_artist = None
self.title = None
self.performer = None
def extract_wav(self):
"""Dummy function for wav files"""
raise NotImplementedError
def encode(self):
"""Encode and tag file"""
self.out_fname = self._get_output_fn()
self.extract_wav()
self.encoder.encode(self.wav, self.out_fname)
self._tag_file()
self.cleanup()
def cleanup(self):
"""Remove intermediate wav file"""
if not self.tmp_wav_remove:
return
os.unlink(self.wav)
def _get_output_fn(self):
"""Get unique name for the output file"""
out = self.base
while os.path.exists(out + self.encoder.ext):
out = out + "_encoded_"
return out + self.encoder.ext
def _tag_file(self):
"""Transfer tags from source files, or from cue"""
Tag(self.filename, self.out_fname)
class FlacType(FileType):
"""Flac filetype"""
def extract_wav(self):
"""Call flac to extract flac file to wav"""
sp.check_call(["flac", "-d", self.filename])
class ApeType(FileType):
"""Ape filetype"""
def extract_wav(self):
"""Extract ape file to wav"""
sp.check_call(["mac", self.filename, self.wav, "-d"])
class WvType(FileType):
"""Wv filetype"""
def extract_wav(self):
"""Extract wavepack file to wav"""
sp.check_call(["wvunpack", self.filename, "-o", self.wav])
class M4aType(FileType):
"""M4a filetype"""
def __init__(self, filename, encoder):
super().__init__(filename, encoder)
def extract_wav(self):
"""Extract m4a file to wav"""
wav = self.wav
if "," in wav:
wav = wav.replace(",", "\\,")
sp.check_call(["mplayer", "-vo", "none", self.filename, "-ao",
f"pcm:file={wav}"])
class WavType(FileType):
"""Uncompressed wav filetype"""
def __init__(self, filename, encoder):
super().__init__(filename, encoder)
self.wav = filename
self.tmp_wav_remove = False
def extract_wav(self):
"""Do nothing, we already unpacked here"""
return
class Mp3Type(FileType):
"""Mp3 filetype"""
def extract_wav(self):
"""Extract mp3 file to wav"""
sp.check_call(["lame", "--decode", self.filename, self.wav])
class MusepackType(FileType):
"""Musepack filetype"""
def __init__(self, filename, encoder):
super().__init__(filename, encoder)
def extract_wav(self):
"""Extract m4a file to wav"""
wav = self.wav
if "," in wav:
wav = wav.replace(",", "\\,")
sp.check_call(["mpcdec", self.filename, self.wav])
class OggType(FileType):
"""Ogg Vorbis filetype"""
def extract_wav(self):
"""Extract ogg vorbis file to wav"""
sp.check_call(["oggdec", self.filename])
class OpusType(FileType):
"""Opus filetype"""
def extract_wav(self):
"""Extract opus file to wav"""
sp.check_call(["opusdec", self.filename])
class Converter:
"""Main class for converting files"""
extract_map = {'.ape': ApeType,
'.flac': FlacType,
'.m4a': M4aType,
'.mp3': Mp3Type,
'.mpc': MusepackType,
'.ogg': OggType,
'.opus': OpusType,
'.wav': WavType,
'.wv': WvType}
def __init__(self, split=False, files=tuple()):
"""Init"""
self.files = files
self._file_objs = []
self.split = split
def run(self, encoder):
"""Do the conversion"""
self._prepare_files(encoder)
self._encode()
def _prepare_files(self, encoder):
"""Determine file types, and create corresponding objects"""
for filename in self.files:
base, ext = os.path.splitext(filename)
if self.split:
self._split_file(filename, base, ext, encoder)
else:
klass = Converter.extract_map.get(ext.lower())
if not klass:
continue
obj = klass(filename, encoder)
self._file_objs.append(obj)
def _split_file(self, filename, base, ext, encoder):
"""Split file using cue file information"""
wav = base + ".wav"
cuefile = None
for tmp in (base + ".cue", base + ".wav.cue", base + ".flac.cue",
base + ".wv.cue", base + ".ape.cue"):
if os.path.exists(tmp):
cuefile = tmp
print(f"*** cuefile: {cuefile}")
break
if cuefile is None:
print(f"*** No cuefile found for `{filename}'")
return
cue = CueObjectParser(cuefile)
# Extract file to the wav. Note, that object will not be added to the
# list of wavs to encode
klass = Converter.extract_map.get(ext.lower())
if not klass:
print(f"*** Cannot find right converter for `{ext}'")
return
fobj = klass(filename, encoder)
fobj.extract_wav()
pipe = sp.Popen(["cuebreakpoints", cuefile], stdout=sp.PIPE)
sp.check_call(["shnsplit", "-a", base + "_", "-o", "wav", wav],
stdin=pipe.stdout, stdout=sp.PIPE)
filepath = os.path.dirname(filename)
for index, filename in enumerate(match_file(filepath)):
obj = WavType(filename, encoder)
obj.tmp_wav_remove = True
obj.album = cue.album
obj.album_artist = cue.album_artist
obj.album = cue.album
obj.title, obj.performer = cue.get_track_data(index)
self._file_objs.append(obj)
fobj.cleanup()
def _encode(self):
"""Encode files"""
pool = mp.Pool()
# NOTE: map_async and get with timeout 999 are simply a hack for being
# able to interrupt the process with ctrl+c
pool.map_async(encode, tuple(self._file_objs)).get(999)
ENCODERS = {'ogg': OggEncoder,
'mp3': Mp3Encoder,
'opus': OpusEncoder}
def main():
"""Main"""
arg = argparse.ArgumentParser(description='Convert between different '
'audio file format.')
arg.add_argument('-s', '--split', action='store_true',
help='Split output file with provided *.cue file')
arg.add_argument('-r', '--recursive', action='store_true',
help='Do the files searching recursive')
arg.add_argument('-e', '--encoder', default='opus', type=str,
choices=('ogg', 'mp3', 'opus'),
help='Encoder to use. Defaults to "opus"')
arg.add_argument('-q', '--quality', help='Quality of the encoded file. '
'Consult "lame", "oggenc" and "opusenc" manuals for '
'details. Defaults are -V6 for lame, -q8 for oggenc and '
'--bitrate 128 for opusenc')
arg.add_argument('-v', '--version', action='version',
version='%(prog)s v' + VERSION,
help='Display version and exit.')
arg.add_argument('files', nargs='+', help='File(s) to encode')
args = arg.parse_args()
if args.recursive:
files = get_filepaths_recursively(args.files)
else:
files = args.files
conv = Converter(args.split, files)
encoder = ENCODERS[args.encoder](args.quality)
conv.run(encoder)
if __name__ == "__main__":
main()