mindau
10/25/2017 - 9:22 PM

Record Stream

Capture internet stream to file for python with ffmpeg

# ! python
import os, sys, urllib, time, signal, multiprocessing
from time import gmtime, strftime
from subprocess import Popen, PIPE
import httplib2
import json
import requests

TWITCH_VERSION_HEADER = "application/vnd.twitchtv.v5+json"
CHUNKSIZE = 10 * 1024 * 1024 # 10MB chunk size for video parts

#TO FILL
TOKEN = "XXXXXXX"
TWITCH_CLIENT_ID = "XXXXXXX"
USER_ID = "XXXXXX"

def get_channel_name(twitch_auth_token):
    url = 'https://api.twitch.tv/kraken/user'
    headers = {'Authorization': 'OAuth ' + twitch_auth_token,
             'Accept': TWITCH_VERSION_HEADER,
             'Client-ID': TWITCH_CLIENT_ID }  
    r = requests.get(url, headers=headers)
    user = r.json()
    #print user
    return user['name']

def create_twitch_video(title, description, tags, twitch_auth_token):

    print ('Creating video on Twitch... with title' + str(title))
    url = 'https://api.twitch.tv/kraken/videos'
    payload = {'channel_name': get_channel_name(twitch_auth_token),
               'channel_id': USER_ID,
               'title': title,
               'description': description,
               'tags': tags }   
    headers = {'Authorization': 'OAuth ' + twitch_auth_token,
               'Accept': TWITCH_VERSION_HEADER,
               'Client-ID': TWITCH_CLIENT_ID,
               'channel_id': USER_ID,
               'Content-Type': 'application/json' }
    r = requests.post(url, json=payload, headers=headers)
    video = r.json()
    print (video)
    return video["upload"]["url"], video["upload"]["token"]

def upload_to_twitch(filename, upload_url, upload_token):
    print(filename)
    print(upload_url)
    print(upload_token)
    print ("Uploading " + filename + " to Twitch via " + upload_url + ", " + str(CHUNKSIZE) + " bytes at a time..." )

    file = open(filename, 'rb')
    index = 0
    while 1:
      chunk = file.read(CHUNKSIZE)
      if not chunk: break
      index += 1
      headers = {'Accept': TWITCH_VERSION_HEADER,
                 'Client-ID': TWITCH_CLIENT_ID,
                 'Content-Length': str(len(chunk)) }
      params = {'part': index,
                 'upload_token': upload_token }
      r = requests.put(upload_url, params=params, data=chunk, headers=headers)
      print ('Completed uploading part ' + str(index))
    file.close()

    headers = {'Accept': TWITCH_VERSION_HEADER,
               'Client-ID': TWITCH_CLIENT_ID }
    params = {'upload_token': upload_token }
    r = requests.post(upload_url + '/complete', params=params, headers=headers)
    print ("DONE!!!!!!!!!")
    return


def main(argv):
    print 
    upload_url, upload_token = create_twitch_video(sys.argv[1], "VIDEO_DESCRIPTION", "VIDEO_TAGS", TOKEN)
    upload_to_twitch(sys.argv[2], upload_url, upload_token)
    #os.remove(sys.argv[2])

if __name__ == "__main__":
    main(sys.argv)

# ! python
import os, sys, urllib, traceback, time, signal, multiprocessing
from time import gmtime, strftime
from subprocess import Popen, PIPE, call
import httplib2
import json
import requests

def record():
    #interval = 43200 # 12h
    interval =3600    
    SRC = 'http://...........playlist.m3u8'

    while True:
        video_time =  time.strftime("%B%d_%H-%M", time.localtime())
        video_title = '"' + time.strftime("%B %d %H:%M", time.localtime())
        path_and_file = "videos/" + video_time + ".flv"

        cmd = ['ffmpeg',
                 '-hide_banner',
                 '-i',
                 SRC,
                 '-vcodec', 'copy',
                 '-acodec', 'aac','-strict', '-2',
                 '-crf' ,'20',
                 '-f', 'flv',
                 '-b:a', '128k',
                 path_and_file,
        ]

        cmd_str = ' '.join(cmd)

        print("Interval=  " + str(interval))
        print("Calling  " + cmd_str)
        print("Capturing stream to " + str(path_and_file))

        p = Popen(cmd_str, shell=True)
        time.sleep(interval)

        print("Sleep interval "+ str(interval)+ " is done. now killing process " + str(p.pid))

        #kill all ffmpeg processes
        pkill("ffmpeg")
        title = video_title + time.strftime(" - %H:%M", time.localtime()) + '"'

        call(["py", "twitchUpload.py", title, path_and_file])

def pkill (process_name):
    try:
        killed = os.system('tskill ' + process_name)
    except Exception:
        killed = 0
    return killed

def main(argv):
    print ("FFMPEG python script started...")
    record()
    #print "starting recording: "
    #print strftime("%Y-%m-%d %H:%M:%S", gmtime())

if __name__ == "__main__":
main(sys.argv)
#! python
import time
import subprocess as sp, sys
import urllib

def record():
    sourcePath ='https://url.m3u8'
    name = '_video.ts'

    destPath = time.strftime("%Y-%m-%d_%H-%M-%S", time.gmtime()) + name

    command = [ 'ffmpeg',
    '-y',  # (optional) overwrite output file if it exists
    '-hide_banner',
    '-loglevel', 'panic',
    '-i',
    sourcePath,
    '-vcodec', 'copy',
    '-acodec', 'copy',
    '-ss', '00:00:00.0',
    '-t', '01:00:00.0',
   # '-profile:v','high',
   # '-preset','slow',
   # '-threads', '2',
    destPath]

    returnExitCode = sp.call(command)

    if returnExitCode != 0:
        url_status = urllib.urlopen(sourcePath).getcode()
        if url_status != 200:
            print "Bad url response = " + str(url_status) + " Check source url"
        else:
            print  "Error in ffmpeg"
            print(returnExitCode)
        print "Waiting 10 seconds"
        time.sleep(10)
    else:
        print "ALL OK"
        # print(returnExitCode)

       # print(destPath)

 
def main(argv):
    print "Program started..."
    while True:
        record()

if __name__ == "__main__":
main(sys.argv)