Exemple #1
0
    def __init__(self, config, database):
        if type(config) is not MusicDBConfig:
            raise TypeError("config argument not of type MusicDBConfig")
        if type(database) is not MusicDatabase:
            raise TypeError("database argument not of type MusicDatabase")

        self.db = database
        self.cfg = config
        self.mdbstate = MDBState(self.cfg.server.statedir, self.db)
        self.blacklist = BlacklistInterface(self.cfg, self.db)
        self.randy = Randy(self.cfg, self.db)

        global Queue
        global QueueLock

        with QueueLock:
            if Queue == None:
                logging.debug("Loading Video Queue…")
                try:
                    self.Load()
                except Exception as e:
                    logging.warning(
                        "Loading video queue failed with error: %s. \033[1;30m(Creating an empty one)",
                        str(e))
                    Queue = []
Exemple #2
0
def StreamingThread():
    """
    This thread manages the streaming of the songs from the Song Queue to the Icecast server.

    The thread tracks the played song using the :doc:`/mdbapi/tracker` module.
    It also tracks randomly added songs assuming the user skips or removes songs that don't fit.
    Only completely played songs will be considered.
    Skipped songs will be ignored.

    The thread triggers the following events:

        * ``StatusChanged``: When the play-state
        * ``TimeChanged``: To update the current streaming progress of a song

    The ``TimeChanged`` event gets triggered approximately every second.
    """
    from lib.stream.icecast import IcecastInterface
    from mdbapi.tracker import Tracker

    global Config
    global RunThread
    global CommandQueue
    global State

    # Create all interfaces that are needed by this Thread
    musicdb = MusicDatabase(Config.database.path)
    tracker = Tracker(Config, musicdb)
    filesystem = Filesystem(Config.music.path)
    queue = SongQueue(Config, musicdb)
    randy = Randy(Config, musicdb)
    icecast = IcecastInterface(port=Config.icecast.port,
                               user=Config.icecast.user,
                               password=Config.icecast.password,
                               mountname=Config.icecast.mountname)
    icecast.Mute()

    while RunThread:
        # Sleep a bit to reduce the load on the CPU. If disconnected, sleep a bit longer
        if State["isconnected"]:
            time.sleep(0.1)
        else:
            time.sleep(2)

        # Check connection to Icecast, and connect if disconnected.
        isconnected = icecast.IsConnected()
        if State["isconnected"] != isconnected:
            State["isconnected"] = isconnected
            Event_StatusChanged()

        if not isconnected:
            # Try to connect, and check if connection succeeded in the next turn of the main loop
            logging.info("Trying to reconnect to Icecast…")
            icecast.Connect()
            continue

        # Get current song that shall be streamed.
        queueentry = queue.CurrentSong()
        if queueentry == None or queueentry["entryid"] == None:
            logging.info("Waiting for 5s to try to get a new song to play.")
            time.sleep(5)
            continue

        mdbsong = musicdb.GetSongById(queueentry["songid"])
        songpath = filesystem.AbsolutePath(mdbsong["path"])

        # Stream song
        icecast.UpdateTitle(mdbsong["path"])
        logging.debug("Start streaming %s", songpath)
        timeplayed = 0
        lasttimestamp = time.time()
        for frameinfo in icecast.StreamFile(songpath):
            # Send every second the estimated time position of the song.
            if not frameinfo["muted"]:
                timeplayed += frameinfo["header"]["frametime"]
            timestamp = time.time()
            timediff = timestamp - lasttimestamp
            if timediff >= 1.0:
                Event_TimeChanged(timeplayed / 1000)
                lasttimestamp = timestamp

            # Check if the thread shall be exit
            if not RunThread:
                break

            # read and handle queue commands if there is one
            if len(CommandQueue) == 0:
                continue

            command, argument = CommandQueue.pop(0)
            if command == "PlayNextSong":
                logging.debug("Playing next song")
                break  # Stop streaming current song, and start the next one

            elif command == "Play":
                logging.debug("Setting Play-State to %s", str(argument))
                State["isplaying"] = argument
                icecast.Mute(
                    not State["isplaying"])  # Mute stream, when not playing
                Event_StatusChanged()
        else:
            # when the for loop streaming the current song gets not left via break,
            # then the whole song was streamed. So add that song to the trackers list
            # Also update the last time played information.
            # In case the loop ended because Icecast failed, update the Status
            if icecast.IsConnected():
                if not queueentry["israndom"]:  # do not track random songs
                    tracker.AddSong(queueentry["songid"])
                if not Config.debug.disablestats:
                    musicdb.UpdateSongStatistic(queueentry["songid"],
                                                "lastplayed", int(time.time()))
            else:
                icecast.Mute()
                State["isplaying"] = False
                State["isconnected"] = False
                Event_StatusChanged()

        # Current song completely streamed. Get next one.
        # When the song was stopped to shutdown the server, do not skip to the next one
        # In case the loop stopped because of an Icecast error, stay at the last song.
        if RunThread and icecast.IsConnected():
            queue.NextSong()
