#!/usr/bin/env python

import os.path
import subprocess

def get_usable_rtmpdump(cmd):
    try:
        p = subprocess.Popen([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        return cmd
    except:
        return None

RTMPDUMP = get_usable_rtmpdump('rtmpdump')

def has_rtmpdump_installed():
    return RTMPDUMP is not None

#
#params ={"-y":"playlist","-q":None,}
#if Only Key ,Value should be None
#-r -o should not be included in params

def download_rtmpdump_stream(url, title, ext,params={},output_dir='.'):
    filename = '%s.%s' % (title, ext)
    filepath = os.path.join(output_dir, filename)

    cmdline = [RTMPDUMP, '-r']
    cmdline.append(url)
    cmdline.append('-o')
    cmdline.append(filepath)

    for key in params.keys():
        cmdline.append(key)
        if params[key]!=None:
            cmdline.append(params[key])

    # cmdline.append('-y')
    # cmdline.append(playpath)
    print("Call rtmpdump:\n"+" ".join(cmdline)+"\n")
    subprocess.call(cmdline)
    return

#
#To be refactor
#To the future myself: Remember to refactor the same function in ffmpeg.py
#
def play_rtmpdump_stream(player, url, params={}):
    cmdline="rtmpdump -r '%s' "%url
    for key in params.keys():
        cmdline+=key+" "+params[key] if params[key]!=None else ""+" "
    cmdline+=" -o - | %s -"%player
    print(cmdline)
    os.system(cmdline)
    # os.system("rtmpdump -r '%s' -y '%s' -o - | %s -" % (url, playpath, player))
    return

@@ -1041,354 +1041,567 @@
 %0A%0A#%0A
-#To be refactor%0A#To the future myself: Remember to refactor the same function in ffmpeg.py%0A#%0Adef play_rtmpdump_stream(player, url, params=%7B%7D):%0A    cmdline=%22rtmpdump -r '%25s' %22%25url%0A    for key in params.keys():%0A        cmdline+=key+%22 %22+params%5Bkey%5D if params%5Bkey%5D!=None else %22%22+%22 %22%0A    cmdline+=%22 -o - %7C %25s -%22%25player%0A    print(cmdline)%0A    os.system
+def play_rtmpdump_stream(player, url, params=%7B%7D):%0A    %0A    #construct left side of pipe%0A    cmdline = %5BRTMPDUMP, '-r'%5D%0A    cmdline.append(url)%0A    %0A    #append other params if exist%0A    for key in params.keys():%0A        cmdline.append(key)%0A        if params%5Bkey%5D!=None:%0A            cmdline.append(params%5Bkey%5D)%0A%0A    cmdline.append('-o')%0A    cmdline.append('-')%0A%0A    #pipe start%0A    cmdline.append('%7C')%0A    cmdline.append(player)%0A    cmdline.append('-')%0A%0A    #logging%0A    print(%22Call rtmpdump:%5Cn%22+%22 %22.join(cmdline)+%22%5Cn%22)%0A%0A    #call RTMPDump!%0A    subprocess.call
 (cmd
@@ -1602,24 +1602,29 @@
 ll(cmdline)%0A
+    %0A
     # os.sys

Fix rtmpdump not portable under Windows