Skip to content

Instantly share code, notes, and snippets.

@ZiTAL
Last active May 3, 2024 16:55
Show Gist options
  • Save ZiTAL/6ef8e5a3b0c03698d67eeed8eddad30d to your computer and use it in GitHub Desktop.
Save ZiTAL/6ef8e5a3b0c03698d67eeed8eddad30d to your computer and use it in GitHub Desktop.
Dragoi Bola: Twitch plataforman 24/7 martxan!
import os
import sys
import subprocess
import re
import tempfile
from datetime import timedelta
from collections import OrderedDict
sys.path.append('../../')
from src.TwitchFfmpeg import TwitchFfmpeg, TwitchConfig
def refreshToken():
try:
tf = TwitchFfmpeg("../../config")
tf.Api.refreshToken()
except subprocess.CalledProcessError as e:
error = "refreshToken"
print(f"Error {error}: ", e.stderr)
def str2ms(time):
t = timedelta(hours=int(time[:2]), minutes=int(time[3:5]), seconds=int(time[6:8]), milliseconds=int(time[9:]+"0"))
ml = int(t.total_seconds() * 1000)
return ml
def getVideoInfo(file):
result = ''
command = ['ffmpeg-rockchip', '-i', file]
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) as process:
for line in process.stdout:
result = result + line
return result
def getDuration(video_info):
m = re.search(r"Duration:\s+([0-9]+:[0-9]+:[0-9]+\.[0-9]+)", video_info, re.MULTILINE)
if m:
return str2ms(m.group(1))
def getTitle(video_info):
m = re.search(r"\s+title\s+:\s+([^\n]+)", video_info, re.MULTILINE)
if m:
return m.group(1).strip()
def getVideos(folder, exts):
videos = []
for file in os.listdir(folder):
ext = os.path.splitext(file)[1][1:].lower()
if ext in exts:
videos.append(os.path.join(os.path.realpath(folder), file))
videos = sorted(videos)
return videos
def getMsFromStreamLine(line):
m = re.search("time=([0-9]+:[0-9]+:[0-9]+\.[0-9]+)", line.strip())
if m:
return str2ms(m.group(1))
def getVideoInfoFromVideoList(ms, videos_dict):
for key,value in videos_dict.items():
if int(ms)<int(key):
value['ms'] = key
return value
def setTempFile(data):
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
tmp_file.write(data.encode('utf-8'))
tmp_file.flush()
return tmp_file.name
def setCurrentVideo(i):
with open("./current", 'w') as file:
file.write(i)
file.flush()
return True
def getCurrentVideo():
try:
with open("./current", 'r') as file:
for line in file:
return line.strip()
except:
return None
def removeCurrentVideo():
try:
os.unlink("./current")
except Exception as e:
print(e)
def removeConcatFile(concat_file):
os.unlink(concat_file)
def getTwitchUrl():
tc = TwitchConfig("../../config")
twitch_channel = tc.getChannel()
twitch_url = f"{twitch_channel['server']}{twitch_channel['key']}"
return twitch_url
def setStreamTitle(title):
refreshToken()
tf = TwitchFfmpeg("../../config")
tf.Api.setStreamTitle(title)
def main():
refreshToken()
videos_dict = OrderedDict()
videos = getVideos("./", ["mp4"])
# videos = videos[:10]
# videos = ["/home/projects/twitch-ffmpeg/multimedia/db/01.mp4", "/home/projects/twitch-ffmpeg/multimedia/db/02.mp4", "/home/projects/twitch-ffmpeg/multimedia/db/03.mp4"]
key = 0
concat_info = ""
current_video = getCurrentVideo()
_continue = False
for i in videos:
video_info = getVideoInfo(i)
if current_video == None or i == current_video:
_continue = True
if _continue:
duration = getDuration(video_info)
title = getTitle(video_info)
key = key + duration
videos_dict[key] = {"title": title, "file": i}
concat_info = concat_info + f"file '{i}'\n"
concat_file = setTempFile(concat_info)
command = ['ffmpeg-rockchip', '-re', '-f', 'concat', '-safe', '0', '-i', concat_file, '-codec', 'copy', '-bufsize', '5000k', '-tune', 'zerolatency', '-g', '60', '-f', 'flv', getTwitchUrl()]
title = ''
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) as process:
for line in process.stdout:
try:
ms = getMsFromStreamLine(line)
if ms:
video_tmp = getVideoInfoFromVideoList(ms, videos_dict)
if title != video_tmp['title']:
title = video_tmp['title']
setCurrentVideo(video_tmp['file'])
setStreamTitle(title)
except Exception as e:
error = f"main: {e}"
print(error)
removeConcatFile(concat_file)
removeCurrentVideo()
while True:
main()
# /etc/systemd/system/db.service/db.service
[Unit]
Description=Dragoi Bola Zuzenean
After=network.target
[Service]
WorkingDirectory=/home/projects/twitch-ffmpeg/multimedia/db
User=pi
Group=pi
Restart=on-failure
RestartSec=5
ExecStart=/usr/bin/python3 /home/projects/twitch-ffmpeg/multimedia/db/db.py
[Install]
WantedBy=multi-user.target
@ZiTAL
Copy link
Author

ZiTAL commented Mar 27, 2024

systemctl daemon-reload

hasi:

systemctl start db.service

gelditu:

systemctl stop db.service

egoera ikusi:

systemctl status db.service

Geldituz gero current fitxategian egungo bideoaren path-a sartuko da, berriz hasterakoan bideo hortatik hasiko da berriz, hasieratik nahi izanez gero current fitxategia ezabatu beharko da.

@ekaitz-zarraga
Copy link

@ZiTAL
Copy link
Author

ZiTAL commented Apr 2, 2024

eskerrik asko txo! @ekaitz-zarraga

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment