Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature para renderizar videos com o Node sem precisar do After Effects #152

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

felvieira
Copy link

Como nem todos temos acesso ao After Effects procurei uma alternativa viável. Não tem todo poder de personalização do AE mas acredito que vai ser bem usável. Fiz rapidamente , melhorias e sugestões são sempre bem vindas.

Copy link

@leleuvilela leleuvilela left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ai sim, ficou ótimo!
Só ficou faltando colocar pra retornar uma Promise na sua função renderVideoWithNode com resolve() assim que terminar a renderização, pra conseguir fazer a função ficar assíncrona, se não, vai começar a subir o vídeo antes mesmo do vídeo existir kk

assim ó:

async function renderVideoWithNode(content) {
    return new Promise((resolve, reject) => {
      console.log("> Renderizando vídeo com node.");

      let images = [];

      for (
        let sentenceIndex = 0;
        sentenceIndex < content.sentences.length;
        sentenceIndex++
      ) {
        images.push({
          path: `./content/${sentenceIndex}-converted.png`,
          caption: content.sentences[sentenceIndex].text
        });
      }

      const videoOptions = {
        fps: 25,
        loop: 5, // seconds
        transition: true,
        transitionDuration: 1, // seconds
        videoBitrate: 1024,
        videoCodec: "libx264",
        size: "640x?",
        audioBitrate: "128k",
        audioChannels: 2,
        format: "mp4",
        pixelFormat: "yuv420p",
        useSubRipSubtitles: false, // Use ASS/SSA subtitles instead
        subtitleStyle: {
          Fontname: "Verdana",
          Fontsize: "26",
          PrimaryColour: "11861244",
          SecondaryColour: "11861244",
          TertiaryColour: "11861244",
          BackColour: "-2147483640",
          Bold: "2",
          Italic: "0",
          BorderStyle: "2",
          Outline: "2",
          Shadow: "3",
          Alignment: "1", // left, middle, right
          MarginL: "40",
          MarginR: "60",
          MarginV: "40"
        }
      };

      videoshow(images, videoOptions)
        .audio("./templates/1/newsroom.mp3")
        .save("content/output.mp4")
        .on("start", function(command) {
          console.log("> Processo ffmpeg iniciado:", command);
        })
        .on("error", function(err, stdout, stderr) {
          console.error("Error:", err);
          console.error("> ffmpeg stderr:", stderr);
          reject(err);
        })
        .on("end", function(output) {
          console.error("> Video criado:", output);
          resolve();
        });
    });
  }

@felvieira
Copy link
Author

Boa!

@felvieira
Copy link
Author

So mais uma dica no windows deu um erro
"Error: Error: ffmpeg exited with code 1: Error opening filter"
Pra fazer funfar os subtitulos é simples vc precisa editar o arquivo render.js
ele fica em :- nodemodules/videpshow/lib
Na linha 245
filepath = randomName() + extension
fs.writeFileSync(filepath, subtitles)
/------------- Adicionar esse codigo Começa Aqui ---------------/
if(os.platform()==='win32'){

filepath = filepath.replace(/\/g, "\\");
filepath = filepath.replace(/:/g, "\:");
}
/-------acaba aqui---------/

return filepath

@ghost
Copy link

ghost commented May 14, 2019

Oi @felvieira ,,, boa ideia. Porem o node tem reclamado ( no OSX ) em nao encontrar o modulo videoshow ... alguma ideia ?

Ahh, so vi depois que precisa instalar o modulo:
npm install videoshow
ou para uma instalacao global
npm install -g videoshow.

@hebertlima hebertlima mentioned this pull request May 15, 2019
@felvieira
Copy link
Author

Oi @felvieira ,,, boa ideia. Porem o node tem reclamado ( no OSX ) em nao encontrar o modulo videoshow ... alguma ideia ?

Ahh, so vi depois que precisa instalar o modulo:
npm install videoshow
ou para uma instalacao global
npm install -g videoshow.

Sim acredito que ele ja esta como dependencia no package.json desse PR. Ai com npm i ele instala td

@C-Miriane
Copy link

Oi @felvieira fiz as mudanças mas ao tentar rodar deu esse erro:

$ node index.js
C:\Users\HP\Desktop\GIT\video-maker - Cópia (2)\robots\video.js:118
gravity: "center"'
^

SyntaxError: Invalid or unexpected token
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)

Obs. Primeiro coloquei os dados exatamente como vc escreveu, mas como deu erro, decidi "trocar" o número da versão para o qual já tinha na máquina...porém como não conheço o funcionamento e instalação do ffmpeg (apenas havia baixado - 4.1.1) não sei se precisava colocar a versão que tenho ou se podia deixar aquela mesmo....de qualquer forma não deu certo.

