User Tools

Site Tools


doc:appunti:linux:video:ffmpeg

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
doc:appunti:linux:video:ffmpeg [2019/11/24 12:25] – [Final rendering (re-encoding)] niccolodoc:appunti:linux:video:ffmpeg [2023/11/13 11:24] (current) – [Doppiaggio audio con Ardour] niccolo
Line 264: Line 264:
 </code> </code>
  
-====== Final rendering (re-encoding) ====== 
  
-The video stream recorded by the Xiaomi Yi camera is **1920x1080 pixels** at a variable bitrate of **12.0 Mb/s**. Because we watch it on a simple TV set capable only of 1366x768 pixels, we we re-encode it with the following settings:+====== Re-encoding with tonal correction ======
  
-^ Video codec     MPEG-4 AVC (x264) +We had some video clips recorded with an **SJCAM Sj8 Pro** camera with a **bad color balance and saturation** due some bad tables [[..:..:hardware:sjcam-8pro-custom-firmware|loaded into the firmware]]. It is possibile to re-encode all the video clips applying an equalization filter keeping all the encoding paramteres as similar as possibile to the original ones.
-^ Video filter    | swresize, 1366x768, Bilinear +
-^ Video encoding  | Average Bitrate (Two Pass), Average Bitrate 6000 kb/s (about 3 Gb per hour)  | +
-^ Audio codec     | Lame MP3  | +
-^ Audio bitrate   | CBR 192 (or higher)  |+
  
