Esempio n. 1
0
    def value_changed(self, value):
        try:
            """
            Chromecast volume
            """
            volume = value/self.maxvolset
            self.cast.set_volume(volume)
            if round(self.cast.status.volume_level, 1) == 1:
                print(colors.warning(
                    ':::systray::: Maximum volume level reached!'))

            if debug is True:
                print(':::systray::: Volume set to: '+str(volume))
        except AttributeError:
            pass

        try:
            """
            Sonos volume
            """
            self.maxvolset = 100
            volume = value
            self.cast.volume = volume
            self.cast.play()
            if (self.cast.volume) == 100:
                print(colors.warning(':::systray::: Maximum volume reached!'))

            if debug is True:
                print(':::systray::: Volume set to: '+str(volume))
        except AttributeError:
            pass

        if debug is True:
            print(':::systray::: Volume changed: '+str(value))
Esempio n. 2
0
def maxbitrate(codec, bitrate):
    if source_url is None:
        print(colors.warning('Maximum bitrate supported by ' + codec +
                             ' is: ' + bitrate + 'k.'))
    if codec == 'aac' and source_url is None:
        print(colors.warning('At about 128-256k is already considered as '
              '"transparent" for ' + codec + '.'))
        print(colors.warning('You may try lossless audio coding formats.'))
        print(colors.warning('Bitrate has been set to maximum!'))
    return
Esempio n. 3
0
    def _search_cast_(self):
        # This should fix the error socket.gaierror making the system tray to
        # be closed.
        try:
            self.cc = Casting()
            self.cc.initialize_cast()
            self.cc.available_devices()
        except socket.gaierror:
            if debug is True:
                print(colors.warning(
                    ':::Threading::: Socket error, CC set to 0'))
            pass
        except TypeError:
            pass
        except OSError:
            self.cc.available_devices = []

        if len(self.cc.available_devices) == 0 and tray is True:
            available_devices = []
            self.intReady.emit(available_devices)
            self.finished.emit()
        else:
            available_devices = self.cc.available_devices
            self.intReady.emit(available_devices)
            self.finished.emit()
Esempio n. 4
0
def samplerate_no96(codec):
    """This prints warning when sample rates are set incorrectly and no 96k"""
    if source_url is None:
        print(colors.warning('Sample rates supported by ' + codec + ' are: ' +
              str(22050) + 'Hz, ' +
              str(32000) + 'Hz, ' +
              str(44100) + 'Hz or, ' +
              str(48000) + 'Hz.'))
    return
Esempio n. 5
0
    def _play_cast_(self):
        if os.path.exists(configf):
            print(colors.warning(':::Threading::: Configuration file exists.'))
            print(colors.warning(':::Threading::: Using defaults set there.'))
            config.read(configf)
            backend = ConfigSectionMap('settings')['backend']
            print(':::Threading backend::: %s.' % backend)
        else:
            backend = mkchromecast.__init__.backend
        global cast
        if backend == 'node':
            stream()
        else:
            try:
                reload(mkchromecast.audio)
            except NameError:
                from imp import reload
                reload(mkchromecast.audio)
            mkchromecast.audio.main()
        if platform == 'Linux':
            # We create the sink only if it is not available
            if check_sink() is False and adevice is None:
                create_sink()

        start = Casting()
        start.initialize_cast()
        try:
            start.get_devices()
            start.play_cast()
            cast = start.cast
            # Let's change inputs at the end to avoid muting sound too early.
            # For Linux it does not matter given that user has to select sink
            # in pulse audio.  Therefore the sooner it is available, the
            # better.
            if platform == 'Darwin':
                inputdev()
                outputdev()
            self.pcastready.emit('_play_cast_ success')
        except AttributeError:
            self.pcastready.emit('_play_cast_ failed')
        self.pcastfinished.emit()
Esempio n. 6
0
    def read_config(self):
        """
        This is to load variables from configuration file
        """
        config = ConfigParser.RawConfigParser()
        configurations = config_manager()    # Class from mkchromecast.config
        configf = configurations.configf

        if os.path.exists(configf):
            print(colors.warning('Configuration file exists'))
            print(colors.warning('Using defaults set there'))
            config.read(configf)
            self.notifications = ConfigSectionMap('settings')['notifications']
            self.searchatlaunch = ConfigSectionMap('settings')[
                    'searchatlaunch']
            self.colors = ConfigSectionMap('settings')['colors']
        else:
            self.notifications = 'disabled'
            self.searchatlaunch = 'disabled'
            self.colors = 'black'
            if debug is True:
                print(':::systray::: self.notifications '+self.notifications)
                print(':::systray::: self.searchatlaunch '+self.searchatlaunch)
                print(':::systray::: self.colors '+self.colors)
Esempio n. 7
0
def no_bitrate(codec):
    if source_url is None:
        print(
            colors.warning('The ' + codec +
                           ' codec does not require the bitrate argument.'))
    return
