24 Commits
Author SHA1 Message Date
RandyTheSilly 5c83969ce2 Copy non-FLAC files instead of moving them 2022-04-24 13:37:14 -04:00
RandyTheSilly 19a7f3b7b2 Fix existing destination file detection 2022-04-24 13:36:34 -04:00
RandyTheSilly be7166e2dd Copy non-FLAC files to destination directory 2022-04-24 12:36:41 -04:00
RandyTheSilly 8ba7815241 Add support for skipping conversions on non-FLAC files 2022-04-22 12:50:27 -04:00
RandyTheSilly d03d73a2f8 Fixed typo from last commit 2022-04-22 12:44:26 -04:00
RandyTheSilly aa9ec97695 Check for metaflac ReplayGain data first 2022-04-22 12:40:52 -04:00
RandyTheSilly fcee6ba3f4 Cleaned up import statements 2022-04-22 12:29:34 -04:00
RandyTheSilly 1daa02f7ac Added '[' and ']' to special character list 2022-04-22 12:27:43 -04:00
RandyTheSilly 6b8553cbee Prevent crashes when a non-FLAC file is found 2022-04-22 12:26:11 -04:00
RandyTheSilly 88e3994f4f Added EOF return codes 2022-04-20 21:02:46 -04:00
RandyTheSilly f45dab8cfb Added return codes 2022-04-20 20:53:57 -04:00
RandyTheSilly 6d8deda002 Prevent errors when attempting to process files without valid ReplayGain data 2022-04-20 20:51:18 -04:00
RandyTheSilly d2598c561a Update README.md 2022-04-20 20:47:00 -04:00
RandyTheSilly 35bc1d9212 Trigger individual scanning on resolution errors 2022-04-20 20:31:40 -04:00
RandyTheSilly 5550bc5b76 Added script for quickly adding ReplayGain data to a FLAC library 2022-04-20 20:23:40 -04:00
RandyTheSilly b91511286c Added option to stop the program if ReplayGain data cannot be found 2022-04-20 00:48:58 -04:00
RandyTheSilly 8704749e7b Update README.md 2022-04-20 00:37:38 -04:00
RandyTheSilly 094725cad0 Remove --strip option 2022-04-20 00:31:30 -04:00
RandyTheSilly f79d6ce025 Add option to use album gain instead of track gain 2022-04-20 00:21:32 -04:00
RandyTheSilly c9a31dcbce Remove rg2sc integration 2022-04-20 00:09:26 -04:00
RandyTheSilly 1be96f0b20 Fix bugs preventing ffmpeg from completing conversions 2022-04-20 00:05:28 -04:00
RandyTheSilly 282c193804 Remove MP3 support 2022-04-19 23:08:55 -04:00
RandyTheSilly e833e4ce60 Add support for baking in ReplayGain values 2022-04-19 23:01:07 -04:00
RandyTheSilly b5a2b9adb3 Compatibility with new commits to rg2sc 2022-03-30 04:28:14 -04:00
5 changed files with 151 additions and 56 deletions
+10 -5
View File
@@ -1,7 +1,9 @@
# flac2pod # flac2pod
Converts your existing FLAC library to be played on an iPod Classic. Converts your existing FLAC library to be played on an iPod Classic.
This script makes use of ffmpeg to convert your existing FLAC music library to AAC-256 or MP3-320 for easy iPod Classic use. It also takes advantage of "rg2sc" (https://github.com/rwinkhart/rg2sc) to convert any existing ReplayGain tags to Apple SoundCheck tags that are compatible with Apple products. This script makes use of ffmpeg to convert your existing FLAC music library to AAC-256 for easy iPod Classic use. It can also bake your existing ReplayGain data into the output files. SoundCheck support was removed due to this feature being very finicky on iPods. If you would like to add SoundCheck data to your output files, omit the --bake option and then use https://github.com/rwinkhart/rg2sc on your output files.
In order for ReplayGain baking to work, your FLAC library must already be tagged with ReplayGain data. If you haven't already done this, flac2pod comes with a script (flac2pod-flacgain) for quickly applying these ReplayGain tags.
# Usage # Usage
Simply run... Simply run...
@@ -12,7 +14,11 @@ flac2pod <source_dir> <destination_dir>
``` ```
flac2pod --help flac2pod --help
``` ```
...to see additional options. ...to see additional options, or run...
```
flac2pod-flacgain <source_dir>
```
...to tag your FLAC library with ReplayGain data.
In order for flac2pod to function, your source_dir must be structured as follows: In order for flac2pod to function, your source_dir must be structured as follows:
@@ -22,7 +28,6 @@ source_dir -> artist dir -> album dir -> FLAC files
flac2pod is available in the AUR as "flac2pod". If installing on a non-Arch-based distribution, follow the manual installation instructions: flac2pod is available in the AUR as "flac2pod". If installing on a non-Arch-based distribution, follow the manual installation instructions:
- copy the flac2pod executable from https://github.com/rwinkhart/flac2pod/blob/master/bin/flac2pod to your /usr/bin/ - copy the contents of https://github.com/rwinkhart/flac2pod/blob/master/bin/ to your /usr/bin/
- copy the rg2sc executable from https://github.com/rwinkhart/rg2sc/blob/master/bin/rg2sc to your /usr/bin - install flac, python-mutagen, ffmpeg, and screen
- install python-mutagen, ffmpeg, lame, and screen
- start converting - start converting
+66 -47
View File
@@ -3,9 +3,10 @@
# external modules # external modules
from argparse import ArgumentParser from argparse import ArgumentParser
from mutagen.flac import FLAC from mutagen.flac import FLAC, FLACNoHeaderError
from os import cpu_count, path, walk from os import cpu_count, path, walk
from pathlib import Path from pathlib import Path
from shutil import copy
from subprocess import check_output, Popen from subprocess import check_output, Popen
from sys import exit as s_exit from sys import exit as s_exit
from time import sleep from time import sleep
@@ -13,11 +14,11 @@ from time import sleep
# utility functions # utility functions
def scan_source(): def scan_source(_source):
_artist_dirs, _album_dirs, _full_paths = [], [], [] _artist_dirs, _album_dirs, _full_paths = [], [], []
for _root, _directories, _files in walk(path.expanduser(source)): for _root, _directories, _files in walk(path.expanduser(_source)):
for _dir in sorted(_directories): for _dir in sorted(_directories):
if not _root.endswith(path.expanduser(source)): if not _root.endswith(path.expanduser(_source)):
_artist_dirs.append(_root) _artist_dirs.append(_root)
_artist_dirs = list(set(_artist_dirs)) _artist_dirs = list(set(_artist_dirs))
for _artist in sorted(_artist_dirs): for _artist in sorted(_artist_dirs):
@@ -29,7 +30,7 @@ def scan_source():
for _root, _directories, _files in walk(path.expanduser(_album)): for _root, _directories, _files in walk(path.expanduser(_album)):
for _filename in _files: for _filename in _files:
if _filename.endswith('.flac'): if _filename.endswith('.flac'):
_full_paths.append(f"{_album}/{_filename[:-5]}") _full_paths.append(f"{_album}/{_filename}")
return _album_dirs, _full_paths return _album_dirs, _full_paths
@@ -44,18 +45,13 @@ def scan_destination_convert():
for _file in source_directories[1]: for _file in source_directories[1]:
_i_total += 1 _i_total += 1
_progress = round((_i_total / _total_files) * 100, 2) _progress = round((_i_total / _total_files) * 100, 2)
if not Path(f"{_file.replace(path.expanduser(source), path.expanduser(destination))}.mp3").is_file() and not \ if not Path(f"{(_file.replace(path.expanduser(source), path.expanduser(destination)))[:-5]}.m4a").is_file():
Path(f"{_file.replace(path.expanduser(source), path.expanduser(destination))}.m4a").is_file():
_file_s = _file.replace(' ', '\\ ').replace("'", "\\'").replace(')', '\\)').replace('(', '\\(')\ _file_s = _file.replace(' ', '\\ ').replace("'", "\\'").replace(')', '\\)').replace('(', '\\(')\
.replace('&', '\\&').replace('`', '\\`').replace('$', '\\$') + '.flac' .replace(']', '\\]').replace('[', '\\[').replace('&', '\\&').replace('`', '\\`')\
if args.mp3: .replace('$', '\\$')
_file_d = _file.replace(path.expanduser(source), path.expanduser(destination)).replace(' ', '\\ ') \ _file_d = _file.replace(path.expanduser(source), path.expanduser(destination)).replace(' ', '\\ ')\
.replace("'", "\\'").replace(')', '\\)').replace('(', '\\(').replace('&', '\\&') \ .replace("'", "\\'").replace(')', '\\)').replace('(', '\\(').replace(']', '\\]')\
.replace('`', '\\`').replace('$', '\\$') + '.mp3' .replace('[', '\\[').replace('&', '\\&').replace('`', '\\`').replace('$', '\\$')[:-5] + '.m4a'
else:
_file_d = _file.replace(path.expanduser(source), path.expanduser(destination)).replace(' ', '\\ ') \
.replace("'", "\\'").replace(')', '\\)').replace('(', '\\(').replace('&', '\\&') \
.replace('`', '\\`').replace('$', '\\$') + '.m4a'
_active_processes = int(check_output('ps -C ffmpeg | wc -l', shell=True)) - 1 _active_processes = int(check_output('ps -C ffmpeg | wc -l', shell=True)) - 1
if _active_processes >= cpu_count(): if _active_processes >= cpu_count():
while _active_processes >= cpu_count(): while _active_processes >= cpu_count():
@@ -64,35 +60,55 @@ def scan_destination_convert():
_active_processes = int(check_output('ps -C ffmpeg | wc -l', shell=True)) - 1 _active_processes = int(check_output('ps -C ffmpeg | wc -l', shell=True)) - 1
_i += 1 _i += 1
print(f"\n{_progress}% | \u001b[38;5;0;48;5;15mConverting {_file_s} to {_file_d}...\u001b[0m\n") print(f"\n{_progress}% | \u001b[38;5;0;48;5;15mConverting {_file_s} to {_file_d}...\u001b[0m\n")
if args.mp3: # get relevant ReplayGain info
if args.strip: try:
_cmd = f"screen -DmS flac2pod{_i} ffmpeg -i {_file_s} -map 0:a -ab 320k -map_metadata 0" \ _audio = FLAC(f"{_file}")
f" -id3v2_version 3 {_file_d} </dev/null; rg2sc -f -s --mp3 {_file_d}" if args.albumgain:
else: if _audio.get('REPLAYGAIN_ALBUM_GAIN'):
_cmd = f"screen -DmS flac2pod{_i} ffmpeg -i {_file_s} -c:v copy -ab 320k -map_metadata 0" \ _rggain = float(_audio.get('REPLAYGAIN_ALBUM_GAIN')[0][:-3])
f" -id3v2_version 3 {_file_d} </dev/null; rg2sc -f --mp3 {_file_d}" elif _audio.get('replaygain_album_gain'):
else: _rggain = float(_audio.get('replaygain_album_gain')[0][:-3])
_audio = FLAC(f"{_file}.flac")
if _audio.get('replaygain_track_gain'):
_rggain = float(_audio.get('replaygain_track_gain')[0][:-3])
elif _audio.get('REPLAYGAIN_TRACK_GAIN'):
_rggain = float(_audio.get('REPLAYGAIN_TRACK_GAIN')[0][:-3])
else: else:
_rggain = None _rggain = None
if _audio.get('replaygain_track_peak'): if _audio.get('REPLAYGAIN_ALBUM_PEAK'):
_rgpeak = float(_audio.get('replaygain_track_peak')[0]) _rgpeak = float(_audio.get('REPLAYGAIN_ALBUM_PEAK')[0])
elif _audio.get('REPLAYGAIN_TRACK_PEAK'): elif _audio.get('replaygain_album_peak'):
_rgpeak = float(_audio.get('REPLAYGAIN_TRACK_PEAK')[0]) _rgpeak = float(_audio.get('replaygain_album_peak')[0])
else: else:
_rgpeak = None _rgpeak = None
if args.strip:
_cmd = f"screen -DmS flac2pod{_i} ffmpeg -i {_file_s} -c:a aac -ab 256k -map_metadata 0 -metadata" \
f" comment='FLAC2PODRG#{_rggain}#{_rgpeak}#' -aac_pns 0 -movflags +faststart -vn" \
f" {_file_d} </dev/null; rg2sc -f -s {_file_d}"
else: else:
_cmd = f"screen -DmS flac2pod{_i} ffmpeg -i {_file_s} -c:a aac -ab 256k -c:v copy -map_metadata" \ if _audio.get('REPLAYGAIN_TRACK_GAIN'):
f" 0 -metadata comment='FLAC2PODRG#{_rggain}#{_rgpeak}#' -aac_pns 0 -movflags +faststart" \ _rggain = float(_audio.get('REPLAYGAIN_TRACK_GAIN')[0][:-3])
f" {_file_d} </dev/null; rg2sc -f {_file_d}" elif _audio.get('replaygain_track_gain'):
_rggain = float(_audio.get('replaygain_track_gain')[0][:-3])
else:
_rggain = None
if _audio.get('REPLAYGAIN_TRACK_PEAK'):
_rgpeak = float(_audio.get('REPLAYGAIN_TRACK_PEAK')[0])
elif _audio.get('replaygain_track_peak'):
_rgpeak = float(_audio.get('replaygain_track_peak')[0])
else:
_rgpeak = None
except FLACNoHeaderError:
print(f"[{_file}] Not a FLAC file, copying...")
copy(f"{_file}", f"{_file.replace(path.expanduser(source), path.expanduser(destination))}")
_rggain, _rgpeak = None, None
# determine ffmpeg arguments
if args.bake and _rggain is not None:
_bake_args, _flac2pod_rg_tags = '-filter:a "volume=' + str(_rggain) + 'dB"', ''
elif _rggain is not None and _rgpeak is not None:
_bake_args, _flac2pod_rg_tags = '', f"-metadata comment='FLAC2PODRG#{_rggain}#{_rgpeak}#'"
else:
_bake_args, _flac2pod_rg_tags = '', ''
# generate the appropriate ffmpeg command
_cmd = f"screen -DmS flac2pod{_i} ffmpeg -i {_file_s} -c:a aac -ab 256k {_bake_args} -map_metadata 0 " \
f"{_flac2pod_rg_tags} -aac_pns 0 -movflags +faststart -vn {_file_d} </dev/null"
if _rggain is not None:
print(f"\u001b[38;5;0;48;5;15mGain adjustment: {_rggain}dB\u001b[0m")
else:
print(f"\u001b[38;5;0;48;5;88mNo ReplayGain data found!\u001b[0m")
if args.stopifnogain:
s_exit(1)
Popen(_cmd, shell=True) Popen(_cmd, shell=True)
_active_processes = int(check_output('ps -C ffmpeg | wc -l', shell=True)) - 1 _active_processes = int(check_output('ps -C ffmpeg | wc -l', shell=True)) - 1
while _active_processes != 0: while _active_processes != 0:
@@ -101,7 +117,7 @@ def scan_destination_convert():
_active_processes = int(check_output('ps -C ffmpeg | wc -l', shell=True)) - 1 _active_processes = int(check_output('ps -C ffmpeg | wc -l', shell=True)) - 1
sleep(1) sleep(1)
print('\niPod conversion complete!\n') print('\niPod conversion complete!\n')
s_exit() s_exit(0)
# argument parsing # argument parsing
@@ -112,11 +128,12 @@ if __name__ == "__main__":
'and albums') 'and albums')
parser.add_argument('destination_dir', nargs='+', parser.add_argument('destination_dir', nargs='+',
help='destination parent directory for output - will be created if it does not already exist') help='destination parent directory for output - will be created if it does not already exist')
parser.add_argument('-s', '--strip', action='store_true', parser.add_argument('-b', '--bake', action='store_true',
help='strip all TXXX, APIC, and covr tags from the output files') help='bake (encode) ReplayGain values into the file')
parser.add_argument('--mp3', action='store_true', parser.add_argument('-a', '--albumgain', action='store_true',
help='convert to MP3, as opposed to the default of AAC .M4A') help='read ReplayGain album gain instead of ReplayGain track gain')
parser.add_argument('-x', '--stopifnogain', action='store_true',
help='stop flac2pod if ReplayGain data cannot be found in a file')
args = parser.parse_args() args = parser.parse_args()
if args.source_dir[0].endswith('/'): if args.source_dir[0].endswith('/'):
@@ -128,6 +145,8 @@ if __name__ == "__main__":
else: else:
destination = args.destination_dir[0] destination = args.destination_dir[0]
source_directories = scan_source() source_directories = scan_source(source)
create_destination() create_destination()
scan_destination_convert() scan_destination_convert()
s_exit(0)
+70
View File
@@ -0,0 +1,70 @@
#!/bin/python3
from argparse import ArgumentParser
from flac2pod import scan_source
from mutagen.flac import FLAC, FLACNoHeaderError
from os import listdir, system
from subprocess import PIPE, Popen, STDOUT
from sys import exit as s_exit
# argument parsing
if __name__ == "__main__":
parser = ArgumentParser(description='Quickly tag your FLAC library with ReplayGain data using metaflac.')
parser.add_argument('source_dir', nargs='+',
help='directory tree containing music files - folder must contain library sorted into artists '
'and albums')
parser.add_argument('-f', '--force', action='store_true',
help='overwrite existing ReplayGain data')
args = parser.parse_args()
if args.source_dir[0].endswith('/'):
source = args.source_dir[0][:-1]
else:
source = args.source_dir[0]
source_directories = scan_source(source)
gain = 1
for album in sorted(source_directories[0]):
std_album = album.replace(' ', '\\ ').replace("'", "\\'").replace(')', '\\)').replace('(', '\\(')\
.replace(']', '\\]').replace('[', '\\[').replace('&', '\\&').replace('`', '\\`').replace('$', '\\$')
for song in listdir(album):
try:
audio = FLAC(f"{album}/{song}")
if audio.get('replaygain_track_gain') or audio.get('REPLAYGAIN_TRACK_GAIN'):
gain = 1
else:
gain = 0
break
except FLACNoHeaderError:
print(f"[{album}/*] Contains non-FLAC files, skipping album...")
gain = 2
if gain != 2 and (args.force or gain == 0):
print(f"[{album}/*] Adding ReplayGain data...")
system(f"metaflac --remove-replay-gain {std_album}/*")
command = f"metaflac --add-replay-gain {std_album}/*"
output = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
block = output.communicate()[0].strip() # blocks the program from proceeding until stdout is given
if output.returncode == 1:
if block.decode('utf-8').__contains__('sample') or block.decode('utf-8').__contains__('resolution of'):
print('Resolution/Sample Rate mismatch, scanning tracks as individuals...')
for song in listdir(album):
print(f"[{album}/{song}] Adding ReplayGain data...")
std_song = song.replace(' ', '\\ ').replace("'", "\\'").replace(')', '\\)')\
.replace('(', '\\(').replace('&', '\\&').replace('`', '\\`').replace('$', '\\$')
command = f"metaflac --add-replay-gain {std_album}/{std_song}"
output = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
block = output.communicate()[0].strip()
if output.returncode == 1:
print('There was an error processing your files.')
print(f"Return Code: [{str(output.returncode)}] {block.decode('utf-8')}")
s_exit(1)
else:
print('There was an error processing your files.')
print(f"Return Code: [{str(output.returncode)}] {block.decode('utf-8')}")
s_exit(1)
else:
print(f"[{album}/*] ReplayGain data is already present.")
s_exit(0)
+1
View File
@@ -0,0 +1 @@
/usr/bin/flac2pod
+1 -1
View File
@@ -39,7 +39,7 @@ pkgdesc='Converts your FLAC library to be iPod-ready'
url='https://github.com/rwinkhart/flac2pod' url='https://github.com/rwinkhart/flac2pod'
arch=('any') arch=('any')
license=('GPL2') license=('GPL2')
depends=(python ffmpeg lame rg2sc screen python-mutagen) depends=(ffmpeg flac python python-mutagen screen)
source=(\""$source"\") source=(\""$source"\")
sha512sums=('"$sha512"') sha512sums=('"$sha512"')