
Recherche avancée
Autres articles (16)
-
Encoding and processing into web-friendly formats
13 avril 2011, parMediaSPIP automatically converts uploaded files to internet-compatible formats.
Video files are encoded in MP4, Ogv and WebM (supported by HTML5) and MP4 (supported by Flash).
Audio files are encoded in MP3 and Ogg (supported by HTML5) and MP3 (supported by Flash).
Where possible, text is analyzed in order to retrieve the data needed for search engine detection, and then exported as a series of image files.
All uploaded files are stored online in their original format, so you can (...) -
Demande de création d’un canal
12 mars 2010, parEn fonction de la configuration de la plateforme, l’utilisateur peu avoir à sa disposition deux méthodes différentes de demande de création de canal. La première est au moment de son inscription, la seconde, après son inscription en remplissant un formulaire de demande.
Les deux manières demandent les mêmes choses fonctionnent à peu près de la même manière, le futur utilisateur doit remplir une série de champ de formulaire permettant tout d’abord aux administrateurs d’avoir des informations quant à (...) -
Installation en mode ferme
4 février 2011, parLe mode ferme permet d’héberger plusieurs sites de type MediaSPIP en n’installant qu’une seule fois son noyau fonctionnel.
C’est la méthode que nous utilisons sur cette même plateforme.
L’utilisation en mode ferme nécessite de connaïtre un peu le mécanisme de SPIP contrairement à la version standalone qui ne nécessite pas réellement de connaissances spécifique puisque l’espace privé habituel de SPIP n’est plus utilisé.
Dans un premier temps, vous devez avoir installé les mêmes fichiers que l’installation (...)
Sur d’autres sites (3628)
-
Screen Capture with FFMPEG and Google Native Client
18 juillet 2016, par Mohammad Abu MusaI am building a screen recorder that is based on Native Client for Google, I have ffmpeg installed and ready but I do not have experience programming in ffmpeg. so I am looking for tips to understand how to build this recorder.
My goal is to make a screen recorder and export videos as webm files, I have all the required libraries I just could not find any code examples to hack on
This is what I achieved so far
#define __STDC_LIMIT_MACROS
#include
#include <iostream>
#include
#include
#include <sstream>
#include
#include <vector>
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/var_dictionary.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/ppb_console.h"
#include "ppapi/cpp/input_event.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/var.h"
#include "ppapi/cpp/var_array_buffer.h"
// Begin File IO headers
#include "ppapi/c/pp_stdint.h"
#include "ppapi/c/ppb_file_io.h"
#include "ppapi/cpp/directory_entry.h"
#include "ppapi/cpp/file_io.h"
#include "ppapi/cpp/file_ref.h"
#include "ppapi/cpp/file_system.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/message_loop.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "ppapi/cpp/var_array.h"
#include "ppapi/utility/completion_callback_factory.h"
#include "ppapi/utility/threading/simple_thread.h"
#ifndef INT32_MAX
#define INT32_MAX (0x7FFFFFFF)
#endif
#ifdef WIN32
#undef min
#undef max
#undef PostMessage
// Allow 'this' in initializer list
#pragma warning(disable : 4355)
#endif
namespace {
typedef std::vector StringVector;
}
//End File IO headers
extern "C" {
#include <libavcodec></libavcodec>avcodec.h>
#include <libswscale></libswscale>swscale.h>
#include <libavformat></libavformat>avformat.h>
#include <libavutil></libavutil>imgutils.h>
}
const char* file_name = "/file.txt";
const char* video_name = "/video.mpeg";
const char* file_text = "Echo from NaCl: ";
/**
* Pixel formats and codecs
*/
static const AVPixelFormat sourcePixelFormat = AV_PIX_FMT_BGR24;
static const AVPixelFormat destPixelFormat = AV_PIX_FMT_YUV420P;
static const AVCodecID destCodec = AV_CODEC_ID_MPEG2VIDEO;
class RecorderInstance: public pp::Instance {
public:
explicit RecorderInstance(PP_Instance instance) :
pp::Instance(instance), callback_factory_(this), file_system_(this,
PP_FILESYSTEMTYPE_LOCALPERSISTENT), file_system_ready_(
false), file_thread_(this) {
}
virtual ~RecorderInstance() {
file_thread_.Join();
}
virtual bool Init(uint32_t /*argc*/, const char * /*argn*/[],
const char * /*argv*/[]) {
file_thread_.Start();
file_thread_.message_loop().PostWork(
callback_factory_.NewCallback(
&RecorderInstance::OpenFileSystem));
avcodec_register_all(); // mandatory to register ffmpeg functions
return true;
}
private:
pp::CompletionCallbackFactory<recorderinstance> callback_factory_;
pp::FileSystem file_system_;
// Indicates whether file_system_ was opened successfully. We only read/write
// this on the file_thread_.
bool file_system_ready_;
pp::SimpleThread file_thread_;
virtual void HandleMessage(const pp::Var& var_message) {
if (!var_message.is_dictionary()) {
LogToConsole(PP_LOGLEVEL_ERROR, pp::Var("Invalid message!"));
return;
}
pp::VarDictionary dict_message(var_message);
std::string command = dict_message.Get("message").AsString();
if (command == "sendFrame") {
pp::VarArrayBuffer data(dict_message.Get("data"));
uint width = 600;
uint height = 800;
uint8_t endcode[] = { 0, 0, 1, 0xb7 };
/**
* Create an encoder and open it
*/
avcodec_register_all();
AVCodec *h264encoder = avcodec_find_encoder(destCodec);
AVCodecContext *h264encoderContext = avcodec_alloc_context3(
h264encoder);
h264encoderContext->pix_fmt = destPixelFormat;
h264encoderContext->width = width;
h264encoderContext->height = height;
if (avcodec_open2(h264encoderContext, h264encoder, NULL) < 0) {
ShowErrorMessage("Cannot open codec" ,-1);
return;
}
/**
* Create a stream
*/
AVFormatContext *cv2avFormatContext = avformat_alloc_context();
AVStream *h264outputstream = avformat_new_stream(cv2avFormatContext,
h264encoder);
AVFrame *sourceAvFrame = av_frame_alloc(), *destAvFrame =
av_frame_alloc();
int got_frame;
FILE* videoOutFile = fopen("video", "wb");
/**
* Prepare the conversion context
*/
SwsContext *bgr2yuvcontext = sws_getContext(width, height,
sourcePixelFormat, width, height, destPixelFormat,
SWS_BICUBIC, NULL, NULL, NULL);
int framesToEncode = 100;
/**
* Convert and encode frames
*/
for (uint i = 0; i < framesToEncode; i++) {
/**
* Allocate source frame, i.e. input to sws_scale()
*/
av_image_alloc(sourceAvFrame->data, sourceAvFrame->linesize,
width, height, sourcePixelFormat, 1);
/**
* Copy image data into AVFrame from cv::Mat
*/
for (uint32_t h = 0; h < height; h++)
memcpy(
&(sourceAvFrame->data[0][h
* sourceAvFrame->linesize[0]]),
&(data), width * 3);
/**
* Allocate destination frame, i.e. output from sws_scale()
*/
av_image_alloc(destAvFrame->data, destAvFrame->linesize, width,
height, destPixelFormat, 1);
sws_scale(bgr2yuvcontext, sourceAvFrame->data,
sourceAvFrame->linesize, 0, height, destAvFrame->data,
destAvFrame->linesize);
sws_freeContext(bgr2yuvcontext);
/**
* Prepare an AVPacket and set buffer to NULL so that it'll be allocated by FFmpeg
*/
AVPacket avEncodedPacket;
av_init_packet(&avEncodedPacket);
avEncodedPacket.data = NULL;
avEncodedPacket.size = 0;
destAvFrame->pts = i;
avcodec_encode_video2(h264encoderContext, &avEncodedPacket,
destAvFrame, &got_frame);
if (got_frame) {
ShowErrorMessage(
"Encoded a frame of size \n",-1); //+ (string)avEncodedPacket.size + "\n");
if (fwrite(avEncodedPacket.data, 1, avEncodedPacket.size,
videoOutFile) < (unsigned) avEncodedPacket.size)
ShowErrorMessage(
"Could not write all \n",-1);
//+ avEncodedPacket.size
//+ " bytes, but will continue..\n"
fflush(videoOutFile);
}
/**
* Per-frame cleanup
*/
av_packet_free_side_data(&avEncodedPacket);
av_free_packet(&avEncodedPacket);
av_freep(sourceAvFrame->data);
av_frame_free(&sourceAvFrame);
av_freep(destAvFrame->data);
av_frame_free(&destAvFrame);
}
fwrite(endcode, 1, sizeof(endcode), videoOutFile);
fclose(videoOutFile);
/**
* Final cleanup
*/
avformat_free_context(cv2avFormatContext);
avcodec_close(h264encoderContext);
avcodec_free_context(&h264encoderContext);
} else if (command == "createFile") {
file_thread_.message_loop().PostWork(
callback_factory_.NewCallback(&RecorderInstance::Save,
file_name, file_text));
}
}
void OpenFileSystem(int32_t /* result */) {
int32_t rv = file_system_.Open(1024 * 1024, pp::BlockUntilComplete());
if (rv == PP_OK) {
file_system_ready_ = true;
// Notify the user interface that we're ready
ShowStatusMessage("STORAGE READY");
} else {
ShowErrorMessage("Failed to open file system", rv);
}
}
void Save(int32_t /* result */, const std::string& file_name,
const std::string& file_contents) {
if (!file_system_ready_) {
ShowErrorMessage("File system is not open", PP_ERROR_FAILED);
return;
}
pp::FileRef ref(file_system_, file_name.c_str());
pp::FileIO file(this);
int32_t open_result = file.Open(ref,
PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_CREATE
| PP_FILEOPENFLAG_TRUNCATE, pp::BlockUntilComplete());
if (open_result != PP_OK) {
ShowErrorMessage("File open for write failed", open_result);
return;
}
// We have truncated the file to 0 bytes. So we need only write if
// file_contents is non-empty.
if (!file_contents.empty()) {
if (file_contents.length() > INT32_MAX) {
ShowErrorMessage("File too big", PP_ERROR_FILETOOBIG);
return;
}
int64_t offset = 0;
int32_t bytes_written = 0;
do {
bytes_written = file.Write(offset,
file_contents.data() + offset, file_contents.length(),
pp::BlockUntilComplete());
if (bytes_written > 0) {
offset += bytes_written;
} else {
ShowErrorMessage("File write failed", bytes_written);
return;
}
} while (bytes_written
< static_cast(file_contents.length()));
}
// All bytes have been written, flush the write buffer to complete
int32_t flush_result = file.Flush(pp::BlockUntilComplete());
if (flush_result != PP_OK) {
ShowErrorMessage("File fail to flush", flush_result);
return;
}
ShowStatusMessage("Save success");
}
/// Encapsulates our simple javascript communication protocol
void ShowErrorMessage(const std::string& message, int32_t result) {
std::stringstream ss;
ss << "ERROR: " << message << " -- Error #: " << result << "\n";
PostMessage(ss.str());
}
void ShowStatusMessage(const std::string& message) {
std::stringstream ss;
ss << "LOG: " << message << "\n";
PostMessage(ss.str());
}
};
class RecorderModule: public pp::Module {
public:
RecorderModule() :
pp::Module() {
}
virtual ~RecorderModule() {
}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new RecorderInstance(instance);
}
};
namespace pp {
/**
* This function is an entry point to a NaCl application.
* It must be implemented.
*/
Module* CreateModule() {
return new RecorderModule();
}
} // namespace pp
</recorderinstance></vector></sstream></iostream> -
ffmpeg record screen and save video file to disk as .mp4 or .mpg
5 janvier 2015, par musimbateI want to record the screen of my pc (using gdigrab on my windows machine) and store the saved video file on my disk as an mp4 or mpg file .I have found an example piece of code that grabs the screen and shows it in an SDL window here :http://xwk.iteye.com/blog/2125720 (The code is on the bottom of the page and has an english version) and the ffmpeg muxing example https://ffmpeg.org/doxygen/trunk/muxing_8c-source.html seems to be able to help encode audio and video into a desired output video file.
I have tried to combine these two by having a format context for grabbing the screen (AVFormatContext *pFormatCtx ; in my code ) and a separate format context to write the desired video file (AVFormatContext *outFormatContextEncoded ;).Within the loop to read packets from the input stream( screen grab stream) I directly encode write packets to the output file as shown in my code.I have kept the SDL code so I can see what I am recording.Below is my code with my modified write_video_frame() function .
The code builds OK but the output video can’t be played by vlc. When I run the command
ffmpeg -i filename.mpg
I get this output
[mpeg @ 003fed20] probed stream 0 failed
[mpeg @ 003fed20] Stream #0: not enough frames to estimate rate; consider increasing probesize
[mpeg @ 003fed20] Could not find codec parameters for stream 0 (Video: none): unknown codec
Consider increasing the value for the 'analyzeduration' and 'probesize' options
karamage.mpg: could not find codec parameters
Input #0, mpeg, from 'karamage.mpg':
Duration: 19:30:09.25, start: 37545.438756, bitrate: 2 kb/s
Stream #0:0[0x1e0]: Video: none, 90k tbr, 90k tbn
At least one output file must be specifiedAm I doing something wrong here ? I am new to ffmpeg and any guidance on this is highly appreciated.Thank you for your time.
int main(int argc, char* argv[])
{
AVFormatContext *pFormatCtx;
int i, videoindex;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
av_register_all();
avformat_network_init();
//Localy defined structure.
OutputStream outVideoStream = { 0 };
const char *filename;
AVOutputFormat *outFormatEncoded;
AVFormatContext *outFormatContextEncoded;
AVCodec *videoCodec;
filename="karamage.mpg";
int ret1;
int have_video = 0, have_audio = 0;
int encode_video = 0, encode_audio = 0;
AVDictionary *opt = NULL;
//ASSIGN STH TO THE FORMAT CONTEXT.
pFormatCtx = avformat_alloc_context();
//
//Use this when opening a local file.
//char filepath[]="src01_480x272_22.h265";
//avformat_open_input(&pFormatCtx,filepath,NULL,NULL)
//Register Device
avdevice_register_all();
//Use gdigrab
AVDictionary* options = NULL;
//Set some options
//grabbing frame rate
//av_dict_set(&options,"framerate","5",0);
//The distance from the left edge of the screen or desktop
//av_dict_set(&options,"offset_x","20",0);
//The distance from the top edge of the screen or desktop
//av_dict_set(&options,"offset_y","40",0);
//Video frame size. The default is to capture the full screen
//av_dict_set(&options,"video_size","640x480",0);
AVInputFormat *ifmt=av_find_input_format("gdigrab");
if(avformat_open_input(&pFormatCtx,"desktop",ifmt,&options)!=0){
printf("Couldn't open input stream.\n");
return -1;
}
if(avformat_find_stream_info(pFormatCtx,NULL)<0)
{
printf("Couldn't find stream information.\n");
return -1;
}
videoindex=-1;
for(i=0; inb_streams; i++)
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
{
videoindex=i;
break;
}
if(videoindex==-1)
{
printf("Didn't find a video stream.\n");
return -1;
}
pCodecCtx=pFormatCtx->streams[videoindex]->codec;
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL)
{
printf("Codec not found.\n");
return -1;
}
if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)
{
printf("Could not open codec.\n");
return -1;
}
AVFrame *pFrame,*pFrameYUV;
pFrame=avcodec_alloc_frame();
pFrameYUV=avcodec_alloc_frame();
//PIX_FMT_YUV420P WHAT DOES THIS SAY ABOUT THE FORMAT??
uint8_t *out_buffer=(uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);
//<<<<<<<<<<<-------PREP WORK TO WRITE ENCODED VIDEO FILES-----
avformat_alloc_output_context2(&outFormatContextEncoded, NULL, NULL, filename);
if (!outFormatContextEncoded) {
printf("Could not deduce output format from file extension: using MPEG.\n");
avformat_alloc_output_context2(&outFormatContextEncoded, NULL, "mpeg", filename);
}
if (!outFormatContextEncoded)
return 1;
outFormatEncoded=outFormatContextEncoded->oformat;
//THIS CREATES THE STREAMS(AUDIO AND VIDEO) ADDED TO OUR OUTPUT STREAM
if (outFormatEncoded->video_codec != AV_CODEC_ID_NONE) {
//YOUR VIDEO AND AUDIO PROPS ARE SET HERE.
add_stream(&outVideoStream, outFormatContextEncoded, &videoCodec, outFormatEncoded->video_codec);
have_video = 1;
encode_video = 1;
}
// Now that all the parameters are set, we can open the audio and
// video codecs and allocate the necessary encode buffers.
if (have_video)
open_video(outFormatContextEncoded, videoCodec, &outVideoStream, opt);
av_dump_format(outFormatContextEncoded, 0, filename, 1);
/* open the output file, if needed */
if (!(outFormatEncoded->flags & AVFMT_NOFILE)) {
ret1 = avio_open(&outFormatContextEncoded->pb, filename, AVIO_FLAG_WRITE);
if (ret1 < 0) {
//fprintf(stderr, "Could not open '%s': %s\n", filename,
// av_err2str(ret));
fprintf(stderr, "Could not open your dumb file.\n");
return 1;
}
}
/* Write the stream header, if any. */
ret1 = avformat_write_header(outFormatContextEncoded, &opt);
if (ret1 < 0) {
//fprintf(stderr, "Error occurred when opening output file: %s\n",
// av_err2str(ret));
fprintf(stderr, "Error occurred when opening output file\n");
return 1;
}
//<<<<<<<<<<<-------PREP WORK TO WRITE ENCODED VIDEO FILES-----
//SDL----------------------------
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
printf( "Could not initialize SDL - %s\n", SDL_GetError());
return -1;
}
int screen_w=640,screen_h=360;
const SDL_VideoInfo *vi = SDL_GetVideoInfo();
//Half of the Desktop's width and height.
screen_w = vi->current_w/2;
screen_h = vi->current_h/2;
SDL_Surface *screen;
screen = SDL_SetVideoMode(screen_w, screen_h, 0,0);
if(!screen) {
printf("SDL: could not set video mode - exiting:%s\n",SDL_GetError());
return -1;
}
SDL_Overlay *bmp;
bmp = SDL_CreateYUVOverlay(pCodecCtx->width, pCodecCtx->height,SDL_YV12_OVERLAY, screen);
SDL_Rect rect;
//SDL End------------------------
int ret, got_picture;
AVPacket *packet=(AVPacket *)av_malloc(sizeof(AVPacket));
//TRY TO INIT THE PACKET HERE
av_init_packet(packet);
//Output Information-----------------------------
printf("File Information---------------------\n");
av_dump_format(pFormatCtx,0,NULL,0);
printf("-------------------------------------------------\n");
struct SwsContext *img_convert_ctx;
img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
//------------------------------
//
while(av_read_frame(pFormatCtx, packet)>=0)
{
if(packet->stream_index==videoindex)
{
//HERE WE DECODE THE PACKET INTO THE FRAME
ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
if(ret < 0)
{
printf("Decode Error.\n");
return -1;
}
if(got_picture)
{
//THIS IS WHERE WE DO STH WITH THE FRAME WE JUST GOT FROM THE STREAM
//FREE AREA--START
//IN HERE YOU CAN WORK WITH THE FRAME OF THE PACKET.
write_video_frame(outFormatContextEncoded, &outVideoStream,packet);
//FREE AREA--END
sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);
SDL_LockYUVOverlay(bmp);
bmp->pixels[0]=pFrameYUV->data[0];
bmp->pixels[2]=pFrameYUV->data[1];
bmp->pixels[1]=pFrameYUV->data[2];
bmp->pitches[0]=pFrameYUV->linesize[0];
bmp->pitches[2]=pFrameYUV->linesize[1];
bmp->pitches[1]=pFrameYUV->linesize[2];
SDL_UnlockYUVOverlay(bmp);
rect.x = 0;
rect.y = 0;
rect.w = screen_w;
rect.h = screen_h;
SDL_DisplayYUVOverlay(bmp, &rect);
//Delay 40ms----WHY THIS DELAY????
SDL_Delay(40);
}
}
av_free_packet(packet);
}//THE LOOP TO PULL PACKETS FROM THE FORMAT CONTEXT ENDS HERE.
//AFTER THE WHILE LOOP WE DO SOME CLEANING
//av_read_pause(context);
av_write_trailer(outFormatContextEncoded);
close_stream(outFormatContextEncoded, &outVideoStream);
if (!(outFormatContextEncoded->flags & AVFMT_NOFILE))
/* Close the output file. */
avio_close(outFormatContextEncoded->pb);
/* free the stream */
avformat_free_context(outFormatContextEncoded);
//STOP DOING YOUR CLEANING
sws_freeContext(img_convert_ctx);
SDL_Quit();
av_free(out_buffer);
av_free(pFrameYUV);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
return 0;
}
/*
* encode one video frame and send it to the muxer
* return 1 when encoding is finished, 0 otherwise
*/
static int write_video_frame(AVFormatContext *oc, OutputStream *ost,AVPacket * pkt11)
{
int ret;
AVCodecContext *c;
AVFrame *frame;
int got_packet = 0;
c = ost->st->codec;
//DO NOT NEED THIS FRAME.
//frame = get_video_frame(ost);
if (oc->oformat->flags & AVFMT_RAWPICTURE) {
//IGNORE THIS FOR A MOMENT
/* a hack to avoid data copy with some raw video muxers */
AVPacket pkt;
av_init_packet(&pkt);
if (!frame)
return 1;
pkt.flags |= AV_PKT_FLAG_KEY;
pkt.stream_index = ost->st->index;
pkt.data = (uint8_t *)frame;
pkt.size = sizeof(AVPicture);
pkt.pts = pkt.dts = frame->pts;
av_packet_rescale_ts(&pkt, c->time_base, ost->st->time_base);
ret = av_interleaved_write_frame(oc, &pkt);
} else {
ret = write_frame(oc, &c->time_base, ost->st, pkt11);
}
if (ret < 0) {
fprintf(stderr, "Error while writing video frame: %s\n");
exit(1);
}
return 1;
} -
ffmpeg record screen and save video file to disk as .mpg
7 janvier 2015, par musimbateI want to record the screen of my pc (using gdigrab on my windows machine) and store the saved video file on my disk as an mp4 or mpg file .I have found an example piece of code that grabs the screen and shows it in an SDL window here :http://xwk.iteye.com/blog/2125720 (The code is on the bottom of the page and has an english version) and the ffmpeg muxing example https://ffmpeg.org/doxygen/trunk/muxing_8c-source.html seems to be able to help encode audio and video into a desired output video file.
I have tried to combine these two by having a format context for grabbing the screen (AVFormatContext *pFormatCtx ; in my code ) and a separate format context to write the desired video file (AVFormatContext *outFormatContextEncoded ;).Within the loop to read packets from the input stream( screen grab stream) I directly encode write packets to the output file as shown in my code.I have kept the SDL code so I can see what I am recording.Below is my code with my modified write_video_frame() function .
The code builds OK but the output video can’t be played by vlc. When I run the command
ffmpeg -i filename.mpg
I get this output
[mpeg @ 003fed20] probed stream 0 failed
[mpeg @ 003fed20] Stream #0: not enough frames to estimate rate; consider increasing probesize
[mpeg @ 003fed20] Could not find codec parameters for stream 0 (Video: none): unknown codec
Consider increasing the value for the 'analyzeduration' and 'probesize' options
karamage.mpg: could not find codec parameters
Input #0, mpeg, from 'karamage.mpg':
Duration: 19:30:09.25, start: 37545.438756, bitrate: 2 kb/s
Stream #0:0[0x1e0]: Video: none, 90k tbr, 90k tbn
At least one output file must be specifiedAm I doing something wrong here ? I am new to ffmpeg and any guidance on this is highly appreciated.Thank you for your time.
int main(int argc, char* argv[])
{
AVFormatContext *pFormatCtx;
int i, videoindex;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
av_register_all();
avformat_network_init();
//Localy defined structure.
OutputStream outVideoStream = { 0 };
const char *filename;
AVOutputFormat *outFormatEncoded;
AVFormatContext *outFormatContextEncoded;
AVCodec *videoCodec;
filename="karamage.mpg";
int ret1;
int have_video = 0, have_audio = 0;
int encode_video = 0, encode_audio = 0;
AVDictionary *opt = NULL;
//ASSIGN STH TO THE FORMAT CONTEXT.
pFormatCtx = avformat_alloc_context();
//
//Use this when opening a local file.
//char filepath[]="src01_480x272_22.h265";
//avformat_open_input(&pFormatCtx,filepath,NULL,NULL)
//Register Device
avdevice_register_all();
//Use gdigrab
AVDictionary* options = NULL;
//Set some options
//grabbing frame rate
//av_dict_set(&options,"framerate","5",0);
//The distance from the left edge of the screen or desktop
//av_dict_set(&options,"offset_x","20",0);
//The distance from the top edge of the screen or desktop
//av_dict_set(&options,"offset_y","40",0);
//Video frame size. The default is to capture the full screen
//av_dict_set(&options,"video_size","640x480",0);
AVInputFormat *ifmt=av_find_input_format("gdigrab");
if(avformat_open_input(&pFormatCtx,"desktop",ifmt,&options)!=0){
printf("Couldn't open input stream.\n");
return -1;
}
if(avformat_find_stream_info(pFormatCtx,NULL)<0)
{
printf("Couldn't find stream information.\n");
return -1;
}
videoindex=-1;
for(i=0; inb_streams; i++)
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
{
videoindex=i;
break;
}
if(videoindex==-1)
{
printf("Didn't find a video stream.\n");
return -1;
}
pCodecCtx=pFormatCtx->streams[videoindex]->codec;
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL)
{
printf("Codec not found.\n");
return -1;
}
if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)
{
printf("Could not open codec.\n");
return -1;
}
AVFrame *pFrame,*pFrameYUV;
pFrame=avcodec_alloc_frame();
pFrameYUV=avcodec_alloc_frame();
//PIX_FMT_YUV420P WHAT DOES THIS SAY ABOUT THE FORMAT??
uint8_t *out_buffer=(uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);
//<<<<<<<<<<<-------PREP WORK TO WRITE ENCODED VIDEO FILES-----
avformat_alloc_output_context2(&outFormatContextEncoded, NULL, NULL, filename);
if (!outFormatContextEncoded) {
printf("Could not deduce output format from file extension: using MPEG.\n");
avformat_alloc_output_context2(&outFormatContextEncoded, NULL, "mpeg", filename);
}
if (!outFormatContextEncoded)
return 1;
outFormatEncoded=outFormatContextEncoded->oformat;
//THIS CREATES THE STREAMS(AUDIO AND VIDEO) ADDED TO OUR OUTPUT STREAM
if (outFormatEncoded->video_codec != AV_CODEC_ID_NONE) {
//YOUR VIDEO AND AUDIO PROPS ARE SET HERE.
add_stream(&outVideoStream, outFormatContextEncoded, &videoCodec, outFormatEncoded->video_codec);
have_video = 1;
encode_video = 1;
}
// Now that all the parameters are set, we can open the audio and
// video codecs and allocate the necessary encode buffers.
if (have_video)
open_video(outFormatContextEncoded, videoCodec, &outVideoStream, opt);
av_dump_format(outFormatContextEncoded, 0, filename, 1);
/* open the output file, if needed */
if (!(outFormatEncoded->flags & AVFMT_NOFILE)) {
ret1 = avio_open(&outFormatContextEncoded->pb, filename, AVIO_FLAG_WRITE);
if (ret1 < 0) {
//fprintf(stderr, "Could not open '%s': %s\n", filename,
// av_err2str(ret));
fprintf(stderr, "Could not open your dumb file.\n");
return 1;
}
}
/* Write the stream header, if any. */
ret1 = avformat_write_header(outFormatContextEncoded, &opt);
if (ret1 < 0) {
//fprintf(stderr, "Error occurred when opening output file: %s\n",
// av_err2str(ret));
fprintf(stderr, "Error occurred when opening output file\n");
return 1;
}
//<<<<<<<<<<<-------PREP WORK TO WRITE ENCODED VIDEO FILES-----
//SDL----------------------------
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
printf( "Could not initialize SDL - %s\n", SDL_GetError());
return -1;
}
int screen_w=640,screen_h=360;
const SDL_VideoInfo *vi = SDL_GetVideoInfo();
//Half of the Desktop's width and height.
screen_w = vi->current_w/2;
screen_h = vi->current_h/2;
SDL_Surface *screen;
screen = SDL_SetVideoMode(screen_w, screen_h, 0,0);
if(!screen) {
printf("SDL: could not set video mode - exiting:%s\n",SDL_GetError());
return -1;
}
SDL_Overlay *bmp;
bmp = SDL_CreateYUVOverlay(pCodecCtx->width, pCodecCtx->height,SDL_YV12_OVERLAY, screen);
SDL_Rect rect;
//SDL End------------------------
int ret, got_picture;
AVPacket *packet=(AVPacket *)av_malloc(sizeof(AVPacket));
//TRY TO INIT THE PACKET HERE
av_init_packet(packet);
//Output Information-----------------------------
printf("File Information---------------------\n");
av_dump_format(pFormatCtx,0,NULL,0);
printf("-------------------------------------------------\n");
struct SwsContext *img_convert_ctx;
img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
//------------------------------
//
while(av_read_frame(pFormatCtx, packet)>=0)
{
if(packet->stream_index==videoindex)
{
//HERE WE DECODE THE PACKET INTO THE FRAME
ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
if(ret < 0)
{
printf("Decode Error.\n");
return -1;
}
if(got_picture)
{
//THIS IS WHERE WE DO STH WITH THE FRAME WE JUST GOT FROM THE STREAM
//FREE AREA--START
//IN HERE YOU CAN WORK WITH THE FRAME OF THE PACKET.
write_video_frame(outFormatContextEncoded, &outVideoStream,packet);
//FREE AREA--END
sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);
SDL_LockYUVOverlay(bmp);
bmp->pixels[0]=pFrameYUV->data[0];
bmp->pixels[2]=pFrameYUV->data[1];
bmp->pixels[1]=pFrameYUV->data[2];
bmp->pitches[0]=pFrameYUV->linesize[0];
bmp->pitches[2]=pFrameYUV->linesize[1];
bmp->pitches[1]=pFrameYUV->linesize[2];
SDL_UnlockYUVOverlay(bmp);
rect.x = 0;
rect.y = 0;
rect.w = screen_w;
rect.h = screen_h;
SDL_DisplayYUVOverlay(bmp, &rect);
//Delay 40ms----WHY THIS DELAY????
SDL_Delay(40);
}
}
av_free_packet(packet);
}//THE LOOP TO PULL PACKETS FROM THE FORMAT CONTEXT ENDS HERE.
//AFTER THE WHILE LOOP WE DO SOME CLEANING
//av_read_pause(context);
av_write_trailer(outFormatContextEncoded);
close_stream(outFormatContextEncoded, &outVideoStream);
if (!(outFormatContextEncoded->flags & AVFMT_NOFILE))
/* Close the output file. */
avio_close(outFormatContextEncoded->pb);
/* free the stream */
avformat_free_context(outFormatContextEncoded);
//STOP DOING YOUR CLEANING
sws_freeContext(img_convert_ctx);
SDL_Quit();
av_free(out_buffer);
av_free(pFrameYUV);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
return 0;
}
/*
* encode one video frame and send it to the muxer
* return 1 when encoding is finished, 0 otherwise
*/
static int write_video_frame(AVFormatContext *oc, OutputStream *ost,AVPacket * pkt11)
{
int ret;
AVCodecContext *c;
AVFrame *frame;
int got_packet = 0;
c = ost->st->codec;
//DO NOT NEED THIS FRAME.
//frame = get_video_frame(ost);
if (oc->oformat->flags & AVFMT_RAWPICTURE) {
//IGNORE THIS FOR A MOMENT
/* a hack to avoid data copy with some raw video muxers */
AVPacket pkt;
av_init_packet(&pkt);
if (!frame)
return 1;
pkt.flags |= AV_PKT_FLAG_KEY;
pkt.stream_index = ost->st->index;
pkt.data = (uint8_t *)frame;
pkt.size = sizeof(AVPicture);
pkt.pts = pkt.dts = frame->pts;
av_packet_rescale_ts(&pkt, c->time_base, ost->st->time_base);
ret = av_interleaved_write_frame(oc, &pkt);
} else {
ret = write_frame(oc, &c->time_base, ost->st, pkt11);
}
if (ret < 0) {
fprintf(stderr, "Error while writing video frame: %s\n");
exit(1);
}
return 1;
}