How to crop last N seconds from a TS video
Asked Answered
S

1

1

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.

Statuary answered 10/12, 2013 at 18:20 Comment(5)
Are your videos limited to a specific container format? If so, look for the container-specific tools such as avisplit from transcode.Kirsch
Thanks for the hint. The question should have been "How to crop last N seconds from a TS video with any command line tool in Windows."Statuary
Not too many tools working with TS. Try tsMuxeR: videohelp.com/tools/tsMuxeRKirsch
Actually it's also OK if I at first convert them to MP4 h264. And then do the cropping. But tsMuxeR looks very good. I will try that!Statuary
..but the cropping does not support cropping from the end. Only the start and end time for the cropping. :(Statuary
S
1

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% 
    
Statuary answered 12/12, 2013 at 18:54 Comment(1)
This assumes ffmpeg prints duration for all videos, which still might not be the case.Kirsch

© 2022 - 2024 — McMap. All rights reserved.