Esempio n. 8
0
if debug is True:
    print('Google Cast name: %s.' % device_name)
"""
Check that input file exists
"""
if input_file != None and os.path.isfile(input_file) is False:
    if platform == 'Darwin':
        from mkchromecast.audio_devices import inputint, outputint
        inputint()
        outputint()
    else:
        from mkchromecast.pulseaudio import remove_sink
        remove_sink()

    print(colors.warning('File not found!'))
    terminate()
"""
Media-Type
"""
mtype = args.mtype

if args.mtype is not None and args.video is False:
    print(
        colors.warning('The media type is not supported for audio.') %
        args.encoder_backend)
"""
Reset
"""
if args.reset is True:
    if platform == 'Darwin':
Esempio n. 9
0
    def play_cast(self):
        if self.debug is True:
            print('def play_cast(self):')
        localip = self.ip

        try:
            print(
                colors.options('The IP of ') + colors.success(self.cast_to) +
                colors.options(' is:') + ' ' + self.cast.host)
        except TypeError:
            print(
                colors.options('The IP of ') +
                colors.success(self.cast_to.player_name) +
                colors.options(' is:') + ' ' + self.cast_to.ip_address)
        except AttributeError:
            for _ in self.sonos_list:
                if self.cast_to in _.player_name:
                    self.cast_to = _
            print(
                colors.options('The IP of ') +
                colors.success(self.cast_to.player_name) +
                colors.options(' is:') + ' ' + self.cast_to.ip_address)

        if self.host is None:
            print(colors.options('Your local IP is:') + ' ' + localip)
        else:
            print(
                colors.options('Your manually entered local IP is:') + ' ' +
                localip)

        try:
            media_controller = self.cast.media_controller

            if self.tray is True:
                config = ConfigParser.RawConfigParser()
                # Class from mkchromecast.config
                from mkchromecast.config import config_manager
                configurations = config_manager()
                configf = configurations.configf

                if os.path.exists(configf) and self.tray is True:
                    print(self.tray)
                    print(colors.warning('Configuration file exists'))
                    print(colors.warning('Using defaults set there'))
                    config.read(configf)
                    self.backend = ConfigSectionMap('settings')['backend']

            if self.sourceurl is not None:
                if args.video is True:
                    import mkchromecast.video
                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio
                    mtype = mkchromecast.audio.mtype
                print(' ')
                print(
                    colors.options('Casting from stream URL:') + ' ' +
                    self.sourceurl)
                print(colors.options('Using media type:') + ' ' + mtype)
                media_controller.play_media(self.sourceurl,
                                            mtype,
                                            title=self.title)
            elif (self.backend == 'ffmpeg' or self.backend == 'node'
                  or self.backend == 'avconv' or self.backend == 'parec'
                  or self.backend == 'gstreamer' and self.sourceurl is None):
                if args.video is True:
                    import mkchromecast.video
                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio
                    mtype = mkchromecast.audio.mtype
                print(' ')
                print(
                    colors.options('The media type string used is:') + ' ' +
                    mtype)
                media_controller.play_media('http://' + localip + ':' +
                                            self.port + '/stream',
                                            mtype,
                                            title=self.title)
            print(' ')
            print(colors.important('Cast media controller status'))
            print(' ')
            print(self.cast.status)
            print(' ')
            if self.hijack is True:
                self.r = Thread(target=self.hijack_cc)
                # This has to be set to True so that we catch
                # KeyboardInterrupt.
                self.r.daemon = True
                self.r.start()
        except AttributeError:
            self.sonos = self.cast_to
            self.sonos.play_uri('x-rincon-mp3radio://' + localip + ':' +
                                self.port + '/stream',
                                title=self.title)
            if self.tray is True:
                self.cast = self.sonos
Esempio n. 10
0
def streaming():
    """
    Configuration files
    """
    platform = mkchromecast.__init__.platform
    tray = mkchromecast.__init__.tray
    debug = mkchromecast.__init__.debug
    config = ConfigParser.RawConfigParser()
    configurations = config_manager()  # Class from mkchromecast.config
    configf = configurations.configf

    if os.path.exists(configf) and tray == True:
        configurations.chk_config()
        print(colors.warning('Configuration file exists'))
        print(colors.warning('Using defaults set there'))
        config.read(configf)
        backend = ConfigSectionMap('settings')['backend']
        rcodec = ConfigSectionMap('settings')['codec']
        bitrate = ConfigSectionMap('settings')['bitrate']
        samplerate = ConfigSectionMap('settings')['samplerate']
        notifications = ConfigSectionMap('settings')['notifications']
    else:
        backend = mkchromecast.__init__.backend
        rcodec = mkchromecast.__init__.rcodec
        codec = mkchromecast.__init__.codec
        bitrate = str(mkchromecast.__init__.bitrate)
        samplerate = str(mkchromecast.__init__.samplerate)
        notifications = mkchromecast.__init__.notifications

    print(colors.options('Selected backend:') + ' ' + backend)

    if debug == True:
        print(':::node::: variables', backend, rcodec, bitrate, samplerate,
              notifications)

    try:
        youtubeurl = mkchromecast.__init__.youtubeurl
    except AttributeError:
        youtubeurl = None

    if youtubeurl == None:
        if backend == 'node' and rcodec != 'mp3':
            print(
                colors.warning('Codec ' + rcodec +
                               ' is not supported by the node server!'))
            print('Using ' + codec + ' as default.')

        if backend == 'node':
            if int(bitrate) == 192:
                print(
                    colors.options('Default bitrate used:') + ' ' + bitrate +
                    'k')
            elif int(bitrate) > 320:
                print(
                    colors.warning('Maximum bitrate supported by ' + codec +
                                   ' is:') + ' ' + str(320) + 'k')
                bitrate = '320'
                print(colors.warning('Bitrate has been set to maximum!'))
            else:
                print(colors.options('Selected bitrate: ') + bitrate + 'k')

            if samplerate == '44100':
                print(
                    colors.options('Default sample rate used:') + ' ' +
                    samplerate + 'Hz')
            else:
                codecs_sr = ['mp3', 'ogg', 'aac', 'wav', 'flac']
                '''
                The codecs below do not support 96000Hz
                '''
                no96k = ['mp3', 'ogg']

                if codec in codecs_sr and int(samplerate) > 22000 and int(
                        samplerate) <= 27050:
                    samplerate = '22050'
                    msg.samplerate_no96(codec)

                if codec in codecs_sr and int(samplerate) > 27050 and int(
                        samplerate) <= 32000:
                    samplerate = '32000'
                    msg.samplerate_no96(codec)

                elif codec in codecs_sr and int(samplerate) > 32000 and int(
                        samplerate) <= 36000:
                    samplerate = '32000'
                    msg.samplerate_no96(codec)

                elif codec in codecs_sr and int(samplerate) > 36000 and int(
                        samplerate) <= 43000:
                    samplerate = '44100'
                    msg.samplerate_no96(codec)
                    print(
                        colors.warning('Sample rate has been set to default!'))

                elif codec in codecs_sr and int(samplerate) > 43000 and int(
                        samplerate) <= 72000:
                    samplerate = '48000'
                    msg.samplerate_no96(codec)

                elif codec in codecs_sr and int(samplerate) > 72000:
                    if codec in no96k:
                        msg.samplerate_no96(codec)
                        samplerate = '48000'
                    print(
                        colors.warning('Sample rate has been set to maximum!'))

                print(
                    colors.options('Sample rate set to:') + ' ' + samplerate +
                    'Hz')
    """
    Node section
    """
    if os.path.exists('./bin/node') == True:
        webcast = [
            './bin/node',
            './nodejs/node_modules/webcast-osx-audio/bin/webcast.js', '-b',
            bitrate, '-s', samplerate, '-p', '5000', '-u', 'stream'
        ]
    else:
        webcast = [
            './nodejs/bin/node',
            './nodejs/node_modules/webcast-osx-audio/bin/webcast.js', '-b',
            bitrate, '-s', samplerate, '-p', '5000', '-u', 'stream'
        ]
    p = subprocess.Popen(webcast)
    if debug == True:
        print(':::node::: node command', webcast)

    f = open('/tmp/mkchromecast.pid', 'rb')
    pidnumber = int(pickle.load(f))
    print(colors.options('PID of main process:') + ' ' + str(pidnumber))

    localpid = getpid()
    print(colors.options('PID of streaming process:') + ' ' + str(localpid))

    while p.poll() is None:
        try:
            time.sleep(0.5)
            if psutil.pid_exists(
                    pidnumber
            ) == False:  # With this I ensure that if the main app fails, everything
                inputint()  # will get back to normal
                outputint()
                parent = psutil.Process(localpid)
                for child in parent.children(
                        recursive=True
                ):  # or parent.children() for recursive=False
                    child.kill()
                parent.kill()
        except KeyboardInterrupt:
            print('Ctrl-c was requested')
            sys.exit(0)
        except IOError:
            print('I/O Error')
            sys.exit(0)
        except OSError:
            print('OSError')
            sys.exit(0)
    else:
        print(colors.warning('Reconnecting node streaming...'))
        if platform == 'Darwin' and notifications == 'enabled':
            if os.path.exists('images/google.icns') == True:
                noticon = 'images/google.icns'
            else:
                noticon = 'google.icns'
        if debug == True:
            print(':::node::: platform, tray, notifications', platform, tray,
                  notifications)

        if platform == 'Darwin' and tray == True and notifications == 'enabled':
            reconnecting = [
                './notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier',
                '-group', 'cast', '-contentImage', noticon, '-title',
                'mkchromecast', '-subtitle', 'node server failed', '-message',
                'Reconnecting...'
            ]
            subprocess.Popen(reconnecting)

            if debug == True:
                print(':::node::: reconnecting notifier command', reconnecting)
        relaunch(stream, recasting, kill)
    return
Esempio n. 11
0
def streaming():
    """
    Configuration files
    """
    platform = mkchromecast.__init__.platform
    tray = mkchromecast.__init__.tray
    debug = mkchromecast.__init__.debug
    config = ConfigParser.RawConfigParser()
    # Class from mkchromecast.config
    configurations = config_manager()
    configf = configurations.configf

    if os.path.exists(configf) and tray is True:
        configurations.chk_config()
        print(colors.warning("Configuration file exists"))
        print(colors.warning("Using defaults set there"))
        config.read(configf)
        backend = ConfigSectionMap("settings")["backend"]
        rcodec = ConfigSectionMap("settings")["codec"]
        bitrate = ConfigSectionMap("settings")["bitrate"]
        samplerate = ConfigSectionMap("settings")["samplerate"]
        notifications = ConfigSectionMap("settings")["notifications"]
    else:
        backend = mkchromecast.__init__.backend
        rcodec = mkchromecast.__init__.rcodec
        codec = mkchromecast.__init__.codec
        bitrate = str(mkchromecast.__init__.bitrate)
        samplerate = str(mkchromecast.__init__.samplerate)
        notifications = mkchromecast.__init__.notifications

    print(colors.options("Selected backend:") + " " + backend)

    if debug is True:
        print(
            ":::node::: variables %s, %s, %s, %s, %s"
            % (backend, rcodec, bitrate, samplerate, notifications)
        )

    try:
        youtube_url = mkchromecast.__init__.youtube_url
    except AttributeError:
        youtube_url = None

    if youtube_url is None:
        if backend == "node" and rcodec != "mp3":
            print(
                colors.warning(
                    "Codec " + rcodec + " is not supported by the node server!"
                )
            )
            print("Using " + codec + " as default.")

        if backend == "node":
            if int(bitrate) == 192:
                print(colors.options("Default bitrate used:") + " " + bitrate + "k.")
            elif int(bitrate) > 500:
                print(
                    colors.warning("Maximum bitrate supported by " + codec + " is:")
                    + " "
                    + str(500)
                    + "k."
                )
                bitrate = "500"
                print(colors.warning("Bitrate has been set to maximum!"))
            else:
                print(colors.options("Selected bitrate: ") + bitrate + "k.")

            if samplerate == "44100":
                print(
                    colors.options("Default sample rate used:")
                    + " "
                    + samplerate
                    + "Hz."
                )
            else:
                codecs_sr = ["mp3", "ogg", "aac", "wav", "flac"]

                """
                The codecs below do not support 96000Hz
                """
                no96k = ["mp3", "ogg"]

                if (
                    codec in codecs_sr
                    and int(samplerate) > 22000
                    and int(samplerate) <= 27050
                ):
                    samplerate = "22050"
                    msg.samplerate_no96(codec)

                if (
                    codec in codecs_sr
                    and int(samplerate) > 27050
                    and int(samplerate) <= 32000
                ):
                    samplerate = "32000"
                    msg.samplerate_no96(codec)

                elif (
                    codec in codecs_sr
                    and int(samplerate) > 32000
                    and int(samplerate) <= 36000
                ):
                    samplerate = "32000"
                    msg.samplerate_no96(codec)

                elif (
                    codec in codecs_sr
                    and int(samplerate) > 36000
                    and int(samplerate) <= 43000
                ):
                    samplerate = "44100"
                    msg.samplerate_no96(codec)
                    print(
                        colors.warning(
                            "Sample rate has been set to \
                        default!"
                        )
                    )

                elif (
                    codec in codecs_sr
                    and int(samplerate) > 43000
                    and int(samplerate) <= 72000
                ):
                    samplerate = "48000"
                    msg.samplerate_no96(codec)

                elif codec in codecs_sr and int(samplerate) > 72000:
                    if codec in no96k:
                        msg.samplerate_no96(codec)
                        samplerate = "48000"
                    print(
                        colors.warning(
                            "Sample rate has been set to \
                        maximum!"
                        )
                    )

                print(colors.options("Sample rate set to:") + " " + samplerate + "Hz.")

    """
    Node section
    """
    paths = ["/usr/local/bin/node", "./bin/node", "./nodejs/bin/node"]

    for path in paths:
        if os.path.exists(path) is True:
            webcast = [
                path,
                "./nodejs/node_modules/webcast-osx-audio/bin/webcast.js",
                "-b",
                bitrate,
                "-s",
                samplerate,
                "-p",
                "5000",
                "-u",
                "stream",
            ]
            break
    else:
        webcast = None
        print(colors.warning("Node is not installed..."))
        print(
            colors.warning("Use your package manager or their official " "installer...")
        )
        pass

    if webcast is not None:
        p = subprocess.Popen(webcast)

        if debug is True:
            print(":::node::: node command: %s." % webcast)

        f = open("/tmp/mkchromecast.pid", "rb")
        pidnumber = int(pickle.load(f))
        print(colors.options("PID of main process:") + " " + str(pidnumber))

        localpid = getpid()
        print(colors.options("PID of streaming process: ") + str(localpid))

        while p.poll() is None:
            try:
                time.sleep(0.5)
                # With this I ensure that if the main app fails, everything
                # will get back to normal
                if psutil.pid_exists(pidnumber) is False:
                    inputint()
                    outputint()
                    parent = psutil.Process(localpid)
                    # or parent.children() for recursive=False
                    for child in parent.children(recursive=True):
                        child.kill()
                    parent.kill()
            except KeyboardInterrupt:
                print("Ctrl-c was requested")
                sys.exit(0)
            except IOError:
                print("I/O Error")
                sys.exit(0)
            except OSError:
                print("OSError")
                sys.exit(0)
        else:
            print(colors.warning("Reconnecting node streaming..."))
            if platform == "Darwin" and notifications == "enabled":
                if os.path.exists("images/google.icns") is True:
                    noticon = "images/google.icns"
                else:
                    noticon = "google.icns"
            if debug is True:
                print(
                    ":::node::: platform, tray, notifications: %s, %s, %s."
                    % (platform, tray, notifications)
                )

            if platform == "Darwin" and tray is True and notifications == "enabled":
                reconnecting = [
                    "./notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier",
                    "-group",
                    "cast",
                    "-contentImage",
                    noticon,
                    "-title",
                    "mkchromecast",
                    "-subtitle",
                    "node server failed",
                    "-message",
                    "Reconnecting...",
                ]
                subprocess.Popen(reconnecting)

                if debug is True:
                    print(
                        ":::node::: reconnecting notifier command: %s." % reconnecting
                    )
            relaunch(stream, recasting, kill)
        return
Esempio n. 12
0
def no_bitrate(codec):
    if source_url is None:
        print(colors.warning('The ' + codec +
                             ' codec does not require the bitrate argument.'))
    return
Esempio n. 13
0
Not yet implemented
"""
if args.config == True:
    print(colors.error('This option is not implemented yet.'))
    sys.exit(0)
"""
Version
"""
if args.version is True:
    print('mkchromecast ' + 'v' + colors.success(__version__))
    sys.exit(0)
"""
Update
"""
if args.update is True:
    print(colors.warning('Updating mkchromecast'))
    print(colors.important('git pull --all'))
    pull = subprocess.Popen(['git', 'pull', '--all'],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

    print(pull.stdout.read().decode('utf-8').strip())
    print(colors.important('git fetch -p'))
    prune = subprocess.Popen(['git', 'fetch', '-p'],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    print(prune.stdout.read().decode('utf-8').strip())
    sys.exit(0)
"""
Check that encoders exist in the list
"""
Esempio n. 14
0
    def play_cast(self):
        if self.debug is True:
            print('def play_cast(self):')
        localip = self.ip

        try:
            print(colors.options('The IP of ') +
                  colors.success(self.cast_to) + colors.options(' is:') +
                  ' ' + self.cast.host)
        except TypeError:
            print(colors.options('The IP of ') +
                  colors.success(self.cast_to.player_name) +
                  colors.options(' is:') + ' ' + self.cast_to.ip_address)
        except AttributeError:
            for _ in self.sonos_list:
                if self.cast_to == _.player_name:
                    self.cast_to = _
            print(colors.options('The IP of ') +
                  colors.success(self.cast_to.player_name) +
                  colors.options(' is:') + ' ' + self.cast_to.ip_address)

        if self.host is None:
            print(colors.options('Your local IP is:') + ' ' + localip)
        else:
            print(colors.options('Your manually entered local IP is:') +
                  ' ' + localip)

        try:
            media_controller = self.cast.media_controller

            if self.tray is True:
                config = ConfigParser.RawConfigParser()
                # Class from mkchromecast.config
                from mkchromecast.config import config_manager
                configurations = config_manager()
                configf = configurations.configf

                if os.path.exists(configf) and self.tray is True:
                    print(self.tray)
                    print(colors.warning('Configuration file exists'))
                    print(colors.warning('Using defaults set there'))
                    config.read(configf)
                    self.backend = ConfigSectionMap('settings')['backend']

            if self.source_url is not None:
                if args.video is True:
                    import mkchromecast.video
                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio
                    mtype = mkchromecast.audio.mtype
                print(' ')
                print(colors.options('Casting from stream URL:') + ' ' +
                      self.source_url)
                print(colors.options('Using media type:') + ' ' +
                      mtype)
                media_controller.play_media(
                        self.source_url,
                        mtype,
                        title=self.title,
                        stream_type='LIVE'
                        )
                media_controller.play()
            elif (self.backend == 'ffmpeg' or self.backend == 'node' or
                    self.backend == 'avconv' or self.backend == 'parec' or
                    self.backend == 'gstreamer' and self.source_url is None):
                if args.video is True:
                    import mkchromecast.video
                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio
                    mtype = mkchromecast.audio.mtype
                print(' ')
                print(colors.options('The media type string used is:') +
                      ' ' + mtype)
                media_controller.play_media(
                        'http://' + localip + ':' + self.port + '/stream',
                        mtype,
                        title=self.title,
                        stream_type='LIVE'
                        )

            if media_controller.is_active:
                import time
                time.sleep(2)
                media_controller.play()

            print(' ')
            print(colors.important('Cast media controller status'))
            print(' ')
            print(self.cast.status)
            print(' ')
            if self.hijack is True:
                self.r = Thread(target=self.hijack_cc)
                # This has to be set to True so that we catch
                # KeyboardInterrupt.
                self.r.daemon = True
                self.r.start()
        except AttributeError:
            self.sonos = self.cast_to
            self.sonos.play_uri('x-rincon-mp3radio://' + localip +
                                ':' + self.port + '/stream',
                                title=self.title)
            if self.tray is True:
                self.cast = self.sonos
Esempio n. 15
0
                "-pix_fmt",
                "yuv420p",
                "-g",
                "60",
                # '-b', '900k',
                "-f",
                "mp4",
                "-movflags",
                "frag_keyframe+empty_moov",
                "-vf",
                "subtitles=" + subtitles,
                "pipe:1",
            ]

        elif input_file is not None and subtitles is not None and mkv is True:
            print(colors.warning("Subtitles with mkv are not supported yet."))
            command = [
                "ffmpeg",
                "-re",
                "-i",
                input_file,
                "-i",
                subtitles,
                "-c:v",
                "copy",
                "-c:a",
                "copy",
                "-c:s",
                "mov_text",
                "-map",
                "0:0",
Esempio n. 16
0
    mtype = 'audio/mp4'
else:
    if os.path.exists(configf) and tray is True:
        configurations.chk_config()
        config.read(configf)
        backend = ConfigSectionMap('settings')['backend']
        backends_dict[backend] = backend
        codec = ConfigSectionMap('settings')['codec']
        bitrate = ConfigSectionMap('settings')['bitrate']
        samplerate = ConfigSectionMap('settings')['samplerate']
        adevice = ConfigSectionMap('settings')['alsadevice']
        if adevice == 'None':
            adevice = None
        if debug is True:
            print(':::audio::: tray = ' + str(tray))
            print(colors.warning('Configuration file exists'))
            print(colors.warning('Using defaults set there'))
            print(backend, codec, bitrate, samplerate, adevice)
    else:
        backend = mkchromecast.__init__.backend
        backends_dict[backend] = backend
        codec = mkchromecast.__init__.codec
        bitrate = str(mkchromecast.__init__.bitrate)
        samplerate = str(mkchromecast.__init__.samplerate)

    backends = ['ffmpeg', 'avconv', 'parec']
    if tray is True and backend in backends:
        import os
        import getpass
        USER = getpass.getuser()
        PATH = './bin:./nodejs/bin:/Users/' + \
Esempio n. 17
0
    mtype = "audio/mp4"
else:
    if os.path.exists(configf) and tray is True:
        configurations.chk_config()
        config.read(configf)
        backend = ConfigSectionMap("settings")["backend"]
        backends_dict[backend] = backend
        codec = ConfigSectionMap("settings")["codec"]
        bitrate = ConfigSectionMap("settings")["bitrate"]
        samplerate = ConfigSectionMap("settings")["samplerate"]
        adevice = ConfigSectionMap("settings")["alsadevice"]
        if adevice == "None":
            adevice = None
        if debug is True:
            print(":::audio::: tray = " + str(tray))
            print(colors.warning("Configuration file exists"))
            print(colors.warning("Using defaults set there"))
            print(backend, codec, bitrate, samplerate, adevice)
    else:
        backend = mkchromecast.__init__.backend
        backends_dict[backend] = backend
        codec = mkchromecast.__init__.codec
        bitrate = str(mkchromecast.__init__.bitrate)
        samplerate = str(mkchromecast.__init__.samplerate)

    backends = ["ffmpeg", "avconv", "parec"]
    if tray is True and backend in backends:
        import os
        import getpass

        USER = getpass.getuser()
Esempio n. 18
0
    def play_cast(self):
        if self.debug == True:
            print('def play_cast(self):')
        localip = self.ip

        print(
            colors.options('The IP of ') + colors.success(self.cast_to) +
            colors.options(' is:') + ' ' + self.cast.host)
        if self.host == None:
            print(colors.options('Your local IP is:') + ' ' + localip)
        else:
            print(
                colors.options('Your manually entered local IP is:') + ' ' +
                localip)
        """
        if self.youtubeurl != None:
            print(colors.options('The Youtube URL chosen:')+' '+self.youtubeurl)
            import pychromecast.controllers.youtube as youtube
            yt = youtube.YouTubeController()
            self.cast.register_handler(yt)

            try:
                import urlparse
                url_data = urlparse.urlparse(self.youtubeurl)
                query = urlparse.parse_qs(url_data.query)
            except ImportError:
                import urllib.parse
                url_data = urllib.parse.urlparse(self.youtubeurl)
                query = urllib.parse.parse_qs(url_data.query)
            video = query["v"][0]
            print(colors.options('Playing video:')+' '+video)
            yt.play_video(video)
        else:
        """
        media_controller = self.cast.media_controller

        if self.tray == True:
            config = ConfigParser.RawConfigParser()
            configurations = config_manager()  # Class from mkchromecast.config
            configf = configurations.configf

            if os.path.exists(configf) and self.tray == True:
                print(tray)
                print(colors.warning('Configuration file exists'))
                print(colors.warning('Using defaults set there'))
                config.read(configf)
                self.backend = ConfigSectionMap('settings')['backend']

        if self.sourceurl != None:
            if args.video == True:
                import mkchromecast.video
                mtype = mkchromecast.video.mtype
            else:
                import mkchromecast.audio
                mtype = mkchromecast.audio.mtype
            print(' ')
            print(
                colors.options('Casting from stream URL:') + ' ' +
                self.sourceurl)
            print(colors.options('Using media type:') + ' ' + mtype)
            media_controller.play_media(self.sourceurl,
                                        mtype,
                                        title=self.title)
        elif (self.backend == 'ffmpeg' or self.backend == 'node'
              or self.backend == 'avconv' or self.backend == 'parec'
              or self.backend == 'gstreamer' and self.sourceurl == None):
            if args.video == True:
                import mkchromecast.video
                mtype = mkchromecast.video.mtype
            else:
                import mkchromecast.audio
                mtype = mkchromecast.audio.mtype
            print(' ')
            print(
                colors.options('The media type string used is:') + ' ' + mtype)
            media_controller.play_media('http://' + localip + ':5000/stream',
                                        mtype,
                                        title=self.title)
        print(' ')
        print(colors.important('Cast media controller status'))
        print(' ')
        print(self.cast.status)
        print(' ')
        if self.reconnect == True:
            self.r = Thread(target=self.reconnect_cc)
            self.r.daemon = True  # This has to be set to True so that we catch KeyboardInterrupt.
            self.r.start()
Esempio n. 19
0
Not yet implemented
"""
if args.config is True:
    print(colors.error('This option is not implemented yet.'))
    sys.exit(0)
