Plugin v3: Generate M3U playlist

After upgrading to Picard 3, the ‘Generate M3U playlist’ plugin no longer works. With some edits to the v2 python and a MANIFEST.toml file from migrate_plugin.py, I was able to get it working in Picard 3 on Windows by creating a ‘playlist’ sub-folder in %APPDATA%\MusicBrainz\Picard\plugins3\ and adding these two files into the plugins3 folder. It’s probably missing something but it works and creates .m3u8 playlist files.

MANIFEST.toml

uuid = "4ebc9721-2936-4c10-aa05-fe6ec695437d"
name = "Generate M3U playlist"
authors = ["Francis Chin, Sambhav Kothari, Chris Hylen"]
description = """Generate an Extended M3U playlist (.m3u8 file, UTF8
encoded text). Relative pathnames are used where audio files are in the same
directory as the playlist, otherwise absolute (full) pathnames are u..."""
version = "1.3.0"
api = ['3.0']
license = "GPL-2.0-or-later"
license_url = "https://www.gnu.org/licenses/gpl-2.0.html"
long_description = """Generate an Extended M3U playlist (.m3u8 file, UTF8
encoded text). Relative pathnames are used where audio files are in the same
directory as the playlist, otherwise absolute (full) pathnames are used."""

__init__.py file:
#!/usr/bin/python
# -*- coding: utf-8 -*-

# 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.

PLUGIN_NAME = "Generate M3U playlist"
PLUGIN_AUTHOR = "Francis Chin, Sambhav Kothari, Chris Hylen"
PLUGIN_DESCRIPTION = """Generate an Extended M3U playlist (.m3u8 file, UTF8
encoded text). Relative pathnames are used where audio files are in the same
directory as the playlist, otherwise absolute (full) pathnames are used."""
PLUGIN_VERSION = "1.3.0"
PLUGIN_API_VERSIONS = ["3.0"]
PLUGIN_LICENSE = "GPL-2.0-or-later"
PLUGIN_LICENSE_URL = "https://www.gnu.org/licenses/gpl-2.0.html"

import os.path

from PyQt6 import QtCore, QtWidgets
from picard import log
from picard.const import VARIOUS_ARTISTS_ID
from picard.util import find_existing_path

from picard.plugin3.api import BaseAction


_debug_level = 0

def get_safe_filename(filename):
    _valid_chars = " .,_-:+&!()"
    _safe_filename = "".join(
        c if (c.isalnum() or c in _valid_chars) else "_" for c in filename
    ).rstrip()
    return _safe_filename


class PlaylistEntry(list):

    def __init__(self, playlist, index):
        list.__init__(self)
        self.playlist = playlist
        self.index = index

    def add(self, entry_row):
        self.append(entry_row + "\n")


class Playlist(object):

    def __init__(self, filename):
        self.filename = filename
        self.entries = []
        self.headers = []

    def add_header(self, header):
        self.headers.append(header + "\n")

    def write(self):
        b_lines = []
        for header in self.headers:
            b_lines.append(header.encode("utf-8"))
        for entry in self.entries:
            for row in entry:
                b_lines.append(row.encode("utf-8"))
        with open(self.filename, "wb") as f:
            f.writelines(b_lines)


class GeneratePlaylist(BaseAction):
    TITLE = "Generate &Playlist..."

    def callback(self, objs):
        if not objs:
            return
            
        # Find common path of all files to default where to save playlist
        files = []
        for album in objs:
            for track in album.tracks:
                # FIXED: Picard 3.0 uses track.files instead of track.linked_files
                if track.files:
                    for f in track.files:
                        files.append(f.filename)

        try:
            current_directory = os.path.commonpath(files)
        except ValueError:
            current_directory = ""

        # FIXED: Explicitly grab index 0 of selection array to get metadata safely
        first_album = objs[0]
        artist_id = first_album.metadata.get("musicbrainz_albumartistid", "")
        album_artist = first_album.metadata.get("albumartist", "Unknown Artist")
        album_title = first_album.metadata.get("album", "Unknown Album")

        if _debug_level > 1:
            log.debug("{}: VARIOUS_ARTISTS_ID is {}, musicbrainz_albumartistid is {}".format(
                    PLUGIN_NAME, VARIOUS_ARTISTS_ID, artist_id))

        if artist_id != VARIOUS_ARTISTS_ID:
            default_filename = get_safe_filename(f"{album_artist} - {album_title}.m3u8")
        else:
            default_filename = get_safe_filename(f"{album_title}.m3u8")

        if _debug_level > 1:
            log.debug("{}: default playlist filename sanitized to {}".format(
                    PLUGIN_NAME, default_filename))
                    
        filename, selected_format = QtWidgets.QFileDialog.getSaveFileName(
            None, "Save new playlist",
            os.path.join(current_directory, default_filename),
            "Playlist (*.m3u8 *.m3u)"
        )
        if filename:
            playlist = Playlist(filename)
            playlist.add_header("#EXTM3U")

            for album in objs:
                for track in album.tracks:
                    # FIXED: Swapped to track.files mapping loop
                    if track.files:
                        entry = PlaylistEntry(playlist, len(playlist.entries))
                        playlist.entries.append(entry)

                        # M3U EXTINF row
                        track_length_seconds = int(round(track.metadata.length / 1000.0))
                        entry.add("#EXTINF:{duration:d},{artist} - {title}".format(
                            duration=track_length_seconds,
                            artist=track.metadata.get("artist", "Unknown"),
                            title=track.metadata.get("title", "Unknown")
                            )
                        )

                        # M3U URL row - Extract the path from the first matched file object safely
                        first_file = track.files[0]
                        audio_filename = first_file.filename
                        
                        try:
                            audio_filename = os.path.relpath(audio_filename, os.path.dirname(filename))
                        except ValueError:
                            pass
                        entry.add(str(audio_filename))

            playlist.write()


def enable(api):
    api.register_album_action(GeneratePlaylist)

4 Likes

I see rdswift converted the ‘Generate Playlist’ plugin to a proper v3 plugin and it is available for install from the Picard 3 Options > Plugins menu so no need to use the hack conversion I posted earlier. Thank you rdswift!

GitHub - rdswift/picard-plugin-generate-playlist: Generate Playlist plugin for Picard 3 · GitHub

2 Likes