{{ message }}
Repository navigation
Expand file tree
/
Copy pathconvert.py
More file actions
799 lines (699 loc) · 27.3 KB
/
Copy pathconvert.py
File metadata and controls
799 lines (699 loc) · 27.3 KB
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
"""Converts tracks or albums to external directory"""
from __future__ import annotations
import logging
import os
import shlex
import subprocess
import tempfile
import threading
from functools import cached_property
from pathlib import Path
from string import Template
from typing import TYPE_CHECKING, Literal, NamedTuple, Protocol
import mediafile
from confuse import ConfigTypeError, Optional
from beets import plugins, ui, util
from beets.exceptions import UserError
from beets.library import Item, parse_query_string
from beets.plugins import BeetsPlugin
from beets.util import pipeline
from beets.util.artresizer import ArtResizer
from beets.util.m3u import M3UFile
from beets.util.pathformats import get_path_formats
from beetsplug._utils import art
if TYPE_CHECKING:
from collections.abc import Iterable
from beets.importer import ImportSession, ImportTask
from beets.library import Album, Library
from beets.util.pathformats import PathFormat
_fs_lock = threading.Lock()
# Keep track of temporary transcoded files for deletion.
_temp_files: list[bytes] = []
class ConvertCLIOpts(Protocol):
album: bool
keep_new: bool
limit: int | None
yes: bool | None
# Some convenient alternate names for formats.
ALIASES = {"windows media": "wma", "vorbis": "ogg"}
LOSSLESS_FORMATS = ["ape", "flac", "alac", "wave", "aiff"]
class FormatCommand(NamedTuple):
command: bytes
ext: bytes
def replace_ext(path: bytes, ext: bytes) -> bytes:
"""Return the path with its extension replaced by `ext`.
The new extension must not contain a leading dot.
"""
ext_dot = b"." + ext
return os.path.splitext(path)[0] + ext_dot
class ConvertPlugin(BeetsPlugin):
def __init__(self) -> None:
super().__init__()
self.config.add(
{
"dest": None,
"pretend": False,
"link": False,
"hardlink": False,
"threads": os.cpu_count(),
"format": "mp3",
"id3v23": "inherit",
"write_metadata": True,
"formats": {
"aac": {
"command": (
"ffmpeg -i $source -y -vn -acodec aac -aq 1 $dest"
),
"extension": "m4a",
},
"alac": {
"command": (
"ffmpeg -i $source -y -vn -acodec alac $dest"
),
"extension": "m4a",
},
"flac": "ffmpeg -i $source -y -vn -acodec flac $dest",
"mp3": "ffmpeg -i $source -y -vn -aq 2 $dest",
"opus": (
"ffmpeg -i $source -y -vn -acodec libopus -ab 96k $dest"
),
"ogg": (
"ffmpeg -i $source -y -vn -acodec libvorbis -aq 3 $dest"
),
"wma": "ffmpeg -i $source -y -vn -acodec wmav2 -vn $dest",
},
"max_bitrate": None,
"auto": False,
"auto_keep": False,
"tmpdir": None,
"quiet": False,
"embed": True,
"paths": {},
"no_convert": "",
"never_convert_lossy_files": False,
"copy_album_art": False,
"album_art_maxwidth": 0,
"delete_originals": False,
"playlist": None,
"force": False,
"refresh": False,
"keep_new": False,
}
)
self.early_import_stages = [self.auto_convert, self.auto_convert_keep]
self.register_listener("import_task_files", self._cleanup)
def commands(self) -> list[ui.Subcommand]:
cmd = ui.Subcommand("convert", help="convert to external location")
cmd.parser.add_option(
"-p",
"--pretend",
action="store_true",
default=self.config["pretend"].get(),
help="show actions but do nothing",
)
cmd.parser.add_option(
"-t",
"--threads",
action="store",
type="int",
default=self.config["threads"].get(),
help=(
"change the number of threads, defaults to maximum available"
" processors"
),
)
cmd.parser.add_option(
"-r",
"--refresh",
action="store_true",
dest="refresh",
default=self.config["refresh"].get(),
help="reconvert if original file is newer than converted file",
)
cmd.parser.add_option(
"-k",
"--keep-new",
action="store_true",
dest="keep_new",
default=self.config["keep_new"].get(),
help="keep only the converted and move the old files",
)
cmd.parser.add_option(
"-d",
"--dest",
action="store",
default=self.config["dest"].get(),
help="set the destination directory",
)
cmd.parser.add_option(
"-f",
"--format",
action="store",
default=self.config["format"].get(),
help="set the target format of the tracks",
)
cmd.parser.add_option(
"-y",
"--yes",
action="store_true",
help="do not ask for confirmation",
)
cmd.parser.add_option(
"-l",
"--link",
action="store_true",
default=self.config["link"].get(),
help="symlink files that do not need transcoding.",
)
cmd.parser.add_option(
"-H",
"--hardlink",
action="store_true",
default=self.config["hardlink"].get(),
help=(
"hardlink files that do not need transcoding. Overrides --link."
),
)
cmd.parser.add_option(
"-m",
"--playlist",
action="store",
default=self.config["playlist"].get(),
help=(
"create an m3u8 playlist file containing the converted files."
" The playlist file will be saved below the destination"
" directory, thus PLAYLIST could be a file name or a relative"
" path. To ensure a working playlist when transferred to a"
" different computer, or opened from an external drive,"
" relative paths pointing to media files will be used."
),
)
cmd.parser.add_option(
"-F",
"--force",
action="store_true",
default=self.config["force"].get(),
help=(
"force transcoding. Ignores no_convert, "
"never_convert_lossy_files, and max_bitrate"
),
)
cmd.parser.add_album_option()
cmd.parser.add_limit_option(flags=("--limit",))
cmd.func = self.convert_func
return [cmd]
@cached_property
def dest(self) -> bytes:
dest = self.config["dest"].get()
if not dest:
raise UserError("no convert destination set")
return util.bytestring_path(dest)
@cached_property
def threads(self) -> int:
return self.config["threads"].get(int)
@cached_property
def path_formats(self) -> list[PathFormat]:
return get_path_formats(self.config["paths"])
@cached_property
def fmt(self) -> str:
return self.config["format"].as_str().lower()
@cached_property
def playlist(self) -> bytes | None:
if (playlist := self.config["playlist"].get()) is not None:
return os.path.join(self.dest, util.bytestring_path(playlist))
return None
@cached_property
def pretend(self) -> bool:
return self.config["pretend"].get(bool)
@cached_property
def force(self) -> bool:
return self.config["force"].get(bool)
@cached_property
def refresh(self) -> bool:
return self.config["refresh"].get(bool)
@cached_property
def hardlink(self) -> bool:
return self.config["hardlink"].get(bool)
@cached_property
def link(self) -> bool:
return not self.hardlink and self.config["link"].get(bool)
@cached_property
def command(self) -> FormatCommand:
"""Return the command template and the extension from the config."""
fmt = ALIASES.get(self.fmt, self.fmt)
try:
format_info = self.config["formats"][fmt].get(dict)
command = format_info["command"]
extension = format_info.get("extension", fmt)
except KeyError:
raise UserError(f'convert: format {fmt} needs the "command" field')
except ConfigTypeError:
command = self.config["formats"][fmt].get(str)
extension = fmt
# Convenience and backwards-compatibility shortcuts.
keys = self.config.keys()
if "command" in keys:
command = self.config["command"].as_str()
elif "opts" in keys:
# Undocumented option for backwards compatibility with < 1.3.1.
command = (
f"ffmpeg -i $source -y {self.config['opts'].as_str()} $dest"
)
if "extension" in keys:
extension = self.config["extension"].as_str()
return FormatCommand(command.encode("utf-8"), extension.encode("utf-8"))
def auto_convert(self, session: ImportSession, task: ImportTask) -> None:
if self.config["auto"]:
util.par_map(
lambda item: self.convert_on_import(session.lib, item),
task.imported_items(),
)
def auto_convert_keep(
self, session: ImportSession, task: ImportTask
) -> None:
if self.config["auto_keep"]:
items = task.imported_items()
# Filter items based on should_transcode function
items = [item for item in items if self.should_transcode(item)]
self._parallel_convert(items, keep_new=False)
# Utilities converted from functions to methods on logging overhaul
def encode(
self, command_bytes: bytes, source_bytes: bytes, dest_bytes: bytes
) -> None:
"""Encode source to destination using given command template.
Raises `subprocess.CalledProcessError` if the command exited with a
non-zero status code.
"""
pretend, quiet = self.pretend, self.config["quiet"].get(bool)
if not quiet and not pretend:
self._log.info("Encoding {}", util.displayable_path(source_bytes))
command = os.fsdecode(command_bytes)
source = os.fsdecode(source_bytes)
dest = os.fsdecode(dest_bytes)
# Substitute $source and $dest in the argument list.
args = shlex.split(command)
encode_cmd = []
for i, arg in enumerate(args):
args[i] = Template(arg).safe_substitute(
{"source": source, "dest": dest}
)
encode_cmd.append(os.fsdecode(args[i]))
if pretend:
self._log.info("{}", " ".join(args))
return
try:
util.command_output(encode_cmd)
except subprocess.CalledProcessError as exc:
# Something went wrong (probably Ctrl+C), remove temporary files
self._log.info(
"Encoding {} failed. Cleaning up...",
util.displayable_path(source),
)
self._log.debug(
"Command {0} exited with status {1.returncode}: {1.output}",
args,
exc,
)
util.remove(dest)
util.prune_dirs(os.path.dirname(dest))
raise
except OSError as exc:
raise UserError(
f"convert: couldn't invoke {' '.join(args)!r}: {exc}"
)
if not quiet and not pretend:
self._log.info(
"Finished encoding {}", util.displayable_path(source)
)
def in_no_convert(self, item: Item) -> bool:
no_convert_query = self.config["no_convert"].as_str()
if no_convert_query:
query, _ = parse_query_string(no_convert_query, Item)
return query.match(item)
return False
def should_transcode(self, item: Item) -> bool:
"""Determine whether the item should be transcoded as part of
conversion (i.e., its bitrate is high or it has the wrong format).
If ``force`` is True, safety checks like ``no_convert`` and
``never_convert_lossy_files`` are ignored and the item is always
transcoded.
"""
if self.force:
return True
if self.in_no_convert(item) or (
self.config["never_convert_lossy_files"].get(bool)
and item.format.lower() not in LOSSLESS_FORMATS
):
return False
maxbr = self.config["max_bitrate"].get(Optional(int))
if maxbr is not None and item.bitrate >= 1000 * maxbr:
return True
return self.fmt != item.format.lower()
def get_item_destination(self, item: Item) -> bytes:
extension = (
os.fsdecode(self.command.ext)
if (
self.should_transcode(item)
and not self.config["keep_new"].get(bool)
)
else None
)
return item.destination(
basedir=self.dest,
path_formats=self.path_formats,
extension=extension,
)
@pipeline.mutator_stage
def convert_item(self, keep_new: bool, item: Item) -> None:
"""Convert an Item from the library."""
pretend, link, hardlink, refresh = (
self.pretend,
self.link,
self.hardlink,
self.refresh,
)
command, ext = self.command
dest = self.get_item_destination(item)
# Ensure that desired item is readable before processing it. Needed
# to avoid any side-effect of the conversion (linking, keep_new,
# refresh) if we already know that it will fail.
try:
mediafile.MediaFile(util.syspath(item.path))
except mediafile.UnreadableFileError as exc:
self._log.error("Could not open file to convert: {}", exc)
return
# When keeping the new file in the library, we first move the
# current (pristine) file to the destination. We'll then copy it
# back to its old path or transcode it to a new path.
if keep_new:
original = dest
converted = item.path
if self.should_transcode(item):
converted = replace_ext(converted, ext)
else:
original = item.path
if self.should_transcode(item):
dest = replace_ext(dest, ext)
converted = dest
# If the destination file exists, we have to choose between:
# 1) Skipping current conversion
# 2) Removing the target file to start a fresh conversion
if os.path.exists(util.syspath(dest)):
# Test to skip the conversion, whether because:
# 1) `refresh` is false (default)
# 2) `keep_new` is true (incompatible with `refresh`)
# 3) The original file is older than the destination file
if (
not refresh
or keep_new
or os.path.getmtime(item.path) <= os.path.getmtime(dest)
):
self._log.info(
"Skipping {.filepath} (destination file exists)", item
)
if keep_new and refresh:
self._log.debug(
"Skipping refresh: not supported with keep_new"
)
return
# If reached, `refresh` is true, `keep_new` is false, and original file
# is newer than the destination file: we should consider deleting the
# existing destination files. If we pretend to convert files, only inform
# user about what would be removed without removing anything.
if pretend:
self._log.info(
"Pretend to remove {0} (original file modified)",
util.displayable_path(dest),
)
# Otherwise, actually remove the destination file
else:
self._log.info(
"Removing {0} (original file modified)",
util.displayable_path(dest),
)
util.remove(dest)
# Ensure that only one thread tries to create directories at a
# time. (The existence check is not atomic with the directory
# creation inside this function.)
if not pretend:
with _fs_lock:
util.mkdirall(dest)
if keep_new:
if pretend:
self._log.info(
"Pretend to move {.filepath} to {}",
item,
util.displayable_path(original),
)
else:
self._log.info("Moving to {}", util.displayable_path(original))
util.move(item.path, original)
if self.should_transcode(item):
linked = False
try:
self.encode(command, original, converted)
except subprocess.CalledProcessError:
return
else:
linked = link or hardlink
if pretend:
msg = "ln" if hardlink else ("ln -s" if link else "cp")
self._log.info(
"{} {} {}",
msg,
util.displayable_path(original),
util.displayable_path(converted),
)
else:
# No transcoding necessary.
msg = (
"Hardlinking"
if hardlink
else ("Linking" if link else "Copying")
)
self._log.info("{} {.filepath}", msg, item)
if hardlink:
util.hardlink(original, converted)
elif link:
util.link(original, converted)
else:
util.copy(original, converted)
if pretend:
return
id3v23: bool | Literal["inherit"] | None = self.config[
"id3v23"
].as_choice([True, False, "inherit"])
if id3v23 == "inherit":
id3v23 = None
# Write tags from the database to the file if requested
if self.config["write_metadata"].get(bool):
item.try_write(path=converted, id3v23=id3v23)
if keep_new:
# If we're keeping the transcoded file, read it again (after
# writing) to get new bitrate, duration, etc.
item.path = converted
item.read()
item.store() # Store new path and audio data.
if self.config["embed"] and not linked:
album = item._cached_album
if album and (path := album.art_filepath):
maxwidth = self._get_art_resize(path)
self._log.debug(
"embedding album art from {.art_filepath}", album
)
art.embed_item(
self._log,
item,
path,
maxwidth,
itempath=converted,
id3v23=id3v23,
)
if keep_new:
plugins.send("after_convert", item=item, dest=dest, keepnew=True)
else:
plugins.send(
"after_convert", item=item, dest=converted, keepnew=False
)
def copy_album_art(self, album: Album) -> None:
"""Copies or converts the associated cover art of the album. Album must
have at least one track.
"""
if not album or not album.artpath or not album.art_filepath:
return
# The stored art path may point to a missing file (e.g. the cover
# lives in the album's root directory rather than a per-disc one).
if not os.path.isfile(util.syspath(album.artpath)):
self._log.info(
"Skipping {.art_filepath} (source file not found)", album
)
return
album_item = album.items().get()
# Album shouldn't be empty.
if not album_item:
return
# Get the destination of the first item (track) of the album, we use
# this function to format the path accordingly to path_formats.
dest = self.get_item_destination(album_item)
# Remove item from the path.
dest = os.path.join(*util.components(dest)[:-1])
dest = album.art_destination(album.artpath, item_dir=dest)
if album.artpath == dest:
return
if not (pretend := self.pretend):
util.mkdirall(dest)
if os.path.exists(util.syspath(dest)):
self._log.info(
"Skipping {.art_filepath} (destination file exists)", album
)
return
dest_path = Path(os.fsdecode(dest))
# Decide whether we need to resize the cover-art image.
maxwidth = self._get_art_resize(album.art_filepath)
# Either copy or resize (while copying) the image.
if maxwidth is not None:
self._log.info(
"Resizing cover art from {.art_filepath} to {}",
album,
dest_path,
)
if not pretend:
ArtResizer.shared.resize(
maxwidth, album.art_filepath, dest_path
)
else:
link, hardlink = self.link, self.hardlink
if pretend:
msg = "ln" if hardlink else ("ln -s" if link else "cp")
self._log.info("{} {.art_filepath} {}", msg, album, dest_path)
else:
msg = (
"Hardlinking"
if hardlink
else ("Linking" if link else "Copying")
)
self._log.info(
"{} cover art from {.art_filepath} to {}",
msg,
album,
dest_path,
)
if hardlink:
util.hardlink(album.artpath, dest)
elif link:
util.link(album.artpath, dest)
else:
util.copy(album.artpath, dest)
def convert_func(
self, lib: Library, opts: ConvertCLIOpts, args: list[str]
) -> None:
self.config.set(vars(opts))
pretend = self.pretend
if opts.album:
albums = lib.albums(args, limit=opts.limit)
items = [i for a in albums for i in a.items()]
if not pretend:
for a in albums:
ui.print_(format(a, ""))
else:
items = list(lib.items(args, limit=opts.limit))
if not pretend:
for i in items:
ui.print_(format(i, ""))
if not items:
self._log.error("Empty query result.")
return
if not (pretend or opts.yes or ui.input_yn("Convert? (Y/n)")):
return
if opts.album and self.config["copy_album_art"]:
for album in albums:
self.copy_album_art(album)
# If the user supplied a playlist name, create a playlist for files
# copied to the destination.
pl_normpath = None
items_paths = None
if playlist := self.playlist:
# Playlist paths are understood as relative to the dest directory.
pl_normpath = util.normpath(playlist)
pl_dir = os.path.dirname(pl_normpath)
items_paths = []
for item in items:
item_path = self.get_item_destination(item)
# When keeping new files in the library, destination paths
# keep original files and extensions.
if not opts.keep_new and self.should_transcode(item):
item_path = replace_ext(item_path, self.command.ext)
items_paths.append(os.path.relpath(item_path, pl_dir))
self._parallel_convert(
items, keep_new=self.config["keep_new"].get(bool)
)
if playlist:
self._log.info("Creating playlist file {}", pl_normpath)
if not pretend:
m3ufile = M3UFile(playlist)
m3ufile.set_contents(items_paths)
m3ufile.write()
def convert_on_import(self, _: Library, item: Item) -> None:
"""Transcode a file automatically after it is imported into the
library.
"""
if self.should_transcode(item):
command, ext = self.command
# Create a temporary file for the conversion.
tmpdir = self.config["tmpdir"].get()
if tmpdir:
tmpdir = util.bytestring_path(tmpdir)
fd, dest = tempfile.mkstemp(b"." + ext, dir=tmpdir)
os.close(fd)
dest = util.bytestring_path(dest)
_temp_files.append(dest) # Delete the transcode later.
# Convert.
try:
self.encode(command, item.path, dest)
except subprocess.CalledProcessError:
return
# Change the newly-imported database entry to point to the
# converted file.
source_path = item.path
item.path = dest
item.write()
item.read() # Load new audio information data.
item.store()
if self.config["delete_originals"]:
self._log.log(
logging.DEBUG if self.config["quiet"] else logging.INFO,
"Removing original file {}",
source_path,
)
util.remove(source_path, False)
def _get_art_resize(self, artpath: Path) -> int | None:
"""For a given piece of album art, determine whether or not it needs
to be resized according to the user's settings. If so, returns the
new size. If not, returns None.
"""
newwidth = None
if self.config["album_art_maxwidth"]:
maxwidth = self.config["album_art_maxwidth"].get(int)
size = ArtResizer.shared.get_size(artpath)
self._log.debug("image size: {}", size)
if size:
if size[0] > maxwidth:
newwidth = maxwidth
else:
self._log.warning(
"Could not get size of image (please see "
"documentation for dependencies)."
)
return newwidth
def _cleanup(self, task: ImportTask, session: ImportSession) -> None:
for path in task.old_paths:
if path in _temp_files:
if os.path.isfile(util.syspath(path)):
util.remove(path)
_temp_files.remove(path)
def _parallel_convert(self, items: Iterable[Item], keep_new: bool) -> None:
"""Run the convert_item function for every items on as many thread as
defined in threads
"""
convert = [self.convert_item(keep_new) for _ in range(self.threads)]
pipeline.Pipeline([iter(items), convert]).run_parallel()
You can’t perform that action at this time.