$ npm install
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @ffmpeg-installer/linux-ia32@4.1.0 (node_modules@ffmpeg-installer\linux-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @ffmpeg-installer/linux-ia32@4.1.0: wanted {"os":"linux","arch":"ia32"} (current: {"os":"win32","arch":"ia32"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @ffmpeg-installer/linux-x64@4.1.0 (node_modules@ffmpeg-installer\linux-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @ffmpeg-installer/linux-x64@4.1.0: wanted {"os":"linux","arch":"x64"} (current: {"os":"win32","arch":"ia32"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @ffprobe-installer/darwin-x64@4.0.3 (node_modules@ffprobe-installer\darwin-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @ffprobe-installer/darwin-x64@4.0.3: wanted {"os":"darwin","arch":"x64"} (current: {"os":"win32","arch":"ia32"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @ffmpeg-installer/win32-x64@4.1.0 (node_modules@ffmpeg-installer\win32-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @ffmpeg-installer/win32-x64@4.1.0: wanted {"os":"win32","arch":"x64"} (current: {"os":"win32","arch":"ia32"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @ffprobe-installer/linux-ia32@4.0.3 (node_modules@ffprobe-installer\linux-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @ffprobe-installer/linux-ia32@4.0.3: wanted {"os":"linux","arch":"ia32"} (current: {"os":"win32","arch":"ia32"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @ffprobe-installer/linux-x64@4.0.3 (node_modules@ffprobe-installer\linux-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @ffprobe-installer/linux-x64@4.0.3: wanted {"os":"linux","arch":"x64"} (current: {"os":"win32","arch":"ia32"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @ffprobe-installer/win32-x64@4.0.2 (node_modules@ffprobe-installer\win32-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @ffprobe-installer/win32-x64@4.0.2: wanted {"os":"win32","arch":"x64"} (current: {"os":"win32","arch":"ia32"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @ffmpeg-installer/darwin-x64@4.1.0 (node_modules@ffmpeg-installer\darwin-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @ffmpeg-installer/darwin-x64@4.1.0: wanted {"os":"darwin","arch":"x64"} (current: {"os":"win32","arch":"ia32"})

audited 913 packages in 64.445s
found 0 vulnerabilities

Esse teste estou fazendo em um note com 32 bit e como a versão que eu tenho do AF4 não permite usar o template do Felipe, estou buscando outra forma...mas será que ffmpeg ajuda nesse caso?

Sabe dizer que erro é esse?

@felvieira
Copy link
Author

gravity: "center"'

Tem mias uma aspas no center. mude para:

gravity: "center"

@hebertlima hebertlima mentioned this pull request May 17, 2019
@C-Miriane
Copy link

@felvieira Obrigada, arrumei esse erro e outros mais que surgiram e consegui fazer rodar um pouco, só que parou nesse erro abaixo...tentei resolver mas até agora nada...sabe dizer oq tenho q alterar?

Image successfully downloaded: https://lh3.googleusercont
ent.com/i7nQOBF5UnDqmsOjHxR0sYx3TBqUpKqq2e1UKgm7PCXzInxEBOk7i0NlZkkJMkkCX5k

[image-robot] [5][0] Image successfully downloaded: https://i.ytimg.com/vi/tiQ
s5IEfFdQ/maxresdefault.jpg
[video-robot] Starting...
(node:6076) UnhandledPromiseRejectionWarning: Error: Could not execute GraphicsM
agick/ImageMagick: convert "./content/0-original.png[0]" "(" "-clone" "0" "-back
ground" "white" "-blur" "0x9" "-resize" "1920x1080^" ")" "(" "-clone" "0" "-back
ground" "white" "-resize" "1920x1080" ")" "-delete" "0" "-gravity" "center" "-co
mpose" "over" "-composite" "-extent" "1920x1080" "./content/0-converted.png" thi
s most likely means the gm/convert binaries can't be found
at ChildProcess. (C:\Users\HP\Desktop\GIT\video-maker - Cópia (2)
\node_modules\gm\lib\command.js:232:12)
at ChildProcess.emit (events.js:189:13)
at ChildProcess.cp.emit (C:\Users\HP\Desktop\GIT\video-maker - Cópia (2)\nod
e_modules\cross-spawn\lib\enoent.js:36:37)
at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)
(node:6076) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). (rejection
id: 1)
(node:6076) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

@felvieira
Copy link
Author

@felvieira Obrigada, arrumei esse erro e outros mais que surgiram e consegui fazer rodar um pouco, só que parou nesse erro abaixo...tentei resolver mas até agora nada...sabe dizer oq tenho q alterar?

Image successfully downloaded: https://lh3.googleusercont
ent.com/i7nQOBF5UnDqmsOjHxR0sYx3TBqUpKqq2e1UKgm7PCXzInxEBOk7i0NlZkkJMkkCX5k

[image-robot] [5][0] Image successfully downloaded: https://i.ytimg.com/vi/tiQ
s5IEfFdQ/maxresdefault.jpg
[video-robot] Starting...
(node:6076) UnhandledPromiseRejectionWarning: Error: Could not execute GraphicsM
agick/ImageMagick: convert "./content/0-original.png[0]" "(" "-clone" "0" "-back
ground" "white" "-blur" "0x9" "-resize" "1920x1080^" ")" "(" "-clone" "0" "-back
ground" "white" "-resize" "1920x1080" ")" "-delete" "0" "-gravity" "center" "-co
mpose" "over" "-composite" "-extent" "1920x1080" "./content/0-converted.png" thi
s most likely means the gm/convert binaries can't be found
at ChildProcess. (C:\Users\HP\Desktop\GIT\video-maker - Cópia (2)
\node_modules\gm\lib\command.js:232:12)
at ChildProcess.emit (events.js:189:13)
at ChildProcess.cp.emit (C:\Users\HP\Desktop\GIT\video-maker - Cópia (2)\nod
e_modules\cross-spawn\lib\enoent.js:36:37)
at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)
(node:6076) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). (rejection
id: 1)
(node:6076) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

Da uma olhada nisso
https://www.google.com/search?q=thi+s+most+likely+means+the+gm%2Fconvert+binaries+can%27t+be+found+at+ChildProcess&oq=thi+s+most+likely+means+the+gm%2Fconvert+binaries+can%27t+be+found+at+ChildProcess&aqs=chrome..69i57&sourceid=chrome&ie=UTF-8

@hebertlima
Copy link
Contributor

hebertlima commented May 18, 2019

@felvieira Obrigada, arrumei esse erro e outros mais que surgiram e consegui fazer rodar um pouco, só que parou nesse erro abaixo...tentei resolver mas até agora nada...sabe dizer oq tenho q alterar?

Image successfully downloaded: https://lh3.googleusercont
ent.com/i7nQOBF5UnDqmsOjHxR0sYx3TBqUpKqq2e1UKgm7PCXzInxEBOk7i0NlZkkJMkkCX5k

[image-robot] [5][0] Image successfully downloaded: https://i.ytimg.com/vi/tiQ
s5IEfFdQ/maxresdefault.jpg
[video-robot] Starting...
(node:6076) UnhandledPromiseRejectionWarning: Error: Could not execute GraphicsM
agick/ImageMagick: convert "./content/0-original.png[0]" "(" "-clone" "0" "-back
ground" "white" "-blur" "0x9" "-resize" "1920x1080^" ")" "(" "-clone" "0" "-back
ground" "white" "-resize" "1920x1080" ")" "-delete" "0" "-gravity" "center" "-co
mpose" "over" "-composite" "-extent" "1920x1080" "./content/0-converted.png" thi
s most likely means the gm/convert binaries can't be found
at ChildProcess. (C:\Users\HP\Desktop\GIT\video-maker - Cópia (2)
\node_modules\gm\lib\command.js:232:12)
at ChildProcess.emit (events.js:189:13)
at ChildProcess.cp.emit (C:\Users\HP\Desktop\GIT\video-maker - Cópia (2)\nod
e_modules\cross-spawn\lib\enoent.js:36:37)
at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)
(node:6076) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). (rejection
id: 1)
(node:6076) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

em outras palavras, você precisa adicionar o GraphicsMagick no path do windows

this most likely means the gm/convert binaries can't be found

algo mais ou menos assim:

set PATH=%PATH%;caminho\para\o\GraphicsMagick\bin

Ps. se tiver a pasta bin é essa pasta que você deve indicar se não a pasta principal

tem duas formas de fazer isso no windows e elas são explicadas aqui

@C-Miriane
Copy link

Oi @hebertlima obrigada pela atenção em responder. No dia até tentei, mas só muda o código do erro e não vai. Somente agora pude tentar novamente...só que ao editar o "Path" e apagar um "caminho" que já consta lá - Do Node, o comando node index.js para de funcionar...aí tenho que adicionar novamente e antes de adicionar o "caminho" do Graphics adiciono ";" sem aspas e acho que o problema esta ocorrendo nessa mudança que não estou sabendo fazer. Obs. na pasta do Graphics não tem Bin, aí tentei C:\Program Files\GraphicsMagick-1.3.31-Q8 e \ algumas pastas mas também não vai. Estou bem perdida nessa, se puder me dar uma dica ou informar onde estou errando....Abaixo segue o ultimo erro:

[video-robot] Starting...
(node:2444) UnhandledPromiseRejectionWarning: Error: Could not execute GraphicsM
agick/ImageMagick: convert "./content/0-original.png[0]" "(" "-clone" "0" "-back
ground" "white" "-blur" "0x9" "-resize" "1920x1080^" ")" "(" "-clone" "0" "-back
ground" "white" "-resize" "1920x1080" ")" "-delete" "0" "-gravity" "center" "-co
mpose" "over" "-composite" "-extent" "1920x1080" "./content/0-converted.png" thi
s most likely means the gm/convert binaries can't be found
at ChildProcess. (C:\Users\HP\Desktop\GIT\video-maker - Cópia (2)
\node_modules\gm\lib\command.js:232:12)
at ChildProcess.emit (events.js:189:13)
at ChildProcess.cp.emit (C:\Users\HP\Desktop\GIT\video-maker - Cópia (2)\nod
e_modules\cross-spawn\lib\enoent.js:36:37)
at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)
(node:2444) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). (rejection
id: 1)
(node:2444) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

@hebertlima
Copy link
Contributor

@C-Miriane faz assim então, remove o image magick do projeto:

npm uninstall gm

talvez seja pq o gm não foi instalado de forma global, reinstala novamente assim:

npm install -g gm

depois vai nas variaveis de ambiente e aponta para

C:\Program Files\GraphicsMagick-1.3.31-Q8

@vladimirpezzole
Copy link

Valeu!!! @felvieira e @leleuvilela pela Feature para renderizar videos com o Node sem precisar do After Effects, no Linux se tornaria inviável continuar o projeto de modo contínuo usando After Effects mesmo com Wine, estava tentando utilizar o Kdenlive que fornece um script do template para renderização, mas dessa forma ficou mais prático e funcionou de primeira, muito grato!

Quanto as dependências, instalei todas com sudo mesmo com alguns avisos funcionaram.

"@ffmpeg-installer/ffmpeg" sudo npm install --save @ffmpeg-installer/ffmpeg
"@ffprobe-installer/ffprobe" sudo npm install --save @ffprobe-installer/ffprobe
"videoshow" sudo npm install videoshow
"fluent-ffmpeg" sudo npm install fluent-ffmpeg

@felvieira
Copy link
Author

Valeu!!! @felvieira e @leleuvilela pela Feature para renderizar videos com o Node sem precisar do After Effects, no Linux se tornaria inviável continuar o projeto de modo contínuo usando After Effects mesmo com Wine, estava tentando utilizar o Kdenlive que fornece um script do template para renderização, mas dessa forma ficou mais prático e funcionou de primeira, muito grato!

Quanto as dependências, instalei todas com sudo mesmo com alguns avisos funcionaram.

"@ffmpeg-installer/ffmpeg" sudo npm install --save @ffmpeg-installer/ffmpeg
"@ffprobe-installer/ffprobe" sudo npm install --save @ffprobe-installer/ffprobe
"videoshow" sudo npm install videoshow
"fluent-ffmpeg" sudo npm install fluent-ffmpeg

Boa, Assim nao ficamos presos a um Software pago.

@wfrsilva
Copy link
Contributor

Error: Error: ffmpeg exited with code 1: Error reinitializing filters!
Failed to inject frame into filter network: Invalid argument
Error while processing the decoded data for stream #0:0
Conversion failed!

at ChildProcess.<anonymous> (C:\Users\Avell\Google Drive\robovideoyoutube\video-maker\node_modules\videoshow\node_modules\fluent-ffmpeg\lib\processor.js:182:22)
at ChildProcess.emit (events.js:198:13)
at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)

ffmpeg stderr: undefined

@alportblu
Copy link

image

alguma ideia do que esteja acontecendo?

@ghost
Copy link

ghost commented Mar 21, 2020

Olá felvieira! Tudo bem?
Utilizei o código que você disponibilizou e funcionou normalmente, mas gostaria de saber se: é possível deixar igual o do filipe?, utilizar do mesmo template que ele criou
Obrigado pela compreensão!

@felvieira
Copy link
Author

Entao mas o tempalte pro video que ele criou é do After, e essa solucao é pra nao ser do After pq o After é pago.

@ghost
Copy link

ghost commented Mar 21, 2020

mas é possivel "converter" isso? as ferramentas que você usou tem capacidade para isso??

@felvieira
Copy link
Author

COnverter template do after pra software livre? Dificil.
Mas pode se criar templates novos em softwares opensource, acho que isso é possivel

@1Marcuth
Copy link

1Marcuth commented Jun 5, 2023

E aí pessoal, não tem um melhor que o vídeoshow? Conheço um em python (moviepy) mas seria foda ficar com duas linguagens para esse projeto...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
Status: To do
Development

Successfully merging this pull request may close these issues.

None yet