Skip to content

Commit

Permalink
FFMpeg path fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
anon1efergwerfwer committed May 16, 2022
1 parent 6a55060 commit 6db89be
Show file tree
Hide file tree
Showing 5 changed files with 114 additions and 69 deletions.
38 changes: 24 additions & 14 deletions Beats2Fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@ def write_beatfiles(beats, output_name, song_lenth):
parsers.parsetxt.write_beats(beats, output_name)
parsers.parsefs.write_beats(beats, output_name)
beatutil.plot_beats(beats, output_name, song_lenth)

def get_song_length(song):
result = subprocess.run('ffprobe -v quiet -show_entries format=duration -of csv="p=0" "%s"' % (song), stdout=subprocess.PIPE)
return float(result.stdout.strip())

def process_beats(beats, song_length, clip_dist):
if beats[0] == 0:
Expand All @@ -49,36 +45,39 @@ def process_beats(beats, song_length, clip_dist):
def detect_input(input):
return beatutil.find_beats(input, song_required=True)

def make_pmv(beatinput, vid_folder, fps, recurse, clip_dist, num_vids, beatbar):
def make_pmv(beatinput, vid_folder, fps, recurse, clip_dist, num_vids, beatbar, output_folder):
print("Input: {} - Video dir: {} - Output dir: {}".format(beatinput, vid_folder, output_folder))

with util.UHalo(text="Checking input") as h:
detected_input = detect_input(beatinput)
if not detected_input:
h.fail('No usable input detected')
return False
else:
song = detected_input[0]
song_lenth = get_song_length(song)
song_lenth = videoutil.get_song_length(song)
all_beat_times = detected_input[1]
output_name = os.path.splitext(os.path.basename(song))[0] + '-PMV'
h.succeed('Input - Song: {} - Beatcount: {}, - Output: {} '.format(song, len(all_beat_times), output_name))

if not os.path.exists('out'):
os.mkdir('out')
output_file = os.path.realpath('{}/{}.mp4'.format(output_folder, output_name))
h.succeed('Input - Song: {} - Beatcount: {}, - Output: {} '.format(song, len(all_beat_times), output_file))

output_file = 'out/{}.mp4'.format(output_name)
if not output_folder:
output_folder = 'out'
if not os.path.exists(output_folder):
os.mkdir(output_folder)

with util.UHalo(text="Getting and processing beats") as h:
beats_reduced = process_beats(all_beat_times, song_lenth, clip_dist)
h.succeed()

videos = videoutil.videos_get(vid_folder, recurse, num_vids)
if not videos:
print('No videos')
print('Getting videos failed')
return False

clips = videoutil.clips_get(videos, beats_reduced, fps)
if not clips:
print('No clips')
print('Getting clips failed')
return False

videos_file = videoutil.clips_generate_batched(clips, fps)
Expand Down Expand Up @@ -107,7 +106,7 @@ def make_pmv(beatinput, vid_folder, fps, recurse, clip_dist, num_vids, beatbar):
videoutil.clips_merge(output_file, song, videos_file, song_lenth)

with util.UHalo(text="Witing beat files") as h:
write_beatfiles(all_beat_times, 'out/' + output_name, song_lenth)
write_beatfiles(all_beat_times, output_folder + '/' + output_name, song_lenth)
h.succeed()

print(output_file + " is done")
Expand Down Expand Up @@ -150,6 +149,17 @@ def main():
}
)

parser.add_argument(
'-output_folder',
help='Where to store the output videos / scripts',
widget='DirChooser',
metavar="Output folder",
default="out",
gooey_options={
'message': "Pick output folder"
}
)

parser.add_argument('-recurse', metavar="Search resursive", help='Search videos recursively', action='store_true')
parser.add_argument('-clip_dist', metavar="Clip distance", default=0.4, help='Minimal clip distance in seconds', type=float, widget='DecimalField')
parser.add_argument('-fps', metavar="FPS", default=25, help='Output video FPS', type=int, widget='IntegerField')
Expand Down
2 changes: 2 additions & 0 deletions beatutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ def find_beats(input, option=None, song_required=False):
for p in loaded_parsers:
beats = p.process_input(input, option)
if not beats:
print('x1')
continue
if song_required and not beats[0]:
print('x2')
continue

return beats
Expand Down
12 changes: 8 additions & 4 deletions parsers/parsesm.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def handle_input(simfile, option=None):
files = os.listdir(file_base)
songsearch = fnmatch.filter(files, '*.mp3') + fnmatch.filter(files, '*.ogg')
if len(songsearch) == 0:
print("Song not found for: {}".format(simfile))
return False

song = file_base + '/' + songsearch[0]
Expand All @@ -57,13 +58,16 @@ def find_input(input):
def process_input(input, option=None):
if not os.path.exists(input):
return False

if not os.path.isfile(input):

if os.path.isfile(input):
return handle_input(input, option)

if os.path.isdir(input):
input = find_input(input)
if not input:
return False
return handle_input(input, option)

return False

def find_options(input):
if not os.path.exists(input):
Expand Down
13 changes: 10 additions & 3 deletions util.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from tqdm import tqdm

current_tmp_dir = False
global app_mode
app_mode = None

def get_tmp_file(ext):
Expand All @@ -25,7 +26,9 @@ def get_tmp_dir():
return current_tmp_dir

def init_app_mode():
global app_mode
app_mode = 'plain'

if "--ignore-gooey" in sys.argv:
app_mode = 'goo'
elif len(sys.argv) >= 2:
Expand All @@ -37,15 +40,19 @@ def get_app_mode():
def UHalo(**args):
spinner = 'dots'
if app_mode == 'goo':
spinner = {'interval': 1000, 'frames': ['.', '..', '...']}
spinner = {'interval': 1000, 'frames': ['.', '. .', '. . .']}

return Halo(spinner=spinner, **args)

tout = None

class Utqdm(tqdm):
def __init__(self, iterable=None, **args):
super().__init__(iterable=iterable, **args)
if app_mode == 'goo':
super().__init__(iterable=iterable, **args, ascii=True)
else:
super().__init__(iterable=iterable, **args)

#tout = io.StringIO()

#if app_mode != 'goo':
Expand All @@ -71,5 +78,5 @@ def clamp(n, smallest, largest):

def get_resource(name):
d = dirname(abspath(__file__))
ret = d + "/Resources/" + name
ret = os.path.realpath(d + "/Resources/" + name)
return ret
118 changes: 70 additions & 48 deletions videoutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
video_formats = ['.mp4', '.wmv', '.mov', '.m4v', '.mpg', '.avi', '.flv']

def ffmpeg_run(pts_in, filters, pts_out, silent = True, expected_length = 0, description = None, bar_pos=None):
ff_path = util.get_resource('ffmpeg/ffmpeg')
ff_path = util.get_resource('ffmpeg/ffmpeg.exe')

cmd_pts = [ff_path + ' -hide_banner -y'] + pts_in

