Debian Codegraph @

beetsplug/convert.py

raw
1 """Converts tracks or albums to external directory"""
2
3 from __future__ import annotations
4
5 import logging
6 import os
7 import shlex
8 import subprocess
9 import tempfile
10 import threading
11 from functools import cached_property
12 from string import Template
13 from typing import TYPE_CHECKING, Literal, NamedTuple, Protocol
14
15 import mediafile
16 from confuse import ConfigTypeError, Optional
17
18 from beets import plugins, ui, util
19 from beets.exceptions import UserError
20 from beets.library import Item, parse_query_string
21 from beets.plugins import BeetsPlugin
22 from beets.util import pipeline
23 from beets.util.artresizer import ArtResizer
24 from beets.util.m3u import M3UFile
25 from beets.util.pathformats import get_path_formats
26 from beetsplug._utils import art
27
28 if TYPE_CHECKING:
29 from collections.abc import Iterable
30
31 from beets.importer import ImportSession, ImportTask
32 from beets.library import Album, Library
33 from beets.util.pathformats import PathFormat
34
35 _fs_lock = threading.Lock()
36 # Keep track of temporary transcoded files for deletion.
37 _temp_files: list[bytes] = []
38
39
40 class ConvertCLIOpts(Protocol):
41 album: bool
42 keep_new: bool
43 yes: bool | None
44
45
46 # Some convenient alternate names for formats.
47 ALIASES = {"windows media": "wma", "vorbis": "ogg"}
48
49 LOSSLESS_FORMATS = ["ape", "flac", "alac", "wave", "aiff"]
50
51
52 class FormatCommand(NamedTuple):
53 command: bytes
54 ext: bytes
55
56
57 def replace_ext(path: bytes, ext: bytes) -> bytes:
58 """Return the path with its extension replaced by `ext`.
59
60 The new extension must not contain a leading dot.
61 """
62 ext_dot = b"." + ext
63 return os.path.splitext(path)[0] + ext_dot
64
65
66 class ConvertPlugin(BeetsPlugin):
67 def __init__(self) -> None:
68 super().__init__()
69 self.config.add(
70 {
71 "dest": None,
72 "pretend": False,
73 "link": False,
74 "hardlink": False,
75 "threads": os.cpu_count(),
76 "format": "mp3",
77 "id3v23": "inherit",
78 "write_metadata": True,
79 "formats": {
80 "aac": {
81 "command": (
82 "ffmpeg -i $source -y -vn -acodec aac -aq 1 $dest"
83 ),
84 "extension": "m4a",
85 },
86 "alac": {
87 "command": (
88 "ffmpeg -i $source -y -vn -acodec alac $dest"
89 ),
90 "extension": "m4a",
91 },
92 "flac": "ffmpeg -i $source -y -vn -acodec flac $dest",
93 "mp3": "ffmpeg -i $source -y -vn -aq 2 $dest",
94 "opus": (
95 "ffmpeg -i $source -y -vn -acodec libopus -ab 96k $dest"
96 ),
97 "ogg": (
98 "ffmpeg -i $source -y -vn -acodec libvorbis -aq 3 $dest"
99 ),
100 "wma": "ffmpeg -i $source -y -vn -acodec wmav2 -vn $dest",
101 },
102 "max_bitrate": None,
103 "auto": False,
104 "auto_keep": False,
105 "tmpdir": None,
106 "quiet": False,
107 "embed": True,
108 "paths": {},
109 "no_convert": "",
110 "never_convert_lossy_files": False,
111 "copy_album_art": False,
112 "album_art_maxwidth": 0,
113 "delete_originals": False,
114 "playlist": None,
115 "force": False,
116 "refresh": False,
117 "keep_new": False,
118 }
119 )
120 self.early_import_stages = [self.auto_convert, self.auto_convert_keep]
121
122 self.register_listener("import_task_files", self._cleanup)
123
124 def commands(self) -> list[ui.Subcommand]:
125 cmd = ui.Subcommand("convert", help="convert to external location")
126 cmd.parser.add_option(
127 "-p",
128 "--pretend",
129 action="store_true",
130 default=self.config["pretend"].get(),
131 help="show actions but do nothing",
132 )
133 cmd.parser.add_option(
134 "-t",
135 "--threads",
136 action="store",
137 type="int",
138 default=self.config["threads"].get(),
139 help=(
140 "change the number of threads, defaults to maximum available"
141 " processors"
142 ),
143 )
144 cmd.parser.add_option(
145 "-r",
146 "--refresh",
147 action="store_true",
148 dest="refresh",
149 default=self.config["refresh"].get(),
150 help="reconvert if original file is newer than converted file",
151 )
152 cmd.parser.add_option(
153 "-k",
154 "--keep-new",
155 action="store_true",
156 dest="keep_new",
157 default=self.config["keep_new"].get(),
158 help="keep only the converted and move the old files",
159 )
160 cmd.parser.add_option(
161 "-d",
162 "--dest",
163 action="store",
164 default=self.config["dest"].get(),
165 help="set the destination directory",
166 )
167 cmd.parser.add_option(
168 "-f",
169 "--format",
170 action="store",
171 default=self.config["format"].get(),
172 help="set the target format of the tracks",
173 )
174 cmd.parser.add_option(
175 "-y",
176 "--yes",
177 action="store_true",
178 help="do not ask for confirmation",
179 )
180 cmd.parser.add_option(
181 "-l",
182 "--link",
183 action="store_true",
184 default=self.config["link"].get(),
185 help="symlink files that do not need transcoding.",
186 )
187 cmd.parser.add_option(
188 "-H",
189 "--hardlink",
190 action="store_true",
191 default=self.config["hardlink"].get(),
192 help=(
193 "hardlink files that do not need transcoding. Overrides --link."
194 ),
195 )
196 cmd.parser.add_option(
197 "-m",
198 "--playlist",
199 action="store",
200 default=self.config["playlist"].get(),
201 help=(
202 "create an m3u8 playlist file containing the converted files."
203 " The playlist file will be saved below the destination"
204 " directory, thus PLAYLIST could be a file name or a relative"
205 " path. To ensure a working playlist when transferred to a"
206 " different computer, or opened from an external drive,"
207 " relative paths pointing to media files will be used."
208 ),
209 )
210 cmd.parser.add_option(
211 "-F",
212 "--force",
213 action="store_true",
214 default=self.config["force"].get(),
215 help=(
216 "force transcoding. Ignores no_convert, "
217 "never_convert_lossy_files, and max_bitrate"
218 ),
219 )
220 cmd.parser.add_album_option()
221 cmd.func = self.convert_func
222 return [cmd]
223
224 @cached_property
225 def dest(self) -> bytes:
226 dest = self.config["dest"].get()
227 if not dest:
228 raise UserError("no convert destination set")
229 return util.bytestring_path(dest)
230
231 @cached_property
232 def threads(self) -> int:
233 return self.config["threads"].get(int)
234
235 @cached_property
236 def path_formats(self) -> list[PathFormat]:
237 return get_path_formats(self.config["paths"])
238
239 @cached_property
240 def fmt(self) -> str:
241 return self.config["format"].as_str().lower()
242
243 @cached_property
244 def playlist(self) -> bytes | None:
245 if (playlist := self.config["playlist"].get()) is not None:
246 return os.path.join(self.dest, util.bytestring_path(playlist))
247
248 return None
249
250 @cached_property
251 def pretend(self) -> bool:
252 return self.config["pretend"].get(bool)
253
254 @cached_property
255 def force(self) -> bool:
256 return self.config["force"].get(bool)
257
258 @cached_property
259 def refresh(self) -> bool:
260 return self.config["refresh"].get(bool)
261
262 @cached_property
263 def hardlink(self) -> bool:
264 return self.config["hardlink"].get(bool)
265
266 @cached_property
267 def link(self) -> bool:
268 return not self.hardlink and self.config["link"].get(bool)
269
270 @cached_property
271 def command(self) -> FormatCommand:
272 """Return the command template and the extension from the config."""
273 fmt = ALIASES.get(self.fmt, self.fmt)
274
275 try:
276 format_info = self.config["formats"][fmt].get(dict)
277 command = format_info["command"]
278 extension = format_info.get("extension", fmt)
279 except KeyError:
280 raise UserError(f'convert: format {fmt} needs the "command" field')
281 except ConfigTypeError:
282 command = self.config["formats"][fmt].get(str)
283 extension = fmt
284
285 # Convenience and backwards-compatibility shortcuts.
286 keys = self.config.keys()
287 if "command" in keys:
288 command = self.config["command"].as_str()
289 elif "opts" in keys:
290 # Undocumented option for backwards compatibility with < 1.3.1.
291 command = (
292 f"ffmpeg -i $source -y {self.config['opts'].as_str()} $dest"
293 )
294 if "extension" in keys:
295 extension = self.config["extension"].as_str()
296
297 return FormatCommand(command.encode("utf-8"), extension.encode("utf-8"))
298
299 def auto_convert(self, session: ImportSession, task: ImportTask) -> None:
300 if self.config["auto"]:
301 util.par_map(
302 lambda item: self.convert_on_import(session.lib, item),
303 task.imported_items(),
304 )
305
306 def auto_convert_keep(
307 self, session: ImportSession, task: ImportTask
308 ) -> None:
309 if self.config["auto_keep"]:
310 items = task.imported_items()
311
312 # Filter items based on should_transcode function
313 items = [item for item in items if self.should_transcode(item)]
314
315 self._parallel_convert(items, keep_new=False)
316
317 # Utilities converted from functions to methods on logging overhaul
318
319 def encode(
320 self, command_bytes: bytes, source_bytes: bytes, dest_bytes: bytes
321 ) -> None:
322 """Encode source to destination using given command template.
323
324 Raises `subprocess.CalledProcessError` if the command exited with a
325 non-zero status code.
326 """
327 pretend, quiet = self.pretend, self.config["quiet"].get(bool)
328
329 if not quiet and not pretend:
330 self._log.info("Encoding {}", util.displayable_path(source_bytes))
331
332 command = os.fsdecode(command_bytes)
333 source = os.fsdecode(source_bytes)
334 dest = os.fsdecode(dest_bytes)
335
336 # Substitute $source and $dest in the argument list.
337 args = shlex.split(command)
338 encode_cmd = []
339 for i, arg in enumerate(args):
340 args[i] = Template(arg).safe_substitute(
341 {"source": source, "dest": dest}
342 )
343 encode_cmd.append(os.fsdecode(args[i]))
344
345 if pretend:
346 self._log.info("{}", " ".join(args))
347 return
348
349 try:
350 util.command_output(encode_cmd)
351 except subprocess.CalledProcessError as exc:
352 # Something went wrong (probably Ctrl+C), remove temporary files
353 self._log.info(
354 "Encoding {} failed. Cleaning up...",
355 util.displayable_path(source),
356 )
357 self._log.debug(
358 "Command {0} exited with status {1.returncode}: {1.output}",
359 args,
360 exc,
361 )
362 util.remove(dest)
363 util.prune_dirs(os.path.dirname(dest))
364 raise
365 except OSError as exc:
366 raise UserError(
367 f"convert: couldn't invoke {' '.join(args)!r}: {exc}"
368 )
369
370 if not quiet and not pretend:
371 self._log.info(
372 "Finished encoding {}", util.displayable_path(source)
373 )
374
375 def in_no_convert(self, item: Item) -> bool:
376 no_convert_query = self.config["no_convert"].as_str()
377
378 if no_convert_query:
379 query, _ = parse_query_string(no_convert_query, Item)
380 return query.match(item)
381 return False
382
383 def should_transcode(self, item: Item) -> bool:
384 """Determine whether the item should be transcoded as part of
385 conversion (i.e., its bitrate is high or it has the wrong format).
386
387 If ``force`` is True, safety checks like ``no_convert`` and
388 ``never_convert_lossy_files`` are ignored and the item is always
389 transcoded.
390 """
391 if self.force:
392 return True
393 if self.in_no_convert(item) or (
394 self.config["never_convert_lossy_files"].get(bool)
395 and item.format.lower() not in LOSSLESS_FORMATS
396 ):
397 return False
398 maxbr = self.config["max_bitrate"].get(Optional(int))
399 if maxbr is not None and item.bitrate >= 1000 * maxbr:
400 return True
401 return self.fmt != item.format.lower()
402
403 def get_item_destination(self, item: Item) -> bytes:
404 extension = (
405 os.fsdecode(self.command.ext)
406 if (
407 self.should_transcode(item)
408 and not self.config["keep_new"].get(bool)
409 )
410 else None
411 )
412 return item.destination(
413 basedir=self.dest,
414 path_formats=self.path_formats,
415 extension=extension,
416 )
417
418 @pipeline.mutator_stage
419 def convert_item(self, keep_new: bool, item: Item) -> None:
420 """Convert an Item from the library."""
421 pretend, link, hardlink, refresh = (
422 self.pretend,
423 self.link,
424 self.hardlink,
425 self.refresh,
426 )
427 command, ext = self.command
428
429 dest = self.get_item_destination(item)
430
431 # Ensure that desired item is readable before processing it. Needed
432 # to avoid any side-effect of the conversion (linking, keep_new,
433 # refresh) if we already know that it will fail.
434 try:
435 mediafile.MediaFile(util.syspath(item.path))
436 except mediafile.UnreadableFileError as exc:
437 self._log.error("Could not open file to convert: {}", exc)
438 return
439
440 # When keeping the new file in the library, we first move the
441 # current (pristine) file to the destination. We'll then copy it
442 # back to its old path or transcode it to a new path.
443 if keep_new:
444 original = dest
445 converted = item.path
446 if self.should_transcode(item):
447 converted = replace_ext(converted, ext)
448 else:
449 original = item.path
450 if self.should_transcode(item):
451 dest = replace_ext(dest, ext)
452 converted = dest
453
454 # If the destination file exists, we have to choose between:
455 # 1) Skipping current conversion
456 # 2) Removing the target file to start a fresh conversion
457 if os.path.exists(util.syspath(dest)):
458 # Test to skip the conversion, whether because:
459 # 1) `refresh` is false (default)
460 # 2) `keep_new` is true (incompatible with `refresh`)
461 # 3) The original file is older than the destination file
462 if (
463 not refresh
464 or keep_new
465 or os.path.getmtime(item.path) <= os.path.getmtime(dest)
466 ):
467 self._log.info(
468 "Skipping {.filepath} (destination file exists)", item
469 )
470 if keep_new and refresh:
471 self._log.debug(
472 "Skipping refresh: not supported with keep_new"
473 )
474 return
475 # If reached, `refresh` is true, `keep_new` is false, and original file
476 # is newer than the destination file: we should consider deleting the
477 # existing destination files. If we pretend to convert files, only inform
478 # user about what would be removed without removing anything.
479 if pretend:
480 self._log.info(
481 "Pretend to remove {0} (original file modified)",
482 util.displayable_path(dest),
483 )
484 # Otherwise, actually remove the destination file
485 else:
486 self._log.info(
487 "Removing {0} (original file modified)",
488 util.displayable_path(dest),
489 )
490 util.remove(dest)
491
492 # Ensure that only one thread tries to create directories at a
493 # time. (The existence check is not atomic with the directory
494 # creation inside this function.)
495 if not pretend:
496 with _fs_lock:
497 util.mkdirall(dest)
498
499 if keep_new:
500 if pretend:
501 self._log.info(
502 "Pretend to move {.filepath} to {}",
503 item,
504 util.displayable_path(original),
505 )
506 else:
507 self._log.info("Moving to {}", util.displayable_path(original))
508 util.move(item.path, original)
509
510 if self.should_transcode(item):
511 linked = False
512 try:
513 self.encode(command, original, converted)
514 except subprocess.CalledProcessError:
515 return
516 else:
517 linked = link or hardlink
518 if pretend:
519 msg = "ln" if hardlink else ("ln -s" if link else "cp")
520
521 self._log.info(
522 "{} {} {}",
523 msg,
524 util.displayable_path(original),
525 util.displayable_path(converted),
526 )
527 else:
528 # No transcoding necessary.
529 msg = (
530 "Hardlinking"
531 if hardlink
532 else ("Linking" if link else "Copying")
533 )
534
535 self._log.info("{} {.filepath}", msg, item)
536
537 if hardlink:
538 util.hardlink(original, converted)
539 elif link:
540 util.link(original, converted)
541 else:
542 util.copy(original, converted)
543
544 if pretend:
545 return
546
547 id3v23: bool | Literal["inherit"] | None = self.config[
548 "id3v23"
549 ].as_choice([True, False, "inherit"])
550 if id3v23 == "inherit":
551 id3v23 = None
552
553 # Write tags from the database to the file if requested
554 if self.config["write_metadata"].get(bool):
555 item.try_write(path=converted, id3v23=id3v23)
556
557 if keep_new:
558 # If we're keeping the transcoded file, read it again (after
559 # writing) to get new bitrate, duration, etc.
560 item.path = converted
561 item.read()
562 item.store() # Store new path and audio data.
563
564 if self.config["embed"] and not linked:
565 album = item._cached_album
566 if album and album.artpath:
567 maxwidth = self._get_art_resize(album.artpath)
568 self._log.debug(
569 "embedding album art from {.art_filepath}", album
570 )
571 art.embed_item(
572 self._log,
573 item,
574 album.artpath,
575 maxwidth,
576 itempath=converted,
577 id3v23=id3v23,
578 )
579
580 if keep_new:
581 plugins.send("after_convert", item=item, dest=dest, keepnew=True)
582 else:
583 plugins.send(
584 "after_convert", item=item, dest=converted, keepnew=False
585 )
586
587 def copy_album_art(self, album: Album) -> None:
588 """Copies or converts the associated cover art of the album. Album must
589 have at least one track.
590 """
591 if not album or not album.artpath:
592 return
593
594 # The stored art path may point to a missing file (e.g. the cover
595 # lives in the album's root directory rather than a per-disc one).
596 if not os.path.isfile(util.syspath(album.artpath)):
597 self._log.info(
598 "Skipping {.art_filepath} (source file not found)", album
599 )
600 return
601
602 album_item = album.items().get()
603 # Album shouldn't be empty.
604 if not album_item:
605 return
606
607 # Get the destination of the first item (track) of the album, we use
608 # this function to format the path accordingly to path_formats.
609 dest = self.get_item_destination(album_item)
610
611 # Remove item from the path.
612 dest = os.path.join(*util.components(dest)[:-1])
613
614 dest = album.art_destination(album.artpath, item_dir=dest)
615 if album.artpath == dest:
616 return
617
618 if not (pretend := self.pretend):
619 util.mkdirall(dest)
620
621 if os.path.exists(util.syspath(dest)):
622 self._log.info(
623 "Skipping {.art_filepath} (destination file exists)", album
624 )
625 return
626
627 # Decide whether we need to resize the cover-art image.
628 maxwidth = self._get_art_resize(album.artpath)
629
630 # Either copy or resize (while copying) the image.
631 if maxwidth is not None:
632 self._log.info(
633 "Resizing cover art from {.art_filepath} to {}",
634 album,
635 util.displayable_path(dest),
636 )
637 if not pretend:
638 ArtResizer.shared.resize(maxwidth, album.artpath, dest)
639 else:
640 link, hardlink = self.link, self.hardlink
641 if pretend:
642 msg = "ln" if hardlink else ("ln -s" if link else "cp")
643
644 self._log.info(
645 "{} {.art_filepath} {}",
646 msg,
647 album,
648 util.displayable_path(dest),
649 )
650 else:
651 msg = (
652 "Hardlinking"
653 if hardlink
654 else ("Linking" if link else "Copying")
655 )
656
657 self._log.info(
658 "{} cover art from {.art_filepath} to {}",
659 msg,
660 album,
661 util.displayable_path(dest),
662 )
663 if hardlink:
664 util.hardlink(album.artpath, dest)
665 elif link:
666 util.link(album.artpath, dest)
667 else:
668 util.copy(album.artpath, dest)
669
670 def convert_func(
671 self, lib: Library, opts: ConvertCLIOpts, args: list[str]
672 ) -> None:
673 self.config.set(vars(opts))
674 pretend = self.pretend
675
676 if opts.album:
677 albums = lib.albums(args)
678 items = [i for a in albums for i in a.items()]
679 if not pretend:
680 for a in albums:
681 ui.print_(format(a, ""))
682 else:
683 items = list(lib.items(args))
684 if not pretend:
685 for i in items:
686 ui.print_(format(i, ""))
687
688 if not items:
689 self._log.error("Empty query result.")
690 return
691 if not (pretend or opts.yes or ui.input_yn("Convert? (Y/n)")):
692 return
693
694 if opts.album and self.config["copy_album_art"]:
695 for album in albums:
696 self.copy_album_art(album)
697
698 # If the user supplied a playlist name, create a playlist for files
699 # copied to the destination.
700 pl_normpath = None
701 items_paths = None
702 if playlist := self.playlist:
703 # Playlist paths are understood as relative to the dest directory.
704 pl_normpath = util.normpath(playlist)
705 pl_dir = os.path.dirname(pl_normpath)
706 items_paths = []
707 for item in items:
708 item_path = self.get_item_destination(item)
709
710 # When keeping new files in the library, destination paths
711 # keep original files and extensions.
712 if not opts.keep_new and self.should_transcode(item):
713 item_path = replace_ext(item_path, self.command.ext)
714
715 items_paths.append(os.path.relpath(item_path, pl_dir))
716
717 self._parallel_convert(
718 items, keep_new=self.config["keep_new"].get(bool)
719 )
720
721 if playlist:
722 self._log.info("Creating playlist file {}", pl_normpath)
723 if not pretend:
724 m3ufile = M3UFile(playlist)
725 m3ufile.set_contents(items_paths)
726 m3ufile.write()
727
728 def convert_on_import(self, _: Library, item: Item) -> None:
729 """Transcode a file automatically after it is imported into the
730 library.
731 """
732 if self.should_transcode(item):
733 command, ext = self.command
734
735 # Create a temporary file for the conversion.
736 tmpdir = self.config["tmpdir"].get()
737 if tmpdir:
738 tmpdir = util.bytestring_path(tmpdir)
739 fd, dest = tempfile.mkstemp(b"." + ext, dir=tmpdir)
740 os.close(fd)
741 dest = util.bytestring_path(dest)
742 _temp_files.append(dest) # Delete the transcode later.
743
744 # Convert.
745 try:
746 self.encode(command, item.path, dest)
747 except subprocess.CalledProcessError:
748 return
749
750 # Change the newly-imported database entry to point to the
751 # converted file.
752 source_path = item.path
753 item.path = dest
754 item.write()
755 item.read() # Load new audio information data.
756 item.store()
757
758 if self.config["delete_originals"]:
759 self._log.log(
760 logging.DEBUG if self.config["quiet"] else logging.INFO,
761 "Removing original file {}",
762 source_path,
763 )
764 util.remove(source_path, False)
765
766 def _get_art_resize(self, artpath: bytes) -> int | None:
767 """For a given piece of album art, determine whether or not it needs
768 to be resized according to the user's settings. If so, returns the
769 new size. If not, returns None.
770 """
771 newwidth = None
772 if self.config["album_art_maxwidth"]:
773 maxwidth = self.config["album_art_maxwidth"].get(int)
774 size = ArtResizer.shared.get_size(artpath)
775 self._log.debug("image size: {}", size)
776 if size:
777 if size[0] > maxwidth:
778 newwidth = maxwidth
779 else:
780 self._log.warning(
781 "Could not get size of image (please see "
782 "documentation for dependencies)."
783 )
784 return newwidth
785
786 def _cleanup(self, task: ImportTask, session: ImportSession) -> None:
787 for path in task.old_paths:
788 if path in _temp_files:
789 if os.path.isfile(util.syspath(path)):
790 util.remove(path)
791 _temp_files.remove(path)
792
793 def _parallel_convert(self, items: Iterable[Item], keep_new: bool) -> None:
794 """Run the convert_item function for every items on as many thread as
795 defined in threads
796 """
797 convert = [self.convert_item(keep_new) for _ in range(self.threads)]
798 pipeline.Pipeline([iter(items), convert]).run_parallel()