-We can use **Avidemux** to make the final rendering (re-encoding). For a **comman line only** solution you can consider ffmpeg to perfomr the re-encoding and **mkvmerge** (contained into the **mkvtoolnix** Debian package) to merge all into a Matroska container.+The video clips were **extracted from the original MP4 container** as **[[wp>MPEG transport stream|MPEG-TS]]** snippets containing only video (no audio). To re-encode each clip we used the following **ffmpeg** recipe: 
 + 
 +<code bash> 
 +#!/bin/sh 
 +
 +# Re-encode video clips in MPEG transport stream (MPEG-TS) format applying 
 +# some saturation and gamma correction. 
 +
 +# saturation:           In range 0.0 to 3.0. The default value is "1"
 +# gamma_{r|g|b}         In range 0.1 to 10.0. The default value is "1"
 + 
 +INPUT="$1" 
 +OUTPUT="$INPUT.eq.ts" 
 +EQ_FILTER="eq=saturation=0.88:gamma_r=0.917:gamma_g=1.007:gamma_b=1.297" 
 + 
 +# Produces MPEG segments like the ones produced by the SJCAM SJ8Pro: 
 +ffmpeg -i "$INPUT"
 +    -vf "$EQ_FILTER"
 +    -codec:v libx264 \ 
 +    -preset veryslow -profile:v main -level:v 4.2 -pix_fmt yuvj420p \ 
 +    -x264-params 'vbv-maxrate=38000:vbv_bufsize=20000:nal-hrd=vbr:force-cfr=1:keyint=8:bframes=0:scenecut=-1:ref=1'
 +    -keyint_min 8 -brand avc1 -f 3gp \ 
 +    -bsf:v h264_mp4toannexb -f mpegts \ 
 +    "$OUTPUT" 
 +</code> 
 + 
 +The gamma correction for the three RGB channels was determined with the GIMP, using the //Colors// => //Levels// => //Pick the gray point for all channels// tool. The use of MPEG-TS clips allowed the montage of the final video by just concatenating them. 
 + 
 +===== AVC (x264is better than ASP (xvid4) ===== 
 + 
 +See this page: **[[https://www.avidemux.org/admWiki/doku.php?id=general:common_myths|Common myths]]** to understand the differences between formats (standards) and codecs (pieces of software). Read also this simple page: **[[https://www.cyberlink.com/support/product-faq-content.do?id=1901|Difference between MPEG-4 AVC and MPEG-4 ASP]]**. See also the Wikipedia article about **[[wp>Advanced Video Coding]]**. 
 + 
 +  * **MPEG-4 Part 2 ASP** (Advanced Simple Profile) 
 +     * Support only 16x16 block size. 
 +     Implemented by the Xvid library/codec. 
 +  **MPEG-4 Part 10 AVC** (Advanced Video Coding) 
 +    * Support variable motion compensation block sizes. 
 +    * Implemented by the x264 library. 
 + 
 +If you want to tweak with x264 codec options, here are some hints on the parameters meaning: 
 + 
 +  * **Preset**: Use the **slow** preset (or less) to achieve best compression ratio, at the expense of more time to encode. 
 +  * **Tuning**: Use the **film** option for real life scenes. 
 +  * **Profile**: The **High** profile is OK for high-definition television (e.g. 1280×720, or Blu-ray disc), //High 10// add support for 10 bits per sample, //High 444// up to 14 bits per sample (both for [[wp>High dynamic range|HDR]] videos). Do not use //Main//, which is for standard-definition TV, e.g. 720×576. 
 +  * **IDC Level**: Leave this parameter to **Auto**, setting it to higer values does not increase the video quality, but imposes higher constraints to the decoder. I.e. to decode 1280×1024@42 it is sufficient the 3.1 IDC level (see [[wp>Advanced Video Coding]]).
  
 ====== More on ffmpeg Command Line ====== ====== More on ffmpeg Command Line ======
Line 366: Line 405:
 </code> </code>
  
-the CSV format can be controlled by several options, e.g. if you want to know the key for each filed use:+the CSV format can be controlled by several options, e.g. if you want to print each field as a **key=val** pair, use:
  
 <code> <code>
Line 442: Line 481:
 </code> </code>
  
-====== Doppiaggio audio con Ardour ======+====== Deinterlace ======
  
-Per doppiare un video sostitutendo o mixando l'audio originale con musiche, ecc. si può utilizzare il programma Ardour. In questi appunti un possibile metodo di lavoro da utilizzare.+We can use the video filter named **yadif** (//yet another deinterlacing filter//). In this example the result was encoded in MPEG-4 AVC using the libx264 library, forcing one keyframe every 8 frames:
  
-Per alcuni suggerimenti vedere il paragrafo sull'uso di **[[..:audio_video#mouse_e_tastiera|mouse testiera con Ardour]]**. +<code> 
-===== Estrazione traccia audio originale =====+ffmpeg -i input-video.mkv -codec:a copy -vf yadif -codec:v libx264 -preset slow \ 
 +        -x264-params 'force-cfr=1:keyint=8:bframes=0:ref=1' \ 
 +        output-video.mkv 
 +</code>
  
-La traccia audio originale verrà usata come riferimento per allineare i brani musicali da abbinare al video.+====== Problem in MKV Remux ======
  
-**ATTENZIONE** alla conversione del file in formato WAVcontrollare con ''mediainfo'' che la durata sia esattamente quella del video originale, al secondo! Può capitare che l'estrazione con ''ffmpeg'' e la successiva conversione in wav (ad esempio con Audacityproduca un file più corto di qualche secondo (1 secondo ogni 10 minuti di durata).+It seems there is a bug in ffmpeg **[[https://trac.ffmpeg.org/ticket/6037|#6037 mkv muxing not broken]]**: muxing two working files into a mkv produces a broken file: seeking around can break (muteaudio. I experienced this bug (with ffmpeg 4.1.6trying to mux one mkv file containing one audio and one subtitle streams to another mkv file conaining video and audioThe resulting file did not play good in mplayer: seeking into the file caused audio or vido to stop playing. 
 + 
 +This was the first try command line:
  
 <code> <code>
-ffmpeg -i video.mp4 -vn -c:a copy audio.m4a +# The resulting video is broken. 
-ffmpeg -i 2018-05_portogallo.m4a -af aresample=async=2018-05_portogallo.fix.wav+ffmpeg -i input_file1.mkv -i input_file2.mkv \ 
 +    -map '0:v:0' -map '0:a:0' \ 
 +    -map '1:a:0' -map '1:s:0' \ 
 +    -codec:v copy -codec:a copy -codec:s copy \ 
 +    output_file.mkv
 </code> </code>
  
-===== Conversione dei brani audio ===== +The workaround was to extract each individual stream, and mux then together:
- +
-Per importare in Ardour i brani musicali vanno convertiti in WAV quelli non direttamente supportati (es. i file MP3 e le tracce M4A solitamente estratte dai video MP4). Per questo si può utilizzare **sox** (dall'omonimo pacchetto Debian):+
  
 <code> <code>
-sox file.mp3 file.wav+ffmpeg -i input_file1.mkv -map 0:v:0 -codec:v copy input-v_env.mkv 
 +ffmpeg -i input_file1.mkv -map 0:a:0 -codec:a copy input-a_ita.mkv 
 +ffmpeg -i input_file2.mkv -map 0:a:0 -codec:a copy input-a_eng.mkv 
 +ffmpeg -i input_file2.mkv -map 0:s:0 -codec:s copy input-s_eng.mkv 
 +ffmpeg \ 
 +    -i input-v_env.mkv \ 
 +    -i input-a_ita.mkv \ 
 +    -i input-a_eng.mkv \ 
 +    -i input-s_eng.mkv \ 
 +    -codec:v copy -codec:a copy -codec:s copy \ 
 +    -map '0' -map '1' -map '2' -map '3'
 +    output_file.mkv
 </code> </code>
  
-===== Manipolazione di tracce e regioni =====+====== ffmpeg: leggere la sequenza di VOB da un DVD ======
  
-Con Ardour si inizia un **nuovo progetto**, impostare **48 kHz, 32 bit float, stereo**, che sono i parametri che vanno per la maggiore nei video MP4 in alta risoluzione. Quando il progetto è avviato (pulsante **Start**) il sistema audio ALSA sarà impegnato in modo esclusivoaltri programmi non potranno usare l'audio.+Nella directory **VIDEO_TS** di un DVD la traccia principale è normalmente suddivisa in file numerati sequenzialmentead esempio: ''VTS_01_0.VOB'', ''VTS_01_1.VOB'', ...
  
-Con Ardour si **importano** le varie **tracce musicali** (menu //Session// => //Import//)Conviene scegliere il **mapping one track per file**, altrimenti il canale destro e sinistro vengono importati come tracce separate. Se necessario il programma provvede automaticamente alla conversione del sample rate.+In teoria è sufficiente concatenare i file in un solo file destinazione e quindi trattarlo come un normale file audio/videoTuttavia è possibile indicare i singoli file come input senza la necessità di occupare ulteriore spazio disco con questa sintassi:
  
-Attenzione al **fader** di ogni tracciase per caso viene spostato con il mouse, fare **Ctrl-click** per resettarlo al **valore predefinito di 0 dB**.+<code bash> 
 +SOURCE="concat:VTS_01_1.VOB|VTS_01_2.VOB|VTS_01_3.VOB|VTS_01_4.VOB|VTS_01_5.VOB" 
 +ffmpeg -i "$SOURCE" ... 
 +</code>
  
-{{..:ardour:track_fader.png?direct&220|Track Fader}}+====== ffmpegimpostare un ritardo sui sottotitoli durante il muxing ======
  
-Ogni **traccia** può essere manipolata separatamente (es. spostata nella timeline, ecc.), inizialmente la traccia è costituita da un'unica **regione**, ma è possibile effettuare ad esempio un taglio per ottenere due regioni manipolabili separatamente. L'oggetto che viene manipolato infatti è la singola regione, non l'intera traccia.+Se un flusso di sottotitoli (ad esempio nel formato Picture based DVDnon indica correttamente l'offset iniziale di riproduzione è possibile dire ad ffmpeg di impostarlo opportunamente in fase di muxing. In questo esempio il primo sottotitolo appare a 44.5 secondi:
  
-=== Spostare ===+<code bash> 
 +ffmpeg -i video-stream.mkv -i audio-stream.mkv -itsoffset 44.5 -i subtitles-stream.mkv ... 
 +</code>
  
-=== Tagliare un pezzo ===+In generale dovrebbe essere possibile scoprire l'offset quando ffmpeg legge l'intero stream, al momento in cui trova il prmio frame dei subtitles mostra qualcosa del genere sulla console:
  
-  * Strumento forbici +<code> 
-  * Zoom opportuno +[mpeg @ 0x55f98bb2c6c0] New subtitle stream 0:7 at pos:14755854 and DTS:44.5s 
-  * Click sul puntotaglia immediatamente la traccia +</code>
-  * Strumento selezione, click sul pezzo da togliere, menu //Region// =//Remove//+
  
-=== Bloccare una singola regione ===+====== Parameters for final rendering ======
  
-  Dopo averla selezionata, menu //Region// => //Position// => //Lock//+See the page **[[ffmpeg_final_rendering]]**.
  
-=== Fade in/out === +====== Doppiaggio audio con Ardour ======
- +
-  * Con lo strumento "Grab mode" cliccare una regione +
-  * Trascinare il quadretto che appare all'estremità +
- +
-===  Esportare tutto il lavoro in WAV ===+
  
-  * //Session// => //Export// => //Export to Audio File(s)// +Vedere la pagina dedicata: **[[ardour_dubbing]]**.
-    * **File formats**: impostare **WAV 16 bit, 48 KHz**. Eventualmente si può abilitare il **Normalize**, che viene applicato alla fine del rendering sull'intera sessione. +
-    * **Time Span**: Controllare che sia pari alla lunghezza originale. Se c'è qualcosa di troppo aggiustare il tag **end** nella barra **Location markers**. +
-    * **Channels**: selezionare solo il **Master**, gli altri canali possono restare deselezionati. ATTENZIONE: Se nel progetto c'è l'audio originale in presa diretta che non va incluso, si deve agire di conseguenza: **selezionare tutte le tracce ad eccezione dell'audio in presa diretta**. In questo caso selezionare o meno il Master è ininfluente.+
doc/appunti/linux/video/ffmpeg.1574594756.txt.gz · Last modified: 2019/11/24 12:25 by niccolo