def get_media_stream_url(media_url):
    """Extract stream URL from the media URL."""
    from youtube_dl import YoutubeDL
    from youtube_dl.utils import DownloadError, ExtractorError

    ydl = YoutubeDL({'quiet': True, 'logger': _LOGGER})

    try:
        all_media_streams = ydl.extract_info(media_url, process=False)
    except DownloadError:
        # This exception will be logged by youtube-dl itself
        raise YDException()

    if 'entries' in all_media_streams:
        _LOGGER.warning("Playlists are not supported, "
                        "looking for the first video")
        try:
            selected_stream = next(all_media_streams['entries'])
        except StopIteration:
            _LOGGER.error("Playlist is empty")
            raise YDException()
    else:
        selected_stream = all_media_streams

    try:
        media_info = ydl.process_ie_result(selected_stream, download=False)
    except (ExtractorError, DownloadError):
        # This exception will be logged by youtube-dl itself
        raise YDException()

    format_selector = ydl.build_format_selector('best')

    try:
        best_quality_stream = next(format_selector(media_info))
    except (KeyError, StopIteration):
        best_quality_stream = media_info

    return best_quality_stream['url']
def get_media_stream_url(media_url):
    """Extract stream URL from the media URL."""
    from youtube_dl import YoutubeDL
    from youtube_dl.utils import DownloadError, ExtractorError

    ydl = YoutubeDL({'quiet': True, 'logger': _LOGGER})

    try:
        all_media_streams = ydl.extract_info(media_url, process=False)
    except DownloadError:
        # This exception will be logged by youtube-dl itself
        raise YDException()

    if 'entries' in all_media_streams:
        _LOGGER.warning("Playlists are not supported, "
                        "looking for the first video")
        try:
            selected_stream = next(all_media_streams['entries'])
        except StopIteration:
            _LOGGER.error("Playlist is empty")
            raise YDException()
    else:
        selected_stream = all_media_streams

    try:
        media_info = ydl.process_ie_result(selected_stream, download=False)
    except (ExtractorError, DownloadError):
        # This exception will be logged by youtube-dl itself
        raise YDException()

    format_selector = ydl.build_format_selector('best')

    try:
        best_quality_stream = next(format_selector(media_info))
    except (KeyError, StopIteration):
        best_quality_stream = media_info

    return best_quality_stream['url']