Skip to content

Instantly share code, notes, and snippets.

@Hellowlol
Last active February 24, 2018 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hellowlol/96e4e7b3591eebc3ec0a4de9f5883fdf to your computer and use it in GitHub Desktop.
Save Hellowlol/96e4e7b3591eebc3ec0a4de9f5883fdf to your computer and use it in GitHub Desktop.
Find end of intro using ffmpeg filters blackdetect and silencedetect
import subprocess
import re
from profilehooks import timecall
def with_in(first, second, dev=5):
x = first - second
y = second - first
if abs(x) <= dev and abs(y) <= dev:
return True
return False
def to_time(sec):
if sec == -1:
return '00:00'
m, s = divmod(sec, 60)
return '%02d:%02d' % (m, s)
@timecall(immediate=True)
def find_offset_ffmpeg(afile, trim=600):
cmd = [
'ffmpeg', '-i', afile, '-t', str(trim), '-vf',
'blackdetect=d=2:pix_th=0.00', '-af', 'silencedetect=n=-50dB:d=0.5',
'-f', 'null', '-'
]
print(' '.join(cmd))
proc = subprocess.Popen(
cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
temp_silence = []
final_audio = []
final_video = []
audio_reg = re.compile('silence_\w+:\s+?(-?\d+\.\d+|\d)')
black_reg = re.compile('black_\w+:(\d+\.\d+|\d)')
while True:
line = proc.stderr.readline()
line = line.decode('utf-8').strip()
if line:
audio_res = re.findall(audio_reg, line)
# Audio shit is sometime on several lines...
if audio_res:
temp_silence.extend(audio_res)
if len(temp_silence) == 3:
k = temp_silence[:]
kk = [float(i) for i in k]
final_audio.append(kk)
temp_silence[:] = []
video_res = re.findall(black_reg, line)
if video_res:
f = [float(i) for i in video_res]
final_video.append(f)
else:
break
print('final_video', final_video)
print('final_audio', final_audio)
# the sub lists are [start, end, duration]
for video in reversed(final_video):
for aud in final_audio:
# Sometime times there are black shit the first 15 sec. lets skip that to remove false positives
if video[1] > 15: # end time of black shit..
# if silence is within black shit its ok.
if aud and with_in(aud[0], video[0]) and with_in(aud[1], video[1]):
print(to_time(video[1]))
return video[1]
return -1
#if __name__ == '__main__':
find_offset_ffmpeg(r'C:\steffen\test_plexapi\Dexter.s01e01.mkv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment