import os import subprocess def freezeLastFrame(tmpdir, fVideoStream, freeze_s, fVideoStreamOut): try: # import subprocess, os E = os.environ.copy() E.update({ 'TMP': tmpdir, 'SRC': fVideoStream, 'FREEZE_S': str(freeze_s), 'DST': fVideoStreamOut }) cmd = ''' cd "$TMP" FFMPEG="ffmpeg -y -hide_banner -nostats" # get last frame NFRAMES=`ffprobe -show_streams "$SRC" 2> /dev/null | grep nb_frames | head -1 | cut -d \= -f 2` let "LAST_FRAME=$NFRAMES-1" $FFMPEG -i $SRC -vf select=\\'eq\(n,$LAST_FRAME\) -vframes 1 LAST_FRAME.jpg # make last-frame-frozen video FRAMERATE=`ffprobe -v 0 -of csv=p=0 -select_streams 0 -show_entries stream=r_frame_rate "$SRC"` $FFMPEG -loop 1 -framerate 1 -i LAST_FRAME.jpg -r "$FRAMERATE" -t "$FREEZE_S" LAST_FRAME.mp4 # -pix_fmt yuv420p # Produces list.txt like this: # file foo.mp4 # file 'bar with spaces.mp4' printf "file %q\\n" "$SRC" LAST_FRAME.mp4 > list.txt # concatenate # $FFMPEG -f concat -safe 0 -i list.txt -c copy "$DST" # problem: sometimes get green-screen for LAST_FRAME.mp4 duration $FFMPEG -i "$SRC" -i LAST_FRAME.mp4 -filter_complex "[0:v] [1:v] concat=n=2:v=1 [v]" -map "[v]" "$DST" # from https://stackoverflow.com/questions/7333232/how-to-concatenate-two-mp4-files-using-ffmpeg ''' # subprocess.Popen( cmd, env=E ) subprocess.check_output(cmd, shell=True, env=E, executable="/bin/bash") except subprocess.CalledProcessError as e: print('freezeLastFrameIfVideoShorter Error:' + str(e)) except: print('freezeLastFrameIfVideoShorter unknown Error!') return fVideoStreamOut freezeLastFrame(tmpdir='.', fVideoStream='./SampleVideo_1280x720_1mb.mp4', freeze_s=3, fVideoStreamOut='out.mp4')