Expand All @@ -36,48 +36,54 @@ def ffmpeg_run(pts_in, filters, pts_out, silent = True, expected_length = 0, des

cmd_pts += pts_out
cmd = ' '.join(cmd_pts)

has_error = False

if not silent:
print(cmd)
os.system(cmd)
return True

pbar = None
last_pos = 0
if expected_length:
bar_end = math.ceil(expected_length)
pbar = tqdm(total=math.ceil(expected_length), desc=description, position=bar_pos)

regx = re.compile(r"time=([\d\:\.]+)")

with subprocess.Popen(cmd, stdout=PIPE, stderr=STDOUT, bufsize=1, universal_newlines=True) as p:
for l in p.stdout:
if 'No decoder surfaces left' in l:
p.terminate()
has_error = True
if 'Error' in l:
p.terminate()
has_error = True

status_line = regx.search(l)
if status_line and pbar:
current_time = from_timestamp(status_line[1])
newseconds = round(current_time - last_pos)
pbar.update(newseconds)
last_pos += newseconds

p.wait()
retcode = p.returncode
if retcode != 0:
has_error = True

if has_error:
raise Exception("ffmpeg failed with {}: command: {}".format(retcode, cmd))

if pbar and last_pos != bar_end:
pbar.update(bar_end - last_pos)
try:
error_msg = None

if not silent:
print(cmd)
os.system(cmd)
return True

pbar = None
last_pos = 0
if expected_length:
bar_end = math.ceil(expected_length)
pbar = tqdm(total=math.ceil(expected_length), desc=description, position=bar_pos)

regx = re.compile(r"time=([\d\:\.]+)")

with subprocess.Popen(cmd, stdout=PIPE, stderr=STDOUT, bufsize=1, universal_newlines=True) as p:
for l in p.stdout:
if 'No decoder surfaces left' in l:
p.terminate()
error_msg = l
if 'Error' in l:
p.terminate()
error_msg = l

status_line = regx.search(l)
if status_line and pbar:
current_time = from_timestamp(status_line[1])
newseconds = round(current_time - last_pos)
pbar.update(newseconds)
last_pos += newseconds

p.wait()
retcode = p.returncode
if retcode != 0 and not error_msg:
error_msg = "Invalid return code"

if error_msg:
raise Exception(error_msg)

if pbar and last_pos != bar_end:
pbar.update(bar_end - last_pos)

except BaseException as e:
print("Exception during ffmpeg: {} - {}".format(cmd, retcode))
raise e


def videos_get(vid_folder, vids_deep, num_vids):
videos = glob(vid_folder + "/*.mp4") + glob(vid_folder + "/*.wmv")
Expand All @@ -93,7 +99,7 @@ def videos_get(vid_folder, vids_deep, num_vids):

video_states = []

with util.Utqdm(total=len(videos), desc="Video clip analasys", ascii=False) as pbar:
with util.Utqdm(total=len(videos), desc="Video clip analasys") as pbar:
def callback(result):
pbar.update()
util.handle_tqdm_out()
Expand All @@ -113,11 +119,26 @@ def callback(result):
return video_states

def video_length(v):
ff_path = util.get_resource('ffmpeg/ffprobe')
result = subprocess.run(ff_path + ' -show_entries format=duration -v quiet -of csv="p=0" -i "%s"' % (v), stdout=subprocess.PIPE)
vid_length = result.stdout.strip()
vid_length = float(vid_length)
return vid_length
try:
ff_path = util.get_resource('ffmpeg/ffprobe.exe')
cmd = ff_path + ' -show_entries format=duration -v quiet -of csv="p=0" -i "%s"' % (v)
result = subprocess.run(ff_path + ' -show_entries format=duration -v quiet -of csv="p=0" -i "%s"' % (v), stdout=subprocess.PIPE)
vid_length = result.stdout.strip()
vid_length = float(vid_length)
return vid_length
except BaseException as e:
print("Exception during ffmpeg: {}".format(cmd))
raise e

def get_song_length(song):
try:
ff_path = util.get_resource('ffmpeg/ffprobe.exe')
cmd = ff_path + ' -v quiet -show_entries format=duration -of csv="p=0" "%s"' % (song)
result = subprocess.run(cmd, stdout=subprocess.PIPE)
return float(result.stdout.strip())
except BaseException as e:
print("Exception during ffmpeg: {}".format(cmd))
raise e

def videos_analyze_thread(v):
start_skip = 10
Expand Down Expand Up @@ -167,6 +188,7 @@ def clips_get(videos, beats, fps):
tries = len(videos)
while not found:
if tries <= 0:
print("Failed finding clip for beat: {} - {}".format(beat_start, beat_end))
return False

beat_pos_osffset = util.clamp(beat_pos + (random.random() * 0.2 - 0.1), 0, 1)
Expand Down

0 comments on commit 6db89be

Please sign in to comment.