-
Notifications
You must be signed in to change notification settings - Fork 6
/
dir2ogg
executable file
·842 lines (763 loc) · 27 KB
/
dir2ogg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
#!/usr/bin/python3
#
# Copyright (C) 2007-2009 Julian Andres Klode <jak@jak-linux.org>
# Copyright (C) 2003-2006 Darren Kirby <d@badcomputer.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
"""
dir2ogg converts mp3, m4a, and wav files to the free open source OGG format. Oggs are
about 20-25% smaller than mp3s with the same relative sound quality. Your mileage may vary.
Keep in mind that converting from mp3 or m4a to ogg is a conversion between two lossy formats.
This is fine if you just want to free up some disk space, but if you're a hard-core audiophile
you may be dissapointed. I really can't notice a difference in quality with 'naked' ears myself.
This script converts mp3s to wavs using mpg123 then converts the wavs to oggs using oggenc.
m4a conversions require faad. Id3 tag support requires mutagen for mp3s.
Scratch tags using the filename will be written for wav files (and mp3s with no tags!)
"""
import locale
import os
import os.path
import re
import sys
import warnings
from fnmatch import translate
from optparse import OptionParser
from subprocess import PIPE, Popen, call
__version__ = "0.12"
__date__ = "2016-01-19"
FILTERS = {
"mp3": ("*.mp3",),
"mpc": ("*.mpc", "*.mpp", "*.mp+"),
"m4a": ("*.aac", "*.m4a", "*.mp4"),
"wma": ("*.asf", "*.wma", "*.wmf"),
"flac": ("*.flac",),
"ape": ("*.ape",),
"wv": ("*.wv", "*.wvc"),
"wav": ("*.wav",),
}
# Cache of regex patterns
_cache = {}
def mmatch(names, patterns, rbool=True):
"""names/patterns=str/list/tuple"""
results = []
if isinstance(names, str):
names = [names]
if isinstance(patterns, str):
patterns = [patterns]
for pat in patterns:
pat = pat.lower()
if pat not in _cache:
_cache[pat] = re.compile(translate(pat))
match = _cache[pat].match
for name in names:
if match(name.lower()):
if rbool:
return True
else:
results.append(name)
if rbool:
return bool(results)
else:
return results
def read_opts():
if "--version" not in sys.argv:
show_banner()
if len(sys.argv[1:]) == 0:
fatal("No arguments specified, see --help for usage.")
parser = OptionParser(
usage="%prog [options] [arguments]", version="%prog " + __version__
)
parser.add_option(
"-l",
"--license",
action="callback",
callback=show_license,
help="display license informations",
)
parser.add_option(
"-d",
"--directory",
action="store_true",
help="convert files in all directories specified as arguments (not needed anymore)",
)
parser.add_option(
"-r",
"--recursive",
action="store_true",
help="convert files in all subdirectories of all directories specified as arguments",
)
parser.add_option(
"-q",
"--quality",
metavar="N",
default=3.0,
type="float",
help="quality. N is a number from 1-10 (default %default)",
)
parser.add_option(
"-t",
"--smart-mp3",
action="store_true",
help="try to use similar quality as original mp3 file (overwrites -q)",
)
parser.add_option(
"-T",
"--smart-mp3-correction",
metavar="N",
default=0.0,
type="float",
help="decrease detected quality (implies -t)",
)
parser.add_option(
"-n",
"--no-mp3",
dest="convert_mp3",
action="store_false",
default=True,
help="don't convert mp3s (use with '-d' or '-r')",
)
parser.add_option(
"-a", "--convert-all", action="store_true", help="convert all supported formats"
)
parser.add_option(
"-A",
"--convert-ape",
action="store_true",
help="convert all APE files found in directories.",
)
parser.add_option(
"-f",
"--convert-flac",
action="store_true",
help="convert all FLAC files found in directories",
)
parser.add_option(
"-m",
"--convert-m4a",
action="store_true",
help="convert all M4A files found in directories",
)
parser.add_option(
"-M",
"--convert-mpc",
action="store_true",
help="convert all MPC files found in directories",
)
parser.add_option(
"-w",
"--convert-wav",
action="store_true",
help="convert all WAV files found in directories",
)
parser.add_option(
"-W",
"--convert-wma",
action="store_true",
help="convert all WMA files found in directories",
)
parser.add_option(
"-V",
"--convert-wv",
action="store_true",
help="convert all WV files found in directories",
)
parser.add_option("--delete-input", action="store_true", help="delete input files")
parser.add_option(
"-p",
"--preserve-wav",
action="store_true",
help="keep the wav files (also includes -P)",
)
parser.add_option(
"-P",
"--no-pipe",
action="store_true",
help="Do not use pipes, use temporary wav files",
)
parser.add_option("-v", "--verbose", action="store_true", help="verbose output")
parser.add_option(
"-Q", "--quiet", action="store_true", help="do not display progress report."
)
# Setup decoders
commands = {
"mp3": ("mpg123", "mpg321", "lame", "mplayer"),
"wma": ("mplayer",),
"m4a": ("faad", "mplayer"),
"flac": ("flac", "ogg123", "mplayer"),
"ape": ("mac", "mplayer"),
"wv": ("wvunpack", "mplayer"),
"mpc": ("mpcdec", "mplayer"),
}
for ext, dec in commands.items():
default, choices = None, []
for command in dec:
in_path = [
prefix
for prefix in os.environ["PATH"].split(os.pathsep)
if os.path.exists(os.path.join(prefix, command))
]
if in_path:
choices.append(command)
default = default or command
parser.add_option(
"--" + ext + "-decoder",
type="choice",
metavar=default,
default=default,
choices=choices,
help="decoder for {} files (choices: {})".format(ext, ", ".join(choices)),
)
# End of decoder options
options, args = parser.parse_args()
options.filters = []
for ext, pat in FILTERS.items():
# Activate Encoders for files on the commandline
if options.convert_all or mmatch(args, pat):
setattr(options, "convert_" + ext, True)
if getattr(options, "convert_" + ext):
options.filters += pat
# Missing decoders
if (
ext != "wav"
and getattr(options, "convert_" + ext)
and not getattr(options, ext + "_decoder")
):
fatal("%s was enabled, but no decoder has been found." % ext)
if len(args) == 0:
fatal("No files/directories specified.")
return options, args
def info(msg):
print("INFO: %s" % msg)
def warn(msg):
"""print errors to the screen (red)"""
print("WARNING: %s" % msg, file=sys.stderr)
def fatal(msg):
"""Fatal error (error + exit)"""
print("ERROR: %s" % msg, file=sys.stderr)
sys.exit(1)
def return_dirs(root):
mydirs = {}
for pdir, dirs, files in os.walk(root):
if pdir not in mydirs:
mydirs[pdir] = files
return mydirs
class Id3TagHandler:
"""Class for handling meta-tags. (Needs mutagen)"""
accept = [
"album",
"album_subtitle",
"albumartist",
"albumartistsort",
"albumsort",
"artist",
"artistsort",
"asin",
"bpm",
"comment",
"compilation",
"composer",
"composersort",
"conductor",
"copyright",
"date",
"discid",
"discnumber",
"encodedby",
"engineer",
"gapless",
"genre",
"grouping",
"isrc",
"label",
"lyricist",
"lyrics",
"mood",
"musicbrainz_albumartistid",
"musicbrainz_albumid",
"musicbrainz_artistid",
"musicbrainz_discid",
"musicbrainz_sortname",
"musicbrainz_trackid",
"musicbrainz_trmid",
"musicip_puid",
"podcast",
"podcasturl",
"releasecountry",
"musicbrainz_albumstatus",
"musicbrainz_albumtype",
"remixer",
"show",
"showsort",
"subtitle",
"title",
"titlesort",
"tracknumber",
"tracktotal",
]
def __init__(self, song):
self.song = song
self.tags = {}
def grab_common(self, handler, convert=None, error=None):
"""Common grabber, starts the handler and applies the tags to self.tags"""
try:
mydict = handler(self.song)
except error:
import traceback
warn("Mutagen failed on %s, no tags available" % self.song)
traceback.print_exc(0)
print(file=sys.stderr)
return
if convert:
convert = {k.lower(): v.lower() for k, v in convert.items()} # Fix convert
for key, val in mydict.items():
key = key.lower()
key = convert and (key in convert and convert[key] or key) or key
if key not in self.accept:
continue
if not convert: # Hack for FLAC, which uses Vorbis tags
pass
elif hasattr(val, "text"):
val = val.text
if convert:
new_val = []
if not isinstance(val, list):
val = [val]
for i in val:
if not isinstance(i, str):
# Convert all invalid values to unicode
try:
new_val.append(str(i))
except UnicodeDecodeError:
warn("Ignoring UnicodeDecodeError in key %s" % key)
new_val.append(str(i, errors="ignore"))
else:
new_val.append(i)
val = new_val
del new_val
self.tags[key] = val
def grab_ape_tags(self):
"""Convert APE tags."""
from mutagen.apev2 import APEv2, error
convert = {"year": "date"}
self.grab_common(APEv2, convert, error)
grab_mpc_tags = grab_ape_tags # Musepack files use APEv2.
grab_wv_tags = grab_ape_tags # WavPack files use APEv2.
def grab_m4a_tags(self):
"""Import MP4 tags handler, set convert and call commonGrab"""
convert = {
"----:com.apple.iTunes:ASIN": "asin",
"----:com.apple.iTunes:MusicBrainz Album Artist Id": "musicbrainz_albumartistid",
"----:com.apple.iTunes:MusicBrainz Album Id": "musicbrainz_albumid",
"----:com.apple.iTunes:MusicBrainz Album Release Country": "releasecountry",
"----:com.apple.iTunes:MusicBrainz Album Status": "musicbrainz_albumstatus",
"----:com.apple.iTunes:MusicBrainz Album Type": "musicbrainz_albumtype",
"----:com.apple.iTunes:MusicBrainz Artist Id": "musicbrainz_artistid",
"----:com.apple.iTunes:MusicBrainz Disc Id": "musicbrainz_discid",
"----:com.apple.iTunes:MusicBrainz TRM Id": "musicbrainz_trmid",
"----:com.apple.iTunes:MusicBrainz Track Id": "musicbrainz_trackid",
"----:com.apple.iTunes:MusicIP PUID": "musicip_puid",
"aART": "albumartist",
"cpil": "compilation",
"cprt": "copyright",
"pcst": "podcast",
"pgap": "gapless",
"purl": "podcasturl",
"soaa": "albumartistsort",
"soal": "albumsort",
"soar": "artistsort",
"soco": "composersort",
"sonm": "titlesort",
"sosn": "showsort",
"trkn": "tracknumber",
"tvsh": "show",
"\xa9ART": "artist",
"\xa9alb": "album",
"\xa9cmt": "comment",
"\xa9day": "date",
"\xa9gen": "genre",
"\xa9grp": "grouping",
"\xa9lyr": "lyrics",
"\xa9nam": "title",
"\xa9too": "encodedby",
"\xa9wrt": "composer",
}
try:
from mutagen.mp4 import MP4, error
except ImportError:
from mutagen.m4a import M4A as MP4, error
self.grab_common(MP4, convert, error)
def grab_wma_tags(self):
"""Import ASF tags handler, set convert and call commonGrab"""
convert = {
"Author": "artist",
"Description": "comment",
"MusicBrainz/Album Artist Id": "musicbrainz_albumartistid",
"MusicBrainz/Album Id": "musicbrainz_albumid",
"MusicBrainz/Album Release Country": "releasecountry",
"MusicBrainz/Album Status": "musicbrainz_albumstatus",
"MusicBrainz/Album Type": "musicbrainz_albumtype",
"MusicBrainz/Artist Id": "musicbrainz_artistid",
"MusicBrainz/Disc Id": "musicbrainz_discid",
"MusicBrainz/TRM Id": "musicbrainz_trmid",
"MusicBrainz/Track Id": "musicbrainz_trackid",
"MusicIP/PUID": "musicip_puid",
"WM/AlbumArtist": "albumartist",
"WM/AlbumArtistSortOrder": "albumartistsort",
"WM/AlbumSortOrder": "albumsort",
"WM/AlbumTitle": "album",
"WM/ArtistSortOrder": "artistsort",
"WM/BeatsPerMinute": "bpm",
"WM/Composer": "composer",
"WM/Conductor": "conductor",
"WM/ContentGroupDescription": "grouping",
"WM/Copyright": "copyright",
"WM/EncodedBy": "encodedby",
"WM/Genre": "genre",
"WM/ISRC": "isrc",
"WM/Lyrics": "lyrics",
"WM/ModifiedBy": "remixer",
"WM/Mood": "mood",
"WM/PartOfSet": "discnumber",
"WM/Producer": "engineer",
"WM/Publisher": "label",
"WM/SetSubTitle": "album_subtitle",
"WM/SubTitle": "subtitle",
"WM/TitleSortOrder": "titlesort",
"WM/TrackNumber": "tracknumber",
"WM/Writer": "lyricist",
"WM/Year": "date",
}
from mutagen.asf import ASF, error
self.grab_common(ASF, convert, error)
def grab_flac_tags(self):
"""Import MP3 tags handler, and call commonGrab"""
from mutagen.flac import FLAC, error
self.grab_common(FLAC, error=error)
def grab_mp3_tags(self):
"""Import MP3 tags handler, and call commonGrab"""
from mutagen.id3 import ID3, error
convert = {
"TPE1": "artist",
"TPE2": "albumartist",
"TPE3": "conductor",
"TPE4": "remixer",
"TCOM": "composer",
"TCON": "genre",
"TALB": "album",
"TIT1": "grouping",
"TIT2": "title",
"TIT3": "subtitle",
"TSST": "discsubtitle",
"TEXT": "lyricist",
"TCMP": "compilation",
"TDRC": "date",
"COMM": "comment",
"TMOO": "mood",
"TMED": "media",
"TBPM": "bpm",
"WOAR": "website",
"TSRC": "isrc",
"TENC": "encodedby",
"TCOP": "copyright",
"TSOA": "albumsort",
"TSOP": "artistsort",
"TSOT": "titlesort",
"TPUB": "label",
"TRCK": "tracknumber",
}
self.grab_common(ID3, convert, error)
def list_if_verbose(self):
info("Meta-tags I will write:")
for key, val in self.tags.items():
if type(val) == list:
info(key + ": " + ",".join(val))
else:
info(key + ": " + val)
class Convert(Id3TagHandler):
"""
Base conversion Class.
__init__ creates some useful attributes,
grabs the id3 tags, and sets a flag to remove files.
Methods are the conversions we can do
"""
def __init__(self, song, conf):
self.device = ""
self.track = ""
Id3TagHandler.__init__(self, song)
self.conf = conf
song_root = os.path.splitext(song)[0] + "."
self.songwav = song_root + "wav"
self.songogg = song_root + "ogg"
self.decoder = ""
def smart_mp3(self):
# initial Code by Marek Palatinus <marek@palatinus.cz>, 2007
# Table of quality = relation between mp3 bitrate and vorbis quality. Source: wikipedia
# quality_table = {45:-1, 64:0, 80:1, 96:2, 112:3, 128:4, 160:5, 192:6, 224:7, 256:8, 320:9, 500:10 }
# log(0.015*bitrate, 1.19) is logaritmic regression of table above. Useful for mp3s in VBR :-).
try:
from mutagen.mp3 import MP3, HeaderNotFoundError
except ImportError:
warn(
"(smartmp3) You dont have mutagen installed. Bitrate detection failed. Using default quality %.02f"
% self.conf.quality
)
return
try:
mp3info = MP3(self.song)
bitrate = mp3info.info.bitrate
except HeaderNotFoundError:
info(
"(smartmp3) File is not an mp3 stream. Using default quality %.02f"
% self.conf.quality
)
return
import math
self.conf.quality = round(
5.383 * math.log(0.01616 * bitrate / 1000.0)
- self.conf.smart_mp3_correction,
2,
)
self.conf.quality = max(self.conf.quality, -1) # Lowest quality is -1
self.conf.quality = min(self.conf.quality, 10) # Highest quality is 10
info("(smartmp3) Detected bitrate: %d kbps" % (bitrate / 1000))
info("(smartmp3) Assumed vorbis quality: %.02f" % self.conf.quality)
def decode(self):
# Used for mplayer
tempwav = "dir2ogg-%s-temp.wav" % os.getpid()
if (
self.decoder not in ("mplayer",)
and not self.conf.no_pipe
and not self.conf.preserve_wav
):
outfile, outfile1 = "-", "/dev/stdout"
use_pipe = 1
else:
outfile = outfile1 = self.songwav
use_pipe = 0
decoder = {
"mpg123": ["mpg123", "-q", "-s", "-w", outfile1, self.song],
"mpg321": ["mpg321", "-q", "-w", outfile, self.song],
"faad": ["faad", "-q", "-o", outfile1, self.song],
"ogg123": ["ogg123", "-q", "-dwav", "-f", outfile, self.song],
"flac": ["flac", "-s", "-o", outfile, "-d", self.song],
"lame": ["lame", "--quiet", "--decode", self.song, outfile],
"mac": ["mac", self.song, outfile, "-d"],
"mpcdec": ["mpcdec", self.song, outfile],
"mplayer": [
"mplayer",
"-really-quiet",
"-vo",
"null",
"-vc",
"dummy",
"-af",
"resample=44100",
"-ao",
"pcm:file=" + tempwav,
self.song,
],
"wvunpack": ["wvunpack", "-q", self.song, "-o", outfile],
"alac-decoder": ["alac-decoder", self.song],
}
if use_pipe:
decoder["mpg123"].remove("-w")
decoder["mpg123"].remove(outfile1)
return True, Popen(decoder[self.decoder], stdout=PIPE)
else:
decoder["mpg123"].remove("-s")
decoder["lame"].remove("--quiet")
retcode = call(decoder[self.decoder])
if self.decoder == "mplayer":
# Move the file for mplayer (which uses tempwav), so it works
# for --preserve-wav.
os.rename(tempwav, self.songwav)
if retcode != 0:
return (False, None)
else:
return (True, None)
def convert(self):
"""Convert with optional smartmp3 feature"""
# (smartmp3) I have to remember default quality for next files
original_quality = self.conf.quality
try:
for ext, pat in FILTERS.items():
if mmatch(self.song, pat) and ext != "wav":
self.decoder = getattr(self.conf, ext + "_decoder")
getattr(self, "grab_%s_tags" % ext)()
if ext == "mp3" and (
self.conf.smart_mp3 or self.conf.smart_mp3_correction
):
self.smart_mp3()
return self.convert_nosmart()
# (smartmp3) Replacing quality by default value
finally:
self.conf.quality = original_quality
def convert_nosmart(self):
""" Convert wav -> ogg."""
info(f'Converting "{self.song}" (using {self.decoder} as decoder)...')
if self.songwav == self.song:
success = True
dec = None
else:
success, dec = self.decode()
if not success:
warn(f'Decoding of "{self.song}" with {self.decoder} failed.')
return False
if dec and self.decoder == "mpg123":
import mutagen
try:
opts = ["-r", "-R", str(mutagen.File(self.song).info.sample_rate)]
if mutagen.File(self.song).info.mode == 3:
opts += ["-C 1"]
except Exception:
warn("An exception occurred while opening the mp3: %s" % self.song)
import traceback
traceback.print_exc()
return False
else:
opts = []
if self.conf.quiet:
opts.append("--quiet")
if dec:
enc = Popen(
[
"oggenc",
"-o",
self.songogg,
"-q",
locale.format_string("%f", self.conf.quality),
"-",
]
+ opts,
stdin=dec.stdout,
)
enc.communicate()
dec.wait()
if dec.returncode < 0:
warn(f'Decoding of "{self.song}" with {self.decoder} failed.')
return False
elif enc.returncode < 0:
warn('Encoding of "%s" failed.' % self.song)
return False
else:
enc = call(
[
"oggenc",
"-o",
self.songogg,
"-q",
locale.format_string("%f", self.conf.quality),
self.songwav,
]
+ opts
)
if enc != 0:
warn('Encoding of "%s" failed.' % self.songwav)
return False
elif not self.conf.preserve_wav and self.song != self.songwav:
os.remove(self.songwav)
if self.tags != {}:
try:
# Add tags to the ogg file
from mutagen.oggvorbis import OggVorbis
myogg = OggVorbis(self.songogg)
myogg.update(self.tags)
myogg.save()
except Exception:
warn("Could not save the tags")
import traceback
traceback.print_exc()
return False
elif self.songwav != self.song:
warn("No tags found...")
if self.conf.delete_input:
os.remove(self.song)
return True
class ConvertDirectory:
"""
This class is just a wrapper for Convert.
Grab the songs to convert, then feed them one
by one to the Convert class.
"""
def __init__(self, conf, directory, files):
""" Decide which files will be converted."""
if os.path.exists(directory) == 0:
fatal('Directory: "%s" not found' % directory)
self.conf = conf
self.directory = directory = os.path.normpath(directory) + os.path.sep
self.songs = sorted(mmatch(files, conf.filters, False))
if conf.verbose:
self.print_if_verbose()
def convert(self):
"""Convert the files"""
return all(
Convert(self.directory + song, self.conf).convert() for song in self.songs
)
def print_if_verbose(self):
""" Echo files to be converted if verbose flag is set."""
info("In %s I am going to convert:" % self.directory)
for song in self.songs:
print(" ", song)
def show_banner():
print(
"dir2ogg %s (%s), converts audio files into ogg vorbis.\n"
% (__version__, __date__)
)
def show_license(*args, **kwargs):
print("Copyright (C) 2007-2009 Julian Andres Klode <jak@jak-linux.org>")
print("Copyright (C) 2003-2006 Darren Kirby <d@badcomputer.org>\n")
print("This program is distributed in the hope that it will be useful,")
print("but WITHOUT ANY WARRANTY; without even the implied warranty of")
print("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the")
print("GNU General Public License for more details.\n")
print("Currently developed by Julian Andres Klode <jak@jak-linux.org>.")
sys.exit(0)
def main():
conf = read_opts()
conf_args, conf = conf[1], conf[0]
rdirs = {}
for path in conf_args:
if not os.path.exists(path):
fatal("Path %r does not exist" % path)
if os.path.isfile(path):
dirname = os.path.dirname(os.path.abspath(path))
try:
rdirs[dirname].append(os.path.basename(path))
except KeyError:
rdirs[dirname] = [os.path.basename(path)]
elif not os.path.isdir(path):
fatal("%r must be a directory or a file." % path)
elif conf.recursive:
rdirs.update(return_dirs(os.path.abspath(path)))
else:
rdirs[os.path.abspath(path)] = os.listdir(path)
success = True
for directory, files in rdirs.items():
if not ConvertDirectory(conf, directory, files).convert():
success = False
if not success:
sys.exit(2)
sys.exit(0)
if __name__ == "__main__":
# mutagen._util sometimes has problems when calling struct.pack().
locale.setlocale(locale.LC_ALL, "")
warnings.filterwarnings(
"ignore",
category=DeprecationWarning,
module="mutagen.*",
message=".*<= number <=.*",
)
main()