AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / ubuntu / Perguntas / 1403736
Accepted
user1579004
user1579004
Asked: 2022-04-23 04:04:07 +0800 CST2022-04-23 04:04:07 +0800 CST 2022-04-23 04:04:07 +0800 CST

Processe recursivamente arquivos de vídeo para liberar espaço

  • 772

Maximizei o espaço de armazenamento que tenho e gostaria de fazer algum espaço.

Eu pensei em converter todos os arquivos para mkv e reduzir os arquivos de alta resolução para uma resolução mais baixa.

Então, para converter mp4 para mkv, existe

ffmpeg -i input.mp4 -vcodec copy -acodec copy output.mkv

E para reduzir há

ffmpeg -i input.mp4 -vf scale=$w:$h <encoding-parameters> output.mp4

mas eu preciso converter todos os arquivos e não um único mp4, preciso remover o arquivo de entrada depois de processá-lo e tenho que fazer isso apenas para arquivos acima de uma determinada resolução. Também gostaria de manter a proporção e não sei se isso está fazendo isso.

Existe uma ferramenta chamada video-dieta que faz parte disso.

Isto é o que eu gostaria de fazer

Recursively find every file under the current directory
If the file resolution has a height equal or greater to a given height.
  Convert the file to mkv if it's in another format avi, mp4, flv, etc
  Downscale to a lower resolution height, keeping the aspect ratio.

Talvez eu também deva diminuir a taxa de quadros para 24 fps?

Se houver uma maneira melhor, eu gostaria de ouvi-la.

video
  • 1 1 respostas
  • 31 Views

1 respostas

  • Voted
  1. Best Answer
    frabjous
    2022-04-23T10:50:56+08:002022-04-23T10:50:56+08:00

    Aqui está um script para você começar. Você provavelmente desejará modificar isso para atender às suas necessidades, adicionar opções ao ffmpeg se desejar alterar a taxa de quadros etc.

    Observe que há uma condicional lá verificando se o arquivo já é um .mkv, mas na verdade não estou fazendo algo diferente com eles, então a condicional é meio inútil. Está lá porque sua pergunta fez parecer que você queria fazer algo diferente com eles, embora eu não tenha certeza do porquê. O FFMPEG pode dimensionar e converter ao mesmo tempo.

    Mas se você quiser fazer algo diferente, altere a linha ffmpeg para quando a condicional for verdadeira para algo diferente.

    #!/bin/bash
    
    # set the resolution above which you want to downscale
    maxwidth=1920
    maxheight=1080
    
    # set the resolution to downscale to; the width will be
    # calculated to preserve aspect ratio
    targetwidth=1280
    
    # a counter for errors
    errors=0
    
    # recursively find video files; add their names to
    # an array to process
    mapfile -t filenames < <(find $(pwd) -type f -iregex '.*avi$\|.*mp4$\|.*m4v$\|.*flv\|.*mkv\|.*ogv\|.*webm$\|.*mov')
    
    # loop through the array
    for filename in "${filenames[@]}" ; do
        # get the resolution with ffprobe
        res="$(ffprobe -hide_banner -v error -select_streams v:0 -show_entries stream=width,height -print_format csv "$filename")"
        # strip "stream" off "res"
        res="${res#stream,}"
        # parse into width and height
        width="${res%,*}"
        height="${res#*,}"
        # compare to maxwidth/height to see if it should be
        # processed
        if [[ "$width" -ge "$maxwidth" ]] || [[ "$height" -ge "$maxheight" ]] ; then
            # determine the output name
            outputname="${filename%.*}-downscaled.mkv"
            # check if output already exists; if so, skip it
            if [[ -e "$outputname" ]] ; then
                continue
            fi
            # calculate targetheight, divide by 2 multiply by 2
            # to ensure it's even
            targetheight="$(( ( ( (targetwidth * height) / width) / 2) * 2 ))"
            # get file extension
            ext="${filename##*.}"
            # do something different with mkvs?
            # not sure why you would though
            if [[ "$ext" =~ '[Mm]{Kk][Vv]' ]] ; then
                ffmpeg -i "$filename" -vf scale="$targetwidth:$targetheight" "$outputname"
                exitcode="$?"
            else
                ffmpeg -i "$filename" -vf scale="$targetwidth:$targetheight" "$outputname"
                exitcode="$?"
            fi
            # if conversion was a success, delete original file
            if [[ "$exitcode" == 0 ]] && [[ -e "$outputname" ]] ; then
                rm "$filename"
            else
                echo
                echo "Error processing $filename" >&2
                echo "Not deleted!"
                let errors++
                echo
            fi
        fi
    done
    
    # report number of errors if there were any
    if [[ "$errors" == 0 ]] ; then
        exit 0
    fi
    echo "There were $errors errors!" >&2
    exit 1
    

    Isso pode ser meio exagerado, e pode haver maneiras de simplificá-lo, mas é o que eu faria.

    • 0

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Existe um comando para listar todos os usuários? Também para adicionar, excluir, modificar usuários, no terminal?

    • 9 respostas
  • Marko Smith

    Como excluir um diretório não vazio no Terminal?

    • 4 respostas
  • Marko Smith

    Como descompactar um arquivo zip do Terminal?

    • 9 respostas
  • Marko Smith

    Como instalo um arquivo .deb por meio da linha de comando?

    • 11 respostas
  • Marko Smith

    Como instalo um arquivo .tar.gz (ou .tar.bz2)?

    • 14 respostas
  • Marko Smith

    Como listar todos os pacotes instalados

    • 24 respostas
  • Martin Hope
    Flimm Como posso usar o docker sem sudo? 2014-06-07 00:17:43 +0800 CST
  • Martin Hope
    led-Zepp Como faço para salvar a saída do terminal em um arquivo? 2014-02-15 11:49:07 +0800 CST
  • Martin Hope
    ubuntu-nerd Como descompactar um arquivo zip do Terminal? 2011-12-11 20:37:54 +0800 CST
  • Martin Hope
    TheXed Como instalo um arquivo .deb por meio da linha de comando? 2011-05-07 09:40:28 +0800 CST
  • Martin Hope
    Ivan Como listar todos os pacotes instalados 2010-12-17 18:08:49 +0800 CST
  • Martin Hope
    David Barry Como determino o tamanho total de um diretório (pasta) na linha de comando? 2010-08-06 10:20:23 +0800 CST
  • Martin Hope
    jfoucher "Os seguintes pacotes foram retidos:" Por que e como resolvo isso? 2010-08-01 13:59:22 +0800 CST
  • Martin Hope
    David Ashford Como os PPAs podem ser removidos? 2010-07-30 01:09:42 +0800 CST

Hot tag

10.10 10.04 gnome networking server command-line package-management software-recommendation sound xorg

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve