How to crop last N seconds from a TS video

1.1k views Asked by At

Is there any way to crop the last N seconds from a video? The format is in this case 'MPEG-TS'.

With FFMPEG, I know there is an option for start time and duration, but neither of these are usable in this use case. Video can have any possible length, so the duration cannot be fixed value.

Also, the solution must run in Windows command line and can be automated.

1

There are 1 answers

1
digitalfootmark On BEST ANSWER

The desired functionality can be achieved with the following steps:

  1. Use ffmpeg to determine the length of the video. Use e.g. a cmd script:

    set input=video.ts
    
    ffmpeg -i "%input%" 2> output.tmp
    
    rem search "  Duration: HH:MM:SS.mm, start: NNNN.NNNN, bitrate: xxxx kb/s"
    for /F "tokens=1,2,3,4,5,6 delims=:., " %%i in (output.tmp) do (
        if "%%i"=="Duration" call :calcLength %%j %%k %%l %%m
    )
    goto :EOF
    
    :calcLength
    set /A s=%3
    set /A s=s+%2*60
    set /A s=s+%1*60*60
    set /A VIDEO_LENGTH_S = s
    set /A VIDEO_LENGTH_MS = s*1000 + %4
    echo Video duration %1:%2:%3.%4 = %VIDEO_LENGTH_MS%ms = %VIDEO_LENGTH_S%s
    
  2. Calculate the start and end point for clip operation

    rem ** 2:00 for the start, 4:00 from the end
    set /A starttime = 120
    set /A stoptime = VIDEO_LENGTH_S - 4*60 
    set /A duration = stoptime - starttime
    
  3. Clip the video. As a bonus, convert the TS file to a more optimal format, such as H.264

    set output=video.mp4
    
    vlc -vvv --start-time %starttime% --stop-time %stoptime% "%input%" 
      --sout=#transcode{vcodec=h264,vb=1200,acodec=mp3, 
      ab=128}:standard{access=file,dst=%output%} vlc://quit
    
    rem ** Handbrake has much better quality **
    handbrakeCLI -i %input% -o %output% -e x264 -B 128 -q 25 
      --start-at duration:%starttime% --stop-at duration:%duration%