"""
Version
"""
if args.version is True:
    print('mkchromecast ' + 'v' + colors.success(__version__))
    sys.exit(0)
"""
Update
"""
if args.update is True:
    print(colors.warning('Updating Mkchromecast'))
    print(colors.important('git pull --all'))
    pull = subprocess.Popen(['git', 'pull', '--all'],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

    print(pull.stdout.read().decode('utf-8').strip())
    print(colors.important('git fetch -p'))
    prune = subprocess.Popen(['git', 'fetch', '-p'],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    print(prune.stdout.read().decode('utf-8').strip())
    sys.exit(0)
"""
Check that encoders exist in the list
"""
Esempio n. 20
0
if debug is True:
    print('Google Cast name: %s.' % device_name)

"""
Check that input file exists
"""
if input_file != None and os.path.isfile(input_file) is False:
    if platform == 'Darwin':
        from mkchromecast.audio_devices import inputint, outputint
        inputint()
        outputint()
    else:
        from mkchromecast.pulseaudio import remove_sink
        remove_sink()

    print(colors.warning('File not found!'))
    terminate()

"""
Media-Type
"""
mtype = args.mtype

if args.mtype is not None and args.video is False:
    print(colors.warning('The media type is not supported for audio.')
          % args.encoder_backend)

"""
Reset
"""
if args.reset is True:
Esempio n. 21
0
    def show_control(self, control):
        """Method to show controls"""
        if control == True:
            from mkchromecast.getch import getch, pause

            self.controls_msg()
            try:
                while (True):
                    key = getch()
                    if (key == 'u'):
                        self.cc.volume_up()
                        if self.encoder_backend == 'ffmpeg':
                            if self.debug == True:
                                self.controls_msg()
                    elif (key == 'd'):
                        self.cc.volume_down()
                        if self.encoder_backend == 'ffmpeg':
                            if self.debug == True:
                                self.controls_msg()
                    elif (key == 'p'):
                        if self.videoarg == True:
                            print('Pausing Casting Process...')
                            action = 'pause'
                            self.backend_handler(action, self.encoder_backend)
                            if self.encoder_backend == 'ffmpeg':
                                if self.debug == True:
                                    self.controls_msg()
                        else:
                            pass
                    elif (key == 'r'):
                        if self.videoarg == True:
                            print('Resuming Casting Process...')
                            action = 'resume'
                            self.backend_handler(action, self.encoder_backend)
                            if self.encoder_backend == 'ffmpeg':
                                if self.debug == True:
                                    self.controls_msg()
                        else:
                            pass
                    elif (key == 'q'):
                        print(colors.error('Quitting application...'))
                        self.terminate_app()
                    elif (key == '\x03'):
                        raise KeyboardInterrupt
                        atexit.register(self.terminate_app())
            except KeyboardInterrupt:
                self.terminate_app()

        else:
            if self.platform == 'Linux' and self.adevice == None:
                print(
                    colors.warning(
                        'Remember to open pavucontrol and select the mkchromecast sink.'
                    ))
            print('')
            print(colors.error('Ctrl-C to kill the Application at any Time'))
            print('')
            try:
                input()
            except KeyboardInterrupt:
                atexit.register(self.terminate_app())
Esempio n. 22
0
"""
Check that input file exists
"""
if input_file != None and os.path.isfile(input_file) is False:
    if platform == "Darwin":
        from mkchromecast.audio_devices import inputint, outputint

        inputint()
        outputint()
    else:
        from mkchromecast.pulseaudio import remove_sink

        remove_sink()

    print(colors.warning("File not found!"))
    terminate()

"""
Media-Type
"""
mtype = args.mtype

if args.mtype is not None and args.video is False:
    print(
        colors.warning("The media type is not supported for audio.")
        % args.encoder_backend
    )

"""
Reset
Esempio n. 23
0
    def play_cast(self):
        if self.debug is True:
            print("def play_cast(self):")
        localip = self.ip

        try:
            print(
                colors.options("The IP of ") + colors.success(self.cast_to) +
                colors.options(" is:") + " " + self.cast.host)
        except TypeError:
            print(
                colors.options("The IP of ") +
                colors.success(self.cast_to.player_name) +
                colors.options(" is:") + " " + self.cast_to.ip_address)
        except AttributeError:
            for _ in self.sonos_list:
                if self.cast_to == _.player_name:
                    self.cast_to = _
            print(
                colors.options("The IP of ") +
                colors.success(self.cast_to.player_name) +
                colors.options(" is:") + " " + self.cast_to.ip_address)

        if self.host is None:
            print(colors.options("Your local IP is:") + " " + localip)
        else:
            print(
                colors.options("Your manually entered local IP is:") + " " +
                localip)

        try:
            media_controller = self.cast.media_controller

            if self.tray is True:
                config = ConfigParser.RawConfigParser()
                # Class from mkchromecast.config
                from mkchromecast.config import config_manager

                configurations = config_manager()
                configf = configurations.configf

                if os.path.exists(configf) and self.tray is True:
                    print(self.tray)
                    print(colors.warning("Configuration file exists"))
                    print(colors.warning("Using defaults set there"))
                    config.read(configf)
                    self.backend = ConfigSectionMap("settings")["backend"]

            if self.source_url is not None:
                if args.video is True:
                    import mkchromecast.video

                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio

                    mtype = mkchromecast.audio.mtype
                print(" ")
                print(
                    colors.options("Casting from stream URL:") + " " +
                    self.source_url)
                print(colors.options("Using media type:") + " " + mtype)
                media_controller.play_media(self.source_url,
                                            mtype,
                                            title=self.title,
                                            stream_type="LIVE")
                media_controller.play()
            elif (self.backend == "ffmpeg" or self.backend == "node"
                  or self.backend == "avconv" or self.backend == "parec"
                  or self.backend == "gstreamer" and self.source_url is None):
                if args.video is True:
                    import mkchromecast.video

                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio

                    mtype = mkchromecast.audio.mtype
                print(" ")
                print(
                    colors.options("The media type string used is:") + " " +
                    mtype)
                media_controller.play_media(
                    "http://" + localip + ":" + self.port + "/stream",
                    mtype,
                    title=self.title,
                    stream_type="LIVE",
                )

            if media_controller.is_active:
                media_controller.play()

            print(" ")
            print(colors.important("Cast media controller status"))
            print(" ")
            print(self.cast.status)
            print(" ")

            time.sleep(5.0)
            media_controller.play()

            if self.hijack is True:
                self.r = Thread(target=self.hijack_cc)
                # This has to be set to True so that we catch
                # KeyboardInterrupt.
                self.r.daemon = True
                self.r.start()

        except AttributeError:
            self.sonos = self.cast_to
            self.sonos.play_uri(
                "x-rincon-mp3radio://" + localip + ":" + self.port + "/stream",
                title=self.title,
            )
            if self.tray is True:
                self.cast = self.sonos