Exemple #3
0
class VideoQueue(object):
    """
    This class implements a queue to manage videos to play.
    Whenever the queue changes, its data gets stored in the MusicDB State Directory

    When the constructor detects that there is no queue yet (not even an empty one),
    it tries to load the stored queue.
    If this fails, a new empty queue gets created.

    Args:
        config: :class:`~lib.cfg.musicdb.MusicDBConfig` object holding the MusicDB Configuration
        database: A :class:`~lib.db.musicdb.MusicDatabase` instance

    Raises:
        TypeError: When the arguments are not of the correct type.
    """
    def __init__(self, config, database):
        if type(config) is not MusicDBConfig:
            raise TypeError("config argument not of type MusicDBConfig")
        if type(database) is not MusicDatabase:
            raise TypeError("database argument not of type MusicDatabase")

        self.db = database
        self.cfg = config
        self.mdbstate = MDBState(self.cfg.server.statedir, self.db)
        self.blacklist = BlacklistInterface(self.cfg, self.db)
        self.randy = Randy(self.cfg, self.db)

        global Queue
        global QueueLock

        with QueueLock:
            if Queue == None:
                logging.debug("Loading Video Queue…")
                try:
                    self.Load()
                except Exception as e:
                    logging.warning(
                        "Loading video queue failed with error: %s. \033[1;30m(Creating an empty one)",
                        str(e))
                    Queue = []

    #####################################################################
    # Event Management                                                  #
    #####################################################################

    def RegisterCallback(self, function):
        """
        Register a callback function that reacts on Video Queue related events.
        For more details see the module description at the top of this document.

        Args:
            function: A function that shall be called on an event.

        Returns:
            *Nothing*
        """
        global Callbacks
        Callbacks.append(function)

    def RemoveCallback(self, function):
        """
        Removes a function from the list of callback functions.

        Args:
            function: A function that shall be called removed.

        Returns:
            *Nothing*
        """
        global Callbacks

        # Not registered? Then do nothing.
        if not function in Callbacks:
            logging.warning(
                "A Video Queue callback function should be removed, but did not exist in the list of callback functions!"
            )
            return

        Callbacks.remove(function)

    def TriggerEvent(self, name, arg=None):
        """
        This function triggers an event.
        It iterates through all registered callback functions and calls them.

        The arguments to the functions are the name of the even (``name``) and addition arguments (``arg``).
        That argument will be ``None`` if there is no argument.

        More details about events can be found in the module description at the top of this document.

        Args:
            name (str): Name of the event
            arg: Additional arguments to the event, or ``None``

        Returns:
            *Nothing*
        """
        global Callbacks
        for callback in Callbacks:
            try:
                callback(name, arg)
            except Exception as e:
                logging.exception(
                    "A Video Queue event callback function crashed!")

    def Event_VideoQueueChanged(self):
        """
        See :meth:`~TriggerEvent` with event name ``"VideoQueueChanged"``.
        More details in the module description at the top of this document.

        This method also tries to save the queue into the MusicDB State Directory.
        """
        try:
            self.Save()
        except Exception as e:
            logging.warning(
                "Saving the current video queue failed with error: %s. \033[1;30m(Continuing without saving)",
                str(e))
        self.TriggerEvent("VideoQueueChanged")

    def Event_VideoChanged(self):
        """
        See :meth:`~TriggerEvent` with event name ``"VideoChanged"``
        More details in the module description at the top of this document.
        """
        self.TriggerEvent("VideoChanged")

    #####################################################################
    # Queue Management                                                  #
    #####################################################################

    def Save(self):
        """
        Save the current queue into a csv file in the MusicDB State Directory.
        Therefor the :meth:`lib.cfg.mdbstate.MDBState.SaveVideoQueue` gets used.

        Returns:
            *Nothing*
        """
        global Queue
        global QueueLock

        with QueueLock:
            self.mdbstate.SaveVideoQueue(Queue)

    def Load(self):
        """
        This method loads the last stored video queue for the MusicDB State Directory
        via :meth:`lib.cfg.mdbstate.MDBState.LoadVideoQueue`.

        Returns:
            *Nothing*
        """
        global Queue
        global QueueLock

        with QueueLock:
            Queue = self.mdbstate.LoadVideoQueue()

    def GenerateID(self):
        """
        This method generate a unique ID.
        In detail, it is a `Version 4 Universally Unique Identifier (UUID) <https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)>`_ .
        It will be returned as an integer.

        This method is build for the internal use in this class.

        Returns:
            A UUID to be used as entry ID

        Example:

            .. code-block:: python

                queue = VideoQueue()
                uuid  = queue.GenerateID()
                print(type(uuid))   # int
        """
        return uuid.uuid4().int

    def CurrentVideo(self):
        """
        This method returns the current video in the queue.

        The method returns element 0 from the queue which is the current video
        that can be streamed or gets already streamed.
        The video shall remain in the queue until it got completely streamed.
        Then it can be removed by calling :meth:`~mdbapi.videoqueue.VideoQueue.NextVideo`.

        When the queue is empty, a new random video gets added.
        This is the exact same video that then will be returned by this method.
        If adding a new video fails, ``None`` gets returned.
        This method triggers the ``VideoQueueChanged`` event when the queue was empty and a new random video got added.

        Returns:
            A dictionary as described in the module description

        Example:

            .. code-block:: python

                queue = VideoQueue()

                # Queue will be empty after creating a VideoQueue object
                entry = queue.CurrentVideo()
                if entry:
                    print("Random VideoID: %s" % (str(entry["videoid"])))
                else
                    print("Queue is empty! - Adding random video failed!")

                # Adds two new video with ID 7357 and 1337. 
                # Then the current video is the first video added.
                queue.AddVideo(7357)
                queue.AddVideo(1337)
                entry = queue.CurrentVideo()
                if entry:
                    print("VideoID: %s" % (str(entry["videoid"]))) # 7357
                else
                    # will not be reached because we explicitly added videos.
                    print("Queue is empty! - Adding random videofailed!")

        """
        global Queue
        global QueueLock

        with QueueLock:
            # Empty Queue? Add a random video!
            if len(Queue) == 0:
                self.AddRandomVideo()
                self.Event_VideoQueueChanged()

            # Still empty (no random video found)? Then return None. Nothing to do…
            if len(Queue) == 0:
                logging.critical(
                    "Queue run empty! \033[1;30m(Check constraints for random video selection and check if there are videos at all)"
                )
                return None

            # Select first video from queue
            entry = Queue[0]

        return entry

    def NextVideo(self):
        """
        This method returns the next video in the queue.
        This entry will be the next current video.

        The method pops the last current element from the queue.
        Then the new element at position 0, the new current element, will be returned.

        If the queue is empty, ``None`` gets returned.

        .. warning::

            In context of streaming, this method may not be the one you want to call.
            This Method drops the current video and sets the next video on top of the queue.

            The stream will not notice this, so that it continues streaming the previous video. (See :doc:`/mdbapi/videostream`).
            If you want to stream the next video, call :meth:`mdbapi.videostream.VideoStreamManager.PlayNextVideo`.

            The :meth:`mdbapi.videostream.VideoStreamManager.PlayNextVideo` then makes the Streaming Thread calling this method.

        This method triggers the ``VideoChanged`` and ``VideoQueueChanged`` event when the queue was not empty.
        The ``VideoChanged`` event gets also triggered when there was no next video.

        When there is only one entry left in the queue - the current video - then a new one gets add via :meth:`AddRandomVideo`

        Returns:
            The new current video entry in the queue as dictionary described in the module description

        Example:

            .. code-block:: python

                queue = VideoQueue()

                # Adds two new video with ID 7357 and 1337. 
                queue.AddVideo(7357)
                queue.AddVideo(1337)
            
                entry = queue.CurrentVideo()
                print("VideoID: %s" % (str(entry["videoid"]))) # 7357

                entry = queue.NextVideo()
                print("VideoID: %s" % (str(entry["videoid"]))) # 1337
                entry = queue.CurrentVideo()
                print("VideoID: %s" % (str(entry["videoid"]))) # 1337

        """
        global Queue
        global QueueLock

        with QueueLock:
            if len(Queue) == 0:
                return None

            # Get next video
            if len(Queue) == 1:
                Queue.pop(0)
                entry = None
            else:  # > 1
                Queue.pop(0)
                entry = Queue[0]

            # Make sure the queue never runs empty
            if len(Queue) < 2:
                self.AddRandomVideo()

        self.Event_VideoChanged()
        self.Event_VideoQueueChanged()
        return entry

    def GetQueue(self):
        """
        This method returns a copy of the video queue.

        The queue is a list of dictionaries.
        The content of the dictionary is described in the description of this module.

        Returns:
            The current video queue. ``[None]`` if there is no queue yet.

        Example:

            .. code-block:: python

                queue = videoqueue.GetQueue()

                if not queue:
                    print("There are no videos in the queue")
                else:
                    for entry in queue:
                        print("Element with ID %i holds the video with ID %i" 
                                % (entry["entryid"], entry["videoid"]))

        """
        global Queue
        return list(Queue)

    def AddVideo(self, videoid, position="last", israndom=False):
        """
        With this method, a new video can be insert into the queue.

        The position in the queue, where the video gets insert can be changed by setting the ``position`` argument:

            * ``"last"`` (default): Appends the video at the end of the queue
            * ``"next"``: Inserts the video right after the current playing video.
            * *Integer*: Entry-ID after that the video shall be inserted.

        On success, this method triggers the ``VideoQueueChanged`` event.

        When the video shall be put at the beginning of the queue, then it gets set to index 1 not index 0.
        So the current playing video (index 0) remains!

        The new video gets added to the :mod:`~mdbapi.blacklist` via :meth:`mdbapi.blacklist.BlacklistInterface.AddVideo`
        The method also triggers the ``VideoQueueChanged`` event.

        Args:
            videoid (int): The ID of the video that shall be added to the queue
            position (str/int): Defines the position where the video gets inserted
            israndom (bool): Defines whether the video is randomly selected or not

        Returns:
            *Nothing*

        Raises:
            TypeError: When ``videoid`` is not of type ``int``
        """
        if type(videoid) is not int:
            raise TypeError("Video ID must be an integer!")

        entryid = self.GenerateID()

        newentry = {}
        newentry["entryid"] = entryid
        newentry["videoid"] = videoid
        newentry["israndom"] = israndom

        global Queue
        global QueueLock

        with QueueLock:
            if position == "next":
                Queue.insert(1, newentry)

            elif position == "last":
                Queue.append(newentry)

            elif type(position) == int:
                for index, entry in enumerate(Queue):
                    if entry["entryid"] == position:
                        Queue.insert(index + 1, newentry)
                        break
                else:
                    logging.warning(
                        "Queue Entry ID %s does not exist. \033[1;30m(Doing nothing)",
                        str(position))
            else:
                logging.warning(
                    "Position must have the value \"next\" or \"last\" or an Queue Entry ID. Given was \"%s\". \033[1;30m(Doing nothing)",
                    str(position))
                return

        # add to blacklist
        self.blacklist.AddVideo(videoid)

        self.Event_VideoQueueChanged()
        return

    def AddRandomVideo(self, position="last"):
        """
        This method adds a random video into the queue.

        The position in the queue, where the video gets insert can be changed by setting the ``position`` argument:

            * ``"last"`` (default): Appends the video at the end of the queue
            * ``"next"``: Inserts the video right after the current playing video.

        The method :meth:`mdbapi.randy.Randy.GetVideo` will be used to get a random video from the activated genres.

        After selecting the random video, the :meth:`~AddVideo` method gets used to insert the new video into the queue.
        If there is no video found by Randy, then nothing gets added to the queue and ``False`` will be returned.

        Args:
            position (str): Defines the position where the video gets inserted.
            albumid (int/NoneType): ID of the album from that the video will be selected, or ``None`` for selecting a video from the activated genres.

        Returns:
            ``True`` when a random video got added to the queue. Otherwise ``False``.

        Raises:
            TypeError: When one of the types of the arguments are not correct
        """
        if type(position) != str:
            raise TypeError("Position must be a string!")

        mdbvideo = self.randy.GetVideo()

        if not mdbvideo:
            return False

        self.AddVideo(mdbvideo["id"], position, israndom=True)
        return True

    def GetVideo(self, entryid):
        """
        Returns the video ID of the entry addressed by the entry ID

        Args:
            entryid (int): ID of the entry that video ID shall be returned

        Returns:
            The video ID of the entry, or ``None`` if the entry does not exists

        Raises:
            TypeError: When ``entryid`` is not of type ``int``
        """
        if type(entryid) is not int:
            raise TypeError("Entry ID must be an integer!")

        global Queue
        global QueueLock

        with QueueLock:
            for entry in Queue:
                if entry["entryid"] == entryid:
                    return entry["videoid"]

        logging.debug(
            "Cannot find the requested entry %s! \033[1;30m(Returning None)",
            str(entryid))
        return None

    def RemoveVideo(self, entryid):
        """
        Removes the entry with the ID ``entryid`` from the queue.
        Removing the current video is not allowed!
        Call :meth:`~NextVideo` instead.

        When there is only one entry left in the queue - the current video - then a new one gets add via :meth:`~AddRandomVideo`

        On success, this method triggers the ``VideoQueueChanged`` event.

        Args:
            entryid (int): Entry to remove

        Returns:
            ``True`` on success, otherwise ``False``

        Raises:
            TypeError: When ``entryid`` is not of type ``int``
        """
        if type(entryid) is not int:
            raise TypeError("Entry ID must be an integer!")

        global Queue
        global QueueLock

        with QueueLock:
            if len(Queue) < 2:
                logging.warning(
                    "The queue has only %i element. There must be at least 2 entries to be able to remove one.",
                    len(Queue))
                return False

            if Queue[0]["entryid"] == entryid:
                logging.warning(
                    "The entry ID addresses the current video. This entry cannot be removed!"
                )
                return False

            Queue = [entry for entry in Queue if entry["entryid"] != entryid]

            # Make sure the queue never runs empty
            if len(Queue) < 2:
                self.AddRandomVideo()

        self.Event_VideoQueueChanged()
        return True

    def MoveVideo(self, entryid, afterid):
        """
        This method moves an entry, addressed by ``entryid`` behind another entry addressed by ``afterid``.
        If both IDs are the same, the method returns immediately without doing anything.
        When ``entryid`` addresses the current video, the method returns with value ``False``

        On success, the method triggers the ``VideoQueueChanged`` event.

        Args:
            entryid (int):
            afterid (int):

        Returns:
            ``True`` when the entry was moved, otherwise ``False``

        Raises:
            TypeError: When ``entryid`` or ``afterid`` is not of type int
        """
        if entryid == afterid:
            return False

        # First check, if everything is OK with the arguments
        if type(entryid) is not int or type(afterid) is not int:
            raise TypeError("Queue entry IDs must be of type int!")

        global Queue
        global QueueLock

        with QueueLock:
            if Queue[0]["entryid"] == entryid:
                logging.warning(
                    "The entry ID addresses the current video. This entry cannot be moved!"
                )
                return False

            # Get Positions
            frompos = [
                pos for pos, entry in enumerate(Queue)
                if entry["entryid"] == entryid
            ]
            topos = [
                pos for pos, entry in enumerate(Queue)
                if entry["entryid"] == afterid
            ]

            if not frompos:
                logging.warning(
                    "Cannot find element with entryid %i in the queue!\033[1;30m (Doing nothing)",
                    entryid)
                return False
            if not topos:
                logging.warning(
                    "Cannot find element with afterid %i in the queue!\033[1;30m (Doing nothing)",
                    afterid)
                return False

            frompos = frompos[0]
            topos = topos[0]

            # When topos is behind frompos, decrement topos because if shifts one entry down due to popping the frompos-element from the list
            if topos < frompos:
                topos += 1

            # Move element
            entry = Queue.pop(frompos)
            Queue.insert(topos, entry)

        self.Event_VideoQueueChanged()
        return True