Combine videos using Ffmpeg in Lambda and S3

Viewed 500

Goal

Im making a video converting tool with AWS Lambda where videos can be uploaded using a webpage to a S3 bucket. When all videos (1 or more) are uploaded to the bucket a done.json file will be uploaded last. A Lambda function is called on every upload and only will do something when the final done.json is uploaded.

Code walkthrough

Once the done.json is uploaded it will get all the videos in the current folder and convert them using Ffmpeg like this:

 i = 0
 ts_video_paths = []
 for video in video_paths:
     video_ts = os.path.splitext(video)[0] + '.ts'
     s3_source_signed_url = s3_client.generate_presigned_url('get_object', Params={'Bucket': S3_SOURCE_BUCKET, 'Key': video},  ExpiresIn=SIGNED_URL_TIMEOUT)
                
     ts_video_paths.append(f'/tmp/{rnd}/ts_video{i}.ts')
     ffmpeg_ts_cmd = f'/opt/bin/ffmpeg -i {s3_source_signed_url} -c:v copy -copyts -bsf:v h264_mp4toannexb -f mpegts -flags -global_header -af aresample=async=1:first_pts=0 /tmp/{rnd}/ts_video{i}.ts'
     command = shlex.split(ffmpeg_ts_cmd)
     subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                
     i += 1

After all the .ts files are made they will be made into one file (saw somewhere that you can just add .ts files)

 data = b''
 for video in ts_video_paths:
   f = open(video, 'rb')
   data += f.read()
            
   f = open(f'/tmp/{rnd}/all.ts', 'wb')
   f.write(data)
   f.close()          

The last step is to convert the all.ts to a .mp4 video. In this step I sometimes can't an error. It only happens with some videos and I cant find a solution.

ffmpeg_combine_cmd = f'/opt/bin/ffmpeg -i /tmp/{rnd}/all.ts -acodec copy -vcodec copy -f mp4 /tmp/{rnd}/video.mp4'
command_final = shlex.split(ffmpeg_combine_cmd)
p2 = subprocess.run(command_final , check=True)  # Sometimes gives an error videos 

Error that I get with some video converting:

Command '['/opt/bin/ffmpeg', '-i', '/tmp/CLZHC/all.ts', '-acodec', 'copy', '-vcodec', 'copy', '-f', 'mp4', '/tmp/CLZHC/video.mp4']' returned non-zero exit status 1.

My question to you

  • Is this the "right" way to tackle this problem?
  • Does someone know what the erro is im getting?
  • Or can anybody give me tips?
0 Answers
Related