
Recherche avancée
Autres articles (75)
-
Organiser par catégorie
17 mai 2013, parDans MédiaSPIP, une rubrique a 2 noms : catégorie et rubrique.
Les différents documents stockés dans MédiaSPIP peuvent être rangés dans différentes catégories. On peut créer une catégorie en cliquant sur "publier une catégorie" dans le menu publier en haut à droite ( après authentification ). Une catégorie peut être rangée dans une autre catégorie aussi ce qui fait qu’on peut construire une arborescence de catégories.
Lors de la publication prochaine d’un document, la nouvelle catégorie créée sera proposée (...) -
Récupération d’informations sur le site maître à l’installation d’une instance
26 novembre 2010, parUtilité
Sur le site principal, une instance de mutualisation est définie par plusieurs choses : Les données dans la table spip_mutus ; Son logo ; Son auteur principal (id_admin dans la table spip_mutus correspondant à un id_auteur de la table spip_auteurs)qui sera le seul à pouvoir créer définitivement l’instance de mutualisation ;
Il peut donc être tout à fait judicieux de vouloir récupérer certaines de ces informations afin de compléter l’installation d’une instance pour, par exemple : récupérer le (...) -
D’autres logiciels intéressants
12 avril 2011, parOn ne revendique pas d’être les seuls à faire ce que l’on fait ... et on ne revendique surtout pas d’être les meilleurs non plus ... Ce que l’on fait, on essaie juste de le faire bien, et de mieux en mieux...
La liste suivante correspond à des logiciels qui tendent peu ou prou à faire comme MediaSPIP ou que MediaSPIP tente peu ou prou à faire pareil, peu importe ...
On ne les connais pas, on ne les a pas essayé, mais vous pouvez peut être y jeter un coup d’oeil.
Videopress
Site Internet : (...)
Sur d’autres sites (4770)
-
where to put the watermark png file in this code ?
15 août 2017, par asifthis is a line from ffmpeg video converter php script ;
$ffmpeg." -i ".$video_to_convert." -vcodec flv -f flv -r 30 -b ".$quality."-ab 128000 -ar".$audio." -s ".$size." ".$converted_vids.$name.".".$new_format."
where :
.$video_to_convert. = input file
.$converted_vids.$name. = output file
.$new_format. ; = file extention format
now i want to add watermark.png file, if i put any where i got error conversion
as i added the linelogo.png -filter_complex 'overlay
in video quality line, i got errorError ;
ffmpeg version N-71954-gbc6f84f Copyright (c) 2000-2015 the FFmpeg developers
built with gcc 4.4.7 (GCC) 20120313 (Red Hat 4.4.7-16)
configuration: --prefix=/usr --enable-version3 --enable-gpl --enable-shared --enable-libmp3lame --enable-libvorbis --enable-libtheora --enable-libvpx --enable-libx264 --enable-libxvid --enable-libopencore-amrwb --enable-libopencore-amrnb --enable-postproc --enable-nonfree --enable-pthreads --enable-x11grab --enable-libfaac --enable-libopenjpeg --enable-zlib --disable-doc
libavutil 54. 23.101 / 54. 23.101
libavcodec 56. 37.101 / 56. 37.101
libavformat 56. 31.102 / 56. 31.102
libavdevice 56. 4.100 / 56. 4.100
libavfilter 5. 16.101 / 5. 16.101
libswscale 3. 1.101 / 3. 1.101
libswresample 1. 1.100 / 1. 1.100
libpostproc 53. 3.100 / 53. 3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'uploaded/1502801111_21.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf56.31.102
Duration: 00:02:27.32, start: 0.023220, bitrate: 635 kb/s
Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 480x320 [SAR 1:1 DAR 3:2], 476 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
Metadata:
handler_name : VideoHandler
Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 151 kb/s (default)
Metadata:
handler_name : SoundHandler
Please use -b:a or -b:v, -b is ambiguous
Cannot find a matching stream for unlabeled input pad 1 on filter Parsed_overlay_0This is index.php file scipt of conversion :
v<?php include("templates/header.php");?>
<div>
<?php
require_once('languages/en.php');
include ("includes/settings.php");
include("includes/functions.php");
include("includes/LIB_parse.php");
include("classes/other.php");
cron(); // to run cron job to delete all files
if(isset($_POST['uploader_0_name']) or isset ($_GET['uploaded_name']))
{
if(isset($_POST['uploader_0_name']))
{
list($_SESSION['original_name'], $ext) = explode('.',$_POST['uploader_0_name']);
}else{
$fullname=$_GET['uploaded_name'];
}
if(isset($_POST['uploader_0_name']))
{
list($_SESSION['original_name'], $ext) = explode('.',$_POST['uploader_0_name']);
}else{
list($_SESSION['original_name'], $ext) = explode('.',$_GET['uploaded_name']);
$_SESSION['original_name']= return_between($_GET['uploaded_name'], '_', "$ext", 'EXCL') ;
$_SESSION['original_name']= str_replace(".","",$_SESSION['original_name']);
}
if(isset($_POST['uploader_0_name']))
{
$fullname= $_POST['uploader_0_tmpname'];
}else{
$fullname=$_GET['uploaded_name'];
}
$ext= pathinfo($fullname, PATHINFO_EXTENSION);
$_SESSION['name']=RemoveExtension($fullname);
$store_dir="uploaded/";
$_SESSION['converted_vids']=$converted_vids;
$_SESSION['temp_dir']=$store_dir;
// if those directotires don't exist - create them and give them read/write permissions
if(!is_dir($store_dir)) mkdir($store_dir, 0777);
if(!is_dir($converted_vids)) mkdir($converted_vids, 0777);
$extension = substr($fullname, strrpos($fullname, "."));
$extension = strtolower($extension);
$video_to_convert=$store_dir.$_SESSION['name'];
$_SESSION['video_to_convert']=$video_to_convert;
$_SESSION['extension']=$extension;
/*******************************
check extenxions
***************************************************/
if (!in_array($ext, $allowedExtensions))
{
echo '<div style="text-align:center"><strong>'.$ext."</strong><br /> is an invalid file type!<br />Supported files are:<br /><strong>";
foreach ($allowedExtensions as $value) { echo $value . "<br />"; }
echo "</strong><br />";
echo "<a href="http://stackoverflow.com/feeds/tag/\"index.php\"">"."<img src="http://stackoverflow.com/feeds/tag/\"images/red-back.png\"" border="\"0\"" style='max-width: 300px; max-height: 300px' /></a></div>";
include("templates/footer.php");
exit;
}
?>
<center>
<form action="index.php" method="post" target="_self">
<br />
<fieldset>
<legend class="show_legend">Convert To</legend>
<div class="radio_buttons">
<img alt="" src="http://stackoverflow.com/feeds/tag/images/flv.jpg" class="format_button" style='max-width: 300px; max-height: 300px' />
<input type="radio" class="blue_font" value="flv" />
<img alt="" src="http://stackoverflow.com/feeds/tag/images/mp4.jpg" class="format_button" style='max-width: 300px; max-height: 300px' />
<input type="radio" value="mp4" />
<img alt="" src="http://stackoverflow.com/feeds/tag/images/wmv.png" class="format_button" style='max-width: 300px; max-height: 300px' />
<input type="radio" value="wmv" />
<img alt="" src="http://stackoverflow.com/feeds/tag/images/avi.png" class="format_button" style='max-width: 300px; max-height: 300px' />
<input type="radio" value="avi" />
<img alt="" src="http://stackoverflow.com/feeds/tag/images/mp3.png" class="format_button" style='max-width: 300px; max-height: 300px' />
<input type="radio" value="mp3" />
<img alt="" src="http://stackoverflow.com/feeds/tag/images/ogg.png" class="format_button" style='max-width: 300px; max-height: 300px' />
<input type="radio" value="ogg" />
<img alt="" src="http://stackoverflow.com/feeds/tag/images/webm.png" class="format_button" style='max-width: 300px; max-height: 300px' />
<input type="radio" value="webm" />
</div>
</fieldset>
<fieldset>
<legend class="show_legend">Optional settings</legend>
<div class="radio_buttons" style="display:inline;padding:10px">
<br />Video quality:
<select class="radio_buttons" disabled="disabled">
<option value="2000000">high</option>
<option value="logo.png -filter_complex 'overlay' ">medium</option>
<option value="-i seen.png \-filter_complex '[0:v][1:v]overlay=10:10:enable=between(t\,15\,25)' -c:v libx264 -pix_fmt yuv420p -movflags faststart">Seen</option>
<option value="-i logo2.png \-filter_complex '[0:v][1:v]overlay=10:10:enable=between(t\,10\,20)'">HD Watermark</option>
<option value="-i logo.png -filter_complex 'overlay'">Watermark</option>
<option value="-vf drawtext='fontsize=20:y=h-line_h-10:x=(2*n)-tw:fontfile='op.ttf':text='DesiBombs.com'' -c:v libx264 -pix_fmt yuv420p -movflags faststart">Watermark</option>
</select>
</div>
<div class="radio_buttons" style="display:inline;padding:10px">Audio quality:
<select class="radio_buttons" disabled="disabled">
<option value="44100">high</option>
<option value="22050">medium</option>
<option value="11025">low</option>
</select>
<div class="radio_buttons" style="display:inline;padding:10px">Video size:
<select class="radio_buttons" disabled="disabled">
<option value="320x240">320x240</option>
<option value="512x384" selected="selected">512x384</option>
<option value="640x360">640x360</option>
<option value="854x480">854x480</option>
<option value="1280x720">1280x720</option>
</select>
</div>
</div></fieldset>
<div class="radio_buttons">
<input type="submit" disabled="disabled" value="" style="display:none" />
</div>
</form></center>
<?php
}
elseif(isset($_POST['type']))
{
$new_format=htmlspecialchars($_POST['type']); // read output format from form
$name=$_SESSION['name'];
//$_SESSION['extension'];
$video_to_convert=$store_dir.$_SESSION['name'].$_SESSION['extension'];
if (isset($_POST['size'])) {$size=$_POST['size'];}
if (isset($_POST['quality'])) {$quality=$_POST['quality'];}
if (isset($_POST['audio'])) {$audio=$_POST['audio'];}
if($new_format=="webm" && $audio=="11025"){$audio="22050";$new_format="webm"; }// for webm and ogg audio can not be 11050
if($new_format=="ogg" && $audio=="11025"){$audio="22050"; $new_format="ogg"; }// for webm and ogg audio can not be 11050
$_SESSION['type']=$new_format;
if($new_format=="flv"){ $call=$ffmpeg." -i ".$video_to_convert." -vcodec flv -f flv -r 30 -b ".$quality."-ab 128000 -ar".$audio." -s ".$size." ".$converted_vids.$name.".".$new_format." -y 2> log/".$name.".txt";}
if($new_format=="avi"){ $call=$ffmpeg." -i ".$video_to_convert." -vcodec mjpeg -f avi -acodec libmp3lame -b ".$quality." -s ".$size." -r 30 -g 12 -qmin 3 -qmax 13 -ab 224 -ar ".$audio." -ac 2 ".$converted_vids.$name.".".$new_format." -y 2> log/".$name.".txt";}
if($new_format=="mp3"){ $call=$ffmpeg." -i ".$video_to_convert." -vn -acodec libmp3lame -ac 2 -ab 128000 -ar ".$audio." ".$converted_vids.$name.".".$new_format." -y 2> log/".$name.".txt";}
if($new_format=="mp4"){ $call=$ffmpeg." -i ".$video_to_convert." -vf logo.png -vcodec mpeg4 -r 30 -b ".$quality." -acodec libmp3lame -ab 126000 -ar ".$audio." -ac 2 -s ".$size." ".$converted_vids.$name.".".$new_format." -y 2> log/".$name.".txt";}
if($new_format=="wmv"){ $call=$ffmpeg." -i ".$video_to_convert." -vcodec wmv1 -r 30 -b ".$quality." -acodec wmav2 -ab 128000 -ar ".$audio." -ac 2 -s ".$size." ".$converted_vids.$name.".".$new_format." -y 2> log/".$name.".txt";}
if($new_format=="ogg"){ $call=$ffmpeg." -i ".$video_to_convert." -vcodec libtheora -r 30 -b ".$quality." -acodec libvorbis -ab 128000 -ar ".$audio." -ac 2 -s ".$size." ".$converted_vids.$name.".".$new_format." -y 2> log/".$name.".txt";}
if($new_format=="webm"){ $call=$ffmpeg." -i ".$video_to_convert." -vcodec libvpx -r 30 -b ".$quality." -acodec libvorbis -ab 128000 -ar ".$audio." -ac 2 -s ".$size." ".$converted_vids.$name.".".$new_format." -y 2> log/".$name.".txt";}
/* START CONVERTING The Video */
require_once("includes/ffmpeg_cmd.php");
$convert = (popen($convert_call, "r"));
pclose($convert);
flush();
// define sessions
$_SESSION['dest_file']=$converted_vids.$name.".".$new_format;
echo "<code class="echappe-js"><script>\n";<br />
echo "counter = 5\n";<br />
echo "var redirect = 0; \n";<br />
echo "$(document).ready(function()\n";<br />
echo "{\n";<br />
echo "var refreshId = setInterval(function() \n";<br />
echo "{\n";<br />
echo "if(redirect == 0) \n { \n";<br />
echo "$('#timeval').load('progress_bar.php');\n";<br />
echo "}\n";<br />
echo "else \n";<br />
echo "{\n";<br />
echo "$('#timeval').load('progress_bar.php?counter='+ counter--);\n";<br />
echo "}\n";<br />
echo "}, 1000);\n";<br />
echo "});\n"; <br />
echo "</script>\n" ;
//
/************************* for debug *************************************
echo "" ; print_r ($_SESSION) ; echo "
" ; **********************************************************************************/
?>
< ?php
else if(isset($_GET[’finished’]))
echo "" ; if(!isset($_SESSION[’name’])) echo "please convert new video" ;include("templates/footer.php") ; ;exit ; $filepath=$converted_vids."./".$_SESSION[’name’].".".$_SESSION[’type’] ; require_once"video_duration.php" ;
$_SESSION[’duration’]=$hours." :".$minutes." :".$seconds ;
$vid_name=$_SESSION[’name’] ;
$vid_src=$_SESSION[’extension’] ;
$vid_new=$_SESSION[’type’] ;
if (isset($_SESSION[’duration’])) $duration=$_SESSION[’duration’] ;else $duration="unknown" ;
if(file_exists($converted_vids.$vid_name.".".$vid_new))
$vid_size=get_size($converted_vids.$vid_name.".".$vid_new) ;
else $vid_size=0 ;?>
your video informationVideo duration < ?php echo $hours." :".$minutes." :".$seconds ; ?> original video name < ?php if(isset($_SESSION[’original_name’]))echo $_SESSION[’original_name’] ; ?> video size < ?php echo $vid_size." MB
" ; ?>source extension < ?php echo str_replace(".","","$vid_src") ; ?> new extension < ?php echo $vid_new ; ?> < ?php
echo "
" ;
session_unset() ;
else
?><script type="text/javascript"><br />
// Convert divs to queue widgets when the DOM is ready<br />
$(function() {<br />
$("#uploader").pluploadQueue({<br />
// General settings<br />
runtimes : 'flash',<br />
url : 'upload.php',<br />
max_file_size : '&lt;?php echo $max_file_size ;?>mb',<br />
chunk_size : '1mb',<br />
unique_names : true,<br />
<br />
// Resize images on clientside if we can<br />
resize : {width : 320, height : 240, quality : 90},<br />
init : {<br />
FilesAdded: function(up, files) {<br />
plupload.each(files, function(file) {<br />
if (up.files.length > 1) {<br />
up.removeFile(file);<br />
}<br />
});<br />
if (up.files.length >= 1) {<br />
$('#pickfiles').hide('slow');<br />
}<br />
},<br />
FilesRemoved: function(up, files) {<br />
if (up.files.length < 1) {<br />
$('#pickfiles').fadeIn('slow');<br />
}<br />
}<br />
},<br />
multi_selection: false,<br />
// Specify what files to browse for<br />
filters : [<br />
{title : "Video files", extensions : "&lt;?php foreach ($allowedExtensions as $value) { echo $value . ","; }?>"}<br />
<br />
],<br />
<br />
// Flash settings<br />
flash_swf_url : 'js/plupload.flash.swf',<br />
<br />
// Silverlight settings<br />
silverlight_xap_url : 'js/plupload.silverlight.xap'<br />
});<br />
<br />
// Client side form validation<br />
$('form').submit(function(e) {<br />
var uploader = $('#uploader').pluploadQueue();<br />
<br />
// Files in queue upload them first<br />
if (uploader.files.length > 0) {<br />
// When all files are uploaded submit form<br />
uploader.bind('StateChanged', function() {<br />
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {<br />
$('form')[0].submit();<br />
}<br />
});<br />
<br />
uploader.start();<br />
} else {<br />
alert('You must queue at least one video.');<br />
}<br />
<br />
return false;<br />
});<br />
});<br />
</script>Maximum upload size < ?php echo $max_file_size ; ?> MB
< ?php include("templates/info.php") ; ?>
< ?php
//End Body Area/
?>
Use libavcodec on MPEG-TS to transcode video and copy audio
I’m trying to use libavcodec
to reduce the video bitrate of an MPEG transport stream while passing audio streams unchanged. The equivalent ffmpeg
command line would be :
ffmpeg -i SPTS_HD_2min.prog.ts -b:v 800k -s cif -map 0:0 -map 0:1 -map 0:2 -c:a copy ./transcodeCLI.ts
The input file contains :
Input #0, mpegts, from 'SPTS_HD_2min.program8.ts': Duration: 00:02:01.56 bitrate: 10579 kb/s
Program 1
Stream #0:0[0x21]: Video: h264 (High) ([27][0][0][0] / 0x001B), yuv420p(tv, bt709, top first), 1920x1080 [SAR 1:1 DAR 16:9], 25 fps, 25 tbr, 90k tbn, 50 tbc
Stream #0:1[0x61](eng): Audio: ac3 (AC-3 / 0x332D4341), 48000 Hz, 5.1(side), fltp, 384 kb/s
Stream #0:2[0x63](eng): Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 192 kb/s
Using the transcoding.c example, the program does generate a valid transport stream. However, the file does not play. Also, analysis tools show the file duration as almost twice as long. Something is not right.
The program is simple : read, encode, write in a loop. The codec context for the video stream is set for a lower bit rate and width/height.
I’ve tinkered with it for a long time without success, but nothing I set gets the expected behavior...
The very summarized source is directly below. (I’ve removed variable defs, error checking and debug messages for brevity).
EDIT
And I’ve included the full, compilable, source code just after that.
EDIT II
The MPEG-TS test file can be downloaded from this sharing server
typedef struct StreamContext
{
AVCodecContext *decodeCtx;
AVCodecContext *encodeCtx;
} StreamContext;
static StreamContext *streamCtx;
static int
openInputFile(const char *filename)
{
inFormatCtx = NULL;
ret = avformat_open_input(&inFormatCtx, filename, NULL, NULL);
ret = avformat_find_stream_info(inFormatCtx, NULL)
streamCtx = av_mallocz_array(inFormatCtx->nb_streams, sizeof(*streamCtx));
for (i = 0; i < inFormatCtx->nb_streams; i++)
{
AVStream *stream = inFormatCtx->streams[i];
AVCodec *dec = avcodec_find_decoder(stream->codecpar->codec_id);
AVCodecContext *pCodecCtx = avcodec_alloc_context3(dec);
ret = avcodec_parameters_to_context(pCodecCtx, stream->codecpar);
if (pCodecCtx->codec_type == AVMEDIA_TYPE_VIDEO || pCodecCtx->codec_type == AVMEDIA_TYPE_AUDIO)
{
if (pCodecCtx->codec_type == AVMEDIA_TYPE_VIDEO)
pCodecCtx->framerate = av_guess_frame_rate(inFormatCtx, stream, NULL);
/* Open decoder */
ret = avcodec_open2(pCodecCtx, dec, NULL);
}
streamCtx[i].decodeCtx = pCodecCtx;
}
return 0;
}
static int
openOutputFile(const char *filename)
{
outFormatCtx = NULL;
avformat_alloc_output_context2(&outFormatCtx, NULL, NULL, filename);
for (i = 0; i < inFormatCtx->nb_streams; i++)
{
out_stream = avformat_new_stream(outFormatCtx, NULL);
in_stream = inFormatCtx->streams[i];
decodeCtx = streamCtx[i].decodeCtx;
if (decodeCtx->codec_type == AVMEDIA_TYPE_VIDEO || decodeCtx->codec_type == AVMEDIA_TYPE_AUDIO)
{
encoder = avcodec_find_encoder(decodeCtx->codec_id);
pEncodeCtx = avcodec_alloc_context3(encoder);
if (decodeCtx->codec_type == AVMEDIA_TYPE_VIDEO)
{
// MAKE IT SMALLER!
pEncodeCtx->height = decodeCtx->height / 4;
pEncodeCtx->width = decodeCtx->width / 4;
pEncodeCtx->sample_aspect_ratio = decodeCtx->sample_aspect_ratio;
// perhaps set these too?
pEncodeCtx->bit_rate = 700000;
pEncodeCtx->bit_rate_tolerance = 0;
pEncodeCtx->framerate = decodeCtx->framerate;
pEncodeCtx->time_base = decodeCtx->time_base;
/* take first format from list of supported formats */
if (encoder->pix_fmts)
pEncodeCtx->pix_fmt = encoder->pix_fmts[0];
else
pEncodeCtx->pix_fmt = decodeCtx->pix_fmt;
/* video time_base can be set to whatever is handy and supported by encoder */
pEncodeCtx->time_base = av_inv_q(decodeCtx->framerate);
}
else
{
pEncodeCtx->sample_rate = decodeCtx->sample_rate;
pEncodeCtx->channel_layout = decodeCtx->channel_layout;
pEncodeCtx->channels = av_get_channel_layout_nb_channels(pEncodeCtx->channel_layout);
/* take first format from list of supported formats */
pEncodeCtx->sample_fmt = encoder->sample_fmts[0];
pEncodeCtx->time_base = (AVRational) { 1, pEncodeCtx->sample_rate };
}
ret = avcodec_open2(pEncodeCtx, encoder, NULL);
ret = avcodec_parameters_from_context(out_stream->codecpar, pEncodeCtx);
if (outFormatCtx->oformat->flags & AVFMT_GLOBALHEADER)
pEncodeCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
out_stream->time_base = pEncodeCtx->time_base;
streamCtx[i].encodeCtx = pEncodeCtx;
}
else if (decodeCtx->codec_type == AVMEDIA_TYPE_UNKNOWN)
return AVERROR_INVALIDDATA;
else
{
/* if this stream must be remuxed */
ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
out_stream->time_base = in_stream->time_base;
}
}
av_dump_format(outFormatCtx, 0, filename, 1);
if (!(outFormatCtx->oformat->flags & AVFMT_NOFILE))
ret = avio_open(&outFormatCtx->pb, filename, AVIO_FLAG_WRITE);
/* init muxer, write output file header */
ret = avformat_write_header(outFormatCtx, NULL);
return 0;
}
static int
encodeAndWriteFrame(AVFrame *inFrame, unsigned int streamIndex, int *pGotFrame)
{
encodedPkt.data = NULL;
encodedPkt.size = 0;
av_init_packet(&encodedPkt);
int codecType = inFormatCtx->streams[streamIndex]->codecpar->codec_type;
if (codecType == AVMEDIA_TYPE_VIDEO)
ret = avcodec_encode_video2(streamCtx[streamIndex].encodeCtx, &encodedPkt, inFrame, pGotFrame);
else
ret = avcodec_encode_audio2(streamCtx[streamIndex].encodeCtx, &encodedPkt, inFrame, pGotFrame);
if (*pGotFrame == 0)
return 0;
/* prepare packet for muxing */
encodedPkt.stream_index = streamIndex;
av_packet_rescale_ts(&encodedPkt, streamCtx[streamIndex].encodeCtx->time_base, outFormatCtx->streams[streamIndex]->time_base);
/* mux encoded frame */
ret = av_interleaved_write_frame(outFormatCtx, &encodedPkt);
return ret;
}
int
main(int argc, char **argv)
{
av_register_all();
avfilter_register_all();
if ((ret = openInputFile(argv[1])) < 0)
goto end;
if ((ret = openOutputFile(argv[2])) < 0)
goto end;
/* read all packets */
while (1)
{
if ((ret = av_read_frame(inFormatCtx, &packet)) < 0)
break;
readPktNum++;
streamIndex = packet.stream_index;
type = inFormatCtx->streams[packet.stream_index]->codecpar->codec_type;
av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n", streamIndex);
if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
{
pDecFrame = av_frame_alloc();
av_packet_rescale_ts(&packet, inFormatCtx->streams[streamIndex]->time_base, streamCtx[streamIndex].decodeCtx->time_base);
if (type == AVMEDIA_TYPE_VIDEO)
ret = avcodec_decode_video2(streamCtx[streamIndex].decodeCtx, pDecFrame, &gotDecFrame, &packet);
else
ret = avcodec_decode_audio4(streamCtx[streamIndex].decodeCtx, pDecFrame, &gotDecFrame, &packet);
if (gotDecFrame)
{
pDecFrame->pts = av_frame_get_best_effort_timestamp(pDecFrame);
ret = encodeAndWriteFrame(pDecFrame, streamIndex, 0);
av_frame_free(&pDecFrame);
if (ret < 0)
goto end;
}
else
av_frame_free(&pDecFrame);
}
else
{
/* remux this frame without reencoding */
av_packet_rescale_ts(&packet, inFormatCtx->streams[streamIndex]->time_base, outFormatCtx->streams[streamIndex]->time_base);
ret = av_interleaved_write_frame(outFormatCtx, &packet);
if (ret < 0)
goto end;
}
av_packet_unref(&packet);
}
/* flush encoders */
for (i = 0; i < inFormatCtx->nb_streams; i++)
{
/* flush encoder */
ret = flushEncoder(i);
}
av_write_trailer(outFormatCtx);
end:
av_packet_unref(&packet);
av_frame_free(&pDecFrame);
for (i = 0; i < inFormatCtx->nb_streams; i++)
{
avcodec_free_context(&streamCtx[i].decodeCtx);
if (outFormatCtx && outFormatCtx->nb_streams > i && outFormatCtx->streams[i] && streamCtx[i].encodeCtx)
avcodec_free_context(&streamCtx[i].encodeCtx);
}
av_free(streamCtx);
avformat_close_input(&inFormatCtx);
if (outFormatCtx && !(outFormatCtx->oformat->flags & AVFMT_NOFILE))
avio_closep(&outFormatCtx->pb);
avformat_free_context(outFormatCtx);
return ret ? 1 : 0;
}
**EDIT - Full source **
/**
* @file
* API example for demuxing, decoding, filtering, encoding and muxing
* @example transcoding.c
*/
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavfilter/avfiltergraph.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_PINK "\x1b[31;1m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_LIME "\x1b[32;1m"
#define ANSI_COLOR_YELLOW "\x1b[33;1m"
#define ANSI_COLOR_BLUE "\x1b[34;1m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36;1m"
#define ANSI_COLOR_RESET "\x1b[0m"
#define true 1
#define false 0
static int readPktNum = 0;
static int decFrameNum = 0;
static int encFrameNum = 0;
static AVFormatContext *inFormatCtx;
static AVFormatContext *outFormatCtx;
typedef struct StreamContext
{
AVCodecContext *decodeCtx;
AVCodecContext *encodeCtx;
} StreamContext;
static StreamContext *streamCtx;
void
writeAVFrameAsYUVFile(const char *filePath, AVFrame *pFrame)
{
printf("Writing YUV file: %d x %d\n", pFrame->width, pFrame->height);
FILE *pFile = fopen(filePath, "wb");
if (!pFile)
return;
int y;
// Writing Y
for (y=0; y < pFrame->height; y++)
fwrite(&pFrame->data[0][pFrame->linesize[0] * y], pFrame->width, 1, pFile);
// Writing U
for (y=0; y < pFrame->height/2; y++)
fwrite(&pFrame->data[1][pFrame->linesize[1] * y], pFrame->width/2, 1, pFile);
// Writing V
for (y=0; y < pFrame->height/2; y++)
fwrite(&pFrame->data[2][pFrame->linesize[2] * y], pFrame->width/2, 1, pFile);
fclose(pFile);
printf("Wrote %s: %d x %d\n", filePath, pFrame->width, pFrame->height);
}
static void
dumpCodecContext(const AVCodecContext *pCodecContext)
{
printf("Codec Context:\n");
printf(" bit rate %d\n", (int)pCodecContext->bit_rate);
printf(" bit rate tolerance %d\n", pCodecContext->bit_rate_tolerance);
printf(" size %d x %d\n", pCodecContext->width, pCodecContext->height);
printf(" GOP Size %d\n", pCodecContext->gop_size);
printf(" Max B Frames %d\n", pCodecContext->max_b_frames);
printf(" Sample Aspect %d:%d (%.3f)\n",
pCodecContext->sample_aspect_ratio.num, pCodecContext->sample_aspect_ratio.den,
1.0 * pCodecContext->sample_aspect_ratio.num / pCodecContext->sample_aspect_ratio.den);
printf(" framerate %d / %d (%.3f fps)\n",
pCodecContext->framerate.num, pCodecContext->framerate.den,
1.0 * pCodecContext->framerate.den / pCodecContext->framerate.num);
printf(" time_base %d / %d (%.3f fps)\n",
pCodecContext->time_base.num, pCodecContext->time_base.den,
1.0 * pCodecContext->time_base.den / pCodecContext->time_base.num);
}
static int
openInputFile(const char *filename)
{
int ret;
unsigned int i;
inFormatCtx = NULL;
if ((ret = avformat_open_input(&inFormatCtx, filename, NULL, NULL)) < 0)
{
av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
return ret;
}
if ((ret = avformat_find_stream_info(inFormatCtx, NULL)) < 0)
{
av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
return ret;
}
streamCtx = av_mallocz_array(inFormatCtx->nb_streams, sizeof(*streamCtx));
if (!streamCtx)
return AVERROR(ENOMEM);
for (i = 0; i < inFormatCtx->nb_streams; i++)
{
AVStream *stream = inFormatCtx->streams[i];
AVCodec *dec = avcodec_find_decoder(stream->codecpar->codec_id);
AVCodecContext *pCodecCtx;
if (!dec)
{
av_log(NULL, AV_LOG_ERROR, "Failed to find decoder for stream #%u\n", i);
return AVERROR_DECODER_NOT_FOUND;
}
pCodecCtx = avcodec_alloc_context3(dec);
if (!pCodecCtx)
{
av_log(NULL, AV_LOG_ERROR, "Failed to allocate the decoder context for stream #%u\n", i);
return AVERROR(ENOMEM);
}
ret = avcodec_parameters_to_context(pCodecCtx, stream->codecpar);
if (ret < 0)
{
av_log(NULL, AV_LOG_ERROR, "Failed to copy decoder parameters to input decoder context for stream #%u\n", i);
return ret;
}
/* Reencode video & audio and remux subtitles etc. */
if (pCodecCtx->codec_type == AVMEDIA_TYPE_VIDEO || pCodecCtx->codec_type == AVMEDIA_TYPE_AUDIO)
{
if (pCodecCtx->codec_type == AVMEDIA_TYPE_VIDEO)
pCodecCtx->framerate = av_guess_frame_rate(inFormatCtx, stream, NULL);
/* Open decoder */
ret = avcodec_open2(pCodecCtx, dec, NULL);
if (ret < 0)
{
av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
return ret;
}
}
streamCtx[i].decodeCtx = pCodecCtx;
}
av_dump_format(inFormatCtx, 0, filename, 0);
return 0;
}
static int
openOutputFile(const char *filename)
{
AVStream *out_stream;
AVStream *in_stream;
AVCodecContext *decodeCtx, *pEncodeCtx;
AVCodec *encoder;
int ret;
unsigned int i;
outFormatCtx = NULL;
avformat_alloc_output_context2(&outFormatCtx, NULL, NULL, filename);
if (!outFormatCtx)
{
av_log(NULL, AV_LOG_ERROR, "Could not create output context\n");
return AVERROR_UNKNOWN;
}
for (i = 0; i < inFormatCtx->nb_streams; i++)
{
out_stream = avformat_new_stream(outFormatCtx, NULL);
if (!out_stream)
{
av_log(NULL, AV_LOG_ERROR, "Failed allocating output stream\n");
return AVERROR_UNKNOWN;
}
in_stream = inFormatCtx->streams[i];
decodeCtx = streamCtx[i].decodeCtx;
if (decodeCtx->codec_type == AVMEDIA_TYPE_VIDEO || decodeCtx->codec_type == AVMEDIA_TYPE_AUDIO)
{
/* in this example, we choose transcoding to same codec */
encoder = avcodec_find_encoder(decodeCtx->codec_id);
if (!encoder)
{
av_log(NULL, AV_LOG_FATAL, "Necessary encoder not found\n");
return AVERROR_INVALIDDATA;
}
pEncodeCtx = avcodec_alloc_context3(encoder);
if (!pEncodeCtx)
{
av_log(NULL, AV_LOG_FATAL, "Failed to allocate the encoder context\n");
return AVERROR(ENOMEM);
}
/* In this example, we transcode to same properties (picture size,
* sample rate etc.). These properties can be changed for output
* streams easily using filters */
if (decodeCtx->codec_type == AVMEDIA_TYPE_VIDEO)
{
printf("DECODE CONTEXT "); dumpCodecContext(decodeCtx);
// MAKE IT SMALLER!
pEncodeCtx->height = decodeCtx->height / 4;
pEncodeCtx->width = decodeCtx->width / 4;
pEncodeCtx->sample_aspect_ratio = decodeCtx->sample_aspect_ratio;
// perhaps set these too?
pEncodeCtx->bit_rate = 700000;
pEncodeCtx->bit_rate_tolerance = 0;
pEncodeCtx->framerate = decodeCtx->framerate;
pEncodeCtx->time_base = decodeCtx->time_base;
printf("ENCODE CONTEXT "); dumpCodecContext(pEncodeCtx);
/* take first format from list of supported formats */
if (encoder->pix_fmts)
pEncodeCtx->pix_fmt = encoder->pix_fmts[0];
else
pEncodeCtx->pix_fmt = decodeCtx->pix_fmt;
/* video time_base can be set to whatever is handy and supported by encoder */
pEncodeCtx->time_base = av_inv_q(decodeCtx->framerate);
}
else
{
pEncodeCtx->sample_rate = decodeCtx->sample_rate;
pEncodeCtx->channel_layout = decodeCtx->channel_layout;
pEncodeCtx->channels = av_get_channel_layout_nb_channels(pEncodeCtx->channel_layout);
/* take first format from list of supported formats */
pEncodeCtx->sample_fmt = encoder->sample_fmts[0];
pEncodeCtx->time_base = (AVRational) { 1, pEncodeCtx->sample_rate };
}
/* Third parameter can be used to pass settings to encoder */
ret = avcodec_open2(pEncodeCtx, encoder, NULL);
if (ret < 0)
{
av_log(NULL, AV_LOG_ERROR, "Cannot open video encoder for stream #%u\n", i);
return ret;
}
ret = avcodec_parameters_from_context(out_stream->codecpar, pEncodeCtx);
if (ret < 0)
{
av_log(NULL, AV_LOG_ERROR, "Failed to copy encoder parameters to output stream #%u\n", i);
return ret;
}
if (outFormatCtx->oformat->flags & AVFMT_GLOBALHEADER)
pEncodeCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
out_stream->time_base = pEncodeCtx->time_base;
streamCtx[i].encodeCtx = pEncodeCtx;
}
else if (decodeCtx->codec_type == AVMEDIA_TYPE_UNKNOWN)
{
av_log(NULL, AV_LOG_FATAL, "Elementary stream #%d is of unknown type, cannot proceed\n", i);
return AVERROR_INVALIDDATA;
}
else
{
printf("STREAM %d is not video or audio\n", i);
/* if this stream must be remuxed */
ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
if (ret < 0)
{
av_log(NULL, AV_LOG_ERROR, "Copying parameters for stream #%u failed\n", i);
return ret;
}
out_stream->time_base = in_stream->time_base;
}
}
av_dump_format(outFormatCtx, 0, filename, 1);
if (!(outFormatCtx->oformat->flags & AVFMT_NOFILE))
{
ret = avio_open(&outFormatCtx->pb, filename, AVIO_FLAG_WRITE);
if (ret < 0)
{
av_log(NULL, AV_LOG_ERROR, "Could not open output file '%s'", filename);
return ret;
}
}
/* init muxer, write output file header */
ret = avformat_write_header(outFormatCtx, NULL);
if (ret < 0)
{
av_log(NULL, AV_LOG_ERROR, "Error occurred when opening output file\n");
return ret;
}
return 0;
}
static int
encodeAndWriteFrame(AVFrame *inFrame, unsigned int streamIndex, int *pGotFrame)
{
int ret;
int got_frame_local;
AVPacket encodedPkt;
if (pGotFrame == 0)
pGotFrame = &got_frame_local;
encodedPkt.data = NULL;
encodedPkt.size = 0;
av_init_packet(&encodedPkt);
int codecType = inFormatCtx->streams[streamIndex]->codecpar->codec_type;
if (codecType == AVMEDIA_TYPE_VIDEO)
ret = avcodec_encode_video2(streamCtx[streamIndex].encodeCtx, &encodedPkt, inFrame, pGotFrame);
else
ret = avcodec_encode_audio2(streamCtx[streamIndex].encodeCtx, &encodedPkt, inFrame, pGotFrame);
if (ret < 0)
return ret;
if (*pGotFrame == 0)
return 0;
if (encFrameNum++ % 10 == 0)
printf("Encoded %s frame #%d\n", (codecType == AVMEDIA_TYPE_VIDEO) ? "Video" : "Audio", encFrameNum);
/* prepare packet for muxing */
encodedPkt.stream_index = streamIndex;
av_packet_rescale_ts(&encodedPkt, streamCtx[streamIndex].encodeCtx->time_base, outFormatCtx->streams[streamIndex]->time_base);
av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
/* mux encoded frame */
ret = av_interleaved_write_frame(outFormatCtx, &encodedPkt);
return ret;
}
static int
flushEncoder(unsigned int streamIndex)
{
int ret;
int got_frame;
if (!(streamCtx[streamIndex].encodeCtx->codec->capabilities & AV_CODEC_CAP_DELAY))
return 0;
while (1)
{
av_log(NULL, AV_LOG_INFO, "Flushing stream #%u encoder\n", streamIndex);
ret = encodeAndWriteFrame(NULL, streamIndex, &got_frame);
if (ret < 0)
break;
if (!got_frame)
return 0;
}
return ret;
}
int
main(int argc, char **argv)
{
int ret;
AVPacket packet = { .data = NULL, .size = 0 };
AVFrame *pDecFrame = NULL;
enum AVMediaType type;
unsigned int streamIndex;
unsigned int i;
int gotDecFrame;
if (argc != 3)
{
av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file="file" /> <output file="file">\n", argv[0]);
return 1;
}
av_register_all();
avfilter_register_all();
if ((ret = openInputFile(argv[1])) < 0)
goto end;
if ((ret = openOutputFile(argv[2])) < 0)
goto end;
/* read all packets */
while (1)
{
if ((ret = av_read_frame(inFormatCtx, &packet)) < 0)
{
printf(ANSI_COLOR_YELLOW "READ PACKET RETURNED %d\n" ANSI_COLOR_RESET, ret);
break;
}
readPktNum++;
streamIndex = packet.stream_index;
type = inFormatCtx->streams[packet.stream_index]->codecpar->codec_type;
av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n", streamIndex);
if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
{
pDecFrame = av_frame_alloc();
if (!pDecFrame)
{
ret = AVERROR(ENOMEM);
break;
}
av_packet_rescale_ts(&packet, inFormatCtx->streams[streamIndex]->time_base, streamCtx[streamIndex].decodeCtx->time_base);
if (type == AVMEDIA_TYPE_VIDEO)
ret = avcodec_decode_video2(streamCtx[streamIndex].decodeCtx, pDecFrame, &gotDecFrame, &packet);
else
ret = avcodec_decode_audio4(streamCtx[streamIndex].decodeCtx, pDecFrame, &gotDecFrame, &packet);
if (ret < 0)
{
av_frame_free(&pDecFrame);
av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
break;
}
if (gotDecFrame)
{
if (decFrameNum++ % 10 == 0)
printf("Decoded %s frame #%d\n", (type == AVMEDIA_TYPE_VIDEO) ? "Video" : "Audio", decFrameNum);
if (0 && type == AVMEDIA_TYPE_VIDEO)
{
printf("VIDEO width %d height %d\n", pDecFrame->width, pDecFrame->height);
writeAVFrameAsYUVFile("/mnt/swdevel/DVStor/decodedYUV.yuv", pDecFrame);
}
pDecFrame->pts = av_frame_get_best_effort_timestamp(pDecFrame);
ret = encodeAndWriteFrame(pDecFrame, streamIndex, 0);
av_frame_free(&pDecFrame);
if (ret < 0)
goto end;
}
else
av_frame_free(&pDecFrame);
}
else
{
/* remux this frame without reencoding */
av_packet_rescale_ts(&packet, inFormatCtx->streams[streamIndex]->time_base, outFormatCtx->streams[streamIndex]->time_base);
ret = av_interleaved_write_frame(outFormatCtx, &packet);
if (ret < 0)
goto end;
}
av_packet_unref(&packet);
}
printf(ANSI_COLOR_YELLOW "EXIT MAIN WHILE(1) - FLUSHING\n" ANSI_COLOR_RESET);
/* flush encoders */
for (i = 0; i < inFormatCtx->nb_streams; i++)
{
/* flush encoder */
ret = flushEncoder(i);
if (ret < 0)
{
av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n");
goto end;
}
}
av_write_trailer(outFormatCtx);
end:
av_packet_unref(&packet);
av_frame_free(&pDecFrame);
for (i = 0; i < inFormatCtx->nb_streams; i++)
{
avcodec_free_context(&streamCtx[i].decodeCtx);
if (outFormatCtx && outFormatCtx->nb_streams > i && outFormatCtx->streams[i] && streamCtx[i].encodeCtx)
avcodec_free_context(&streamCtx[i].encodeCtx);
}
av_free(streamCtx);
avformat_close_input(&inFormatCtx);
if (outFormatCtx && !(outFormatCtx->oformat->flags & AVFMT_NOFILE))
avio_closep(&outFormatCtx->pb);
avformat_free_context(outFormatCtx);
if (ret < 0)
av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));
return ret ? 1 : 0;
}
</output>
How may I resolve 'NReco.VideoConverter.FFMpegException' error ?
The following code :
string pathToVideoFile = "O:\\Byblioteka\\MAH01238.MP4";
var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
ffMpeg.ConvertMedia(pathToVideoFile, "nowyplik.mp4", "Format.mp4");
Is resulting in the following error :
An unhandled exception of type ’NReco.VideoConverter.FFMpegException’ occurred in NReco.VideoConverter.dll
Additional information : nowyplik.mp4 : Invalid argument (exit code : 1)
How may I resolve this ’NReco.VideoConverter.FFMpegException’ error ?