
Recherche avancée
Autres articles (13)
-
Emballe médias : à quoi cela sert ?
4 février 2011, parCe plugin vise à gérer des sites de mise en ligne de documents de tous types.
Il crée des "médias", à savoir : un "média" est un article au sens SPIP créé automatiquement lors du téléversement d’un document qu’il soit audio, vidéo, image ou textuel ; un seul document ne peut être lié à un article dit "média" ; -
Déploiements possibles
31 janvier 2010, parDeux types de déploiements sont envisageable dépendant de deux aspects : La méthode d’installation envisagée (en standalone ou en ferme) ; Le nombre d’encodages journaliers et la fréquentation envisagés ;
L’encodage de vidéos est un processus lourd consommant énormément de ressources système (CPU et RAM), il est nécessaire de prendre tout cela en considération. Ce système n’est donc possible que sur un ou plusieurs serveurs dédiés.
Version mono serveur
La version mono serveur consiste à n’utiliser qu’une (...) -
Gestion des droits de création et d’édition des objets
8 février 2011, parPar défaut, beaucoup de fonctionnalités sont limitées aux administrateurs mais restent configurables indépendamment pour modifier leur statut minimal d’utilisation notamment : la rédaction de contenus sur le site modifiables dans la gestion des templates de formulaires ; l’ajout de notes aux articles ; l’ajout de légendes et d’annotations sur les images ;
Sur d’autres sites (3756)
-
Revision 345fbfef06 : vp9 mt decode : reorder tile decode reorder the tiles based on size and their pr
6 décembre 2013, par James ZernChanged Paths :
Modify /vp9/decoder/vp9_decodeframe.c
vp9 mt decode : reorder tile decodereorder the tiles based on size and their presumed complexity. this
minimizes the cases where the main thread is waiting on a worker to
complete.Change-Id : Ie80642c6a1d64ece884f41683d23a3708ab38e0c
-
Recording video on Android using JavaCV
11 décembre 2013, par Fabio BergmannI'm trying to record a video in Android using the JavaCV lib.
I need to record the video in 640x360.I have installed everything as described in README.txt file and I followed the example as below :
https://code.google.com/p/javacv/source/browse/samples/RecordActivity.java
In this example, the video size is this :
private int imageWidth = 320 ;
private int imageHeight = 240 ;In my case, I need to record a video in 640x360 H.264.
But, or I get an exception or the video records with no correct image.I think that the fix is arround a correct combination on :
yuvIplimage = IplImage.create(imageWidth, imageHeight, IPL_DEPTH_8S, 2) ;
changing the depth and :
recorder.record(yuvIplimage, AV_PIX_FMT_VDPAU_H264) ;
the pixel format.Here is my code :
import static com.googlecode.javacv.cpp.avutil.AV_PIX_FMT_NONE;
import static com.googlecode.javacv.cpp.opencv_core.IPL_DEPTH_8U;
import java.io.IOException;
import java.nio.ShortBuffer;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.autosonvideo.logic.CameraHelpers;
import com.googlecode.javacv.FFmpegFrameRecorder;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class FFmpegRecordActivity extends Activity implements OnClickListener {
private final static String CLASS_LABEL = "RecordActivity";
private final static String LOG_TAG = CLASS_LABEL;
private PowerManager.WakeLock mWakeLock;
private String ffmpeg_link = "/mnt/sdcard/stream.flv";
long startTime = 0;
boolean recording = false;
private volatile FFmpegFrameRecorder recorder;
private boolean isPreviewOn = false;
private int sampleAudioRateInHz = 44100;
private int imageWidth = 640;
private int imageHeight = 360;
private int frameRate = 30;
/* audio data getting thread */
private AudioRecord audioRecord;
private AudioRecordRunnable audioRecordRunnable;
private Thread audioThread;
volatile boolean runAudioThread = true;
/* video data getting thread */
private Camera cameraDevice;
private CameraView cameraView;
private IplImage yuvIplimage = null;
/* layout setting */
private final int bg_screen_bx = 232;
private final int bg_screen_by = 128;
private final int bg_screen_width = 700;
private final int bg_screen_height = 500;
private final int bg_width = 1123;
private final int bg_height = 715;
private final int live_width = 640;
private final int live_height = 360;
private int screenWidth, screenHeight;
private Button btnRecorderControl;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.main);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
CLASS_LABEL);
mWakeLock.acquire();
initLayout();
initRecorder();
}
@Override
protected void onResume() {
super.onResume();
if (mWakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
CLASS_LABEL);
mWakeLock.acquire();
}
}
@Override
protected void onPause() {
super.onPause();
if (mWakeLock != null) {
mWakeLock.release();
mWakeLock = null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
recording = false;
if (cameraView != null) {
cameraView.stopPreview();
cameraDevice.release();
cameraDevice = null;
}
if (mWakeLock != null) {
mWakeLock.release();
mWakeLock = null;
}
}
private void initLayout() {
/* get size of screen */
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
screenWidth = display.getWidth();
screenHeight = display.getHeight();
RelativeLayout.LayoutParams layoutParam = null;
LayoutInflater myInflate = null;
myInflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout topLayout = new RelativeLayout(this);
setContentView(topLayout);
LinearLayout preViewLayout = (LinearLayout) myInflate.inflate(
R.layout.main, null);
layoutParam = new RelativeLayout.LayoutParams(screenWidth, screenHeight);
topLayout.addView(preViewLayout, layoutParam);
/* add control button: start and stop */
btnRecorderControl = (Button) findViewById(R.id.recorder_control);
btnRecorderControl.setText("Start");
btnRecorderControl.setOnClickListener(this);
/* add camera view */
int display_width_d = (int) (1.0 * bg_screen_width * screenWidth / bg_width);
int display_height_d = (int) (1.0 * bg_screen_height * screenHeight / bg_height);
int prev_rw, prev_rh;
if (1.0 * display_width_d / display_height_d > 1.0 * live_width
/ live_height) {
prev_rh = display_height_d;
prev_rw = (int) (1.0 * display_height_d * live_width / live_height);
} else {
prev_rw = display_width_d;
prev_rh = (int) (1.0 * display_width_d * live_height / live_width);
}
layoutParam = new RelativeLayout.LayoutParams(prev_rw, prev_rh);
layoutParam.topMargin = (int) (1.0 * bg_screen_by * screenHeight / bg_height);
layoutParam.leftMargin = (int) (1.0 * bg_screen_bx * screenWidth / bg_width);
cameraDevice = Camera.open();
Log.i(LOG_TAG, "cameara open");
cameraView = new CameraView(this, cameraDevice);
topLayout.addView(cameraView, layoutParam);
Log.i(LOG_TAG, "cameara preview start: OK");
}
// ---------------------------------------
// initialize ffmpeg_recorder
// ---------------------------------------
private void initRecorder() {
Log.w(LOG_TAG, "init recorder");
if (yuvIplimage == null) {
yuvIplimage = IplImage.create(imageWidth, imageHeight,
IPL_DEPTH_8U, 2);
Log.i(LOG_TAG, "create yuvIplimage");
}
ffmpeg_link = CameraHelpers.getOutputMediaFile(
CameraHelpers.MEDIA_TYPE_VIDEO).toString();
Log.i(LOG_TAG, "ffmpeg_url: " + ffmpeg_link);
recorder = new FFmpegFrameRecorder(ffmpeg_link, imageWidth,
imageHeight, 1);
recorder.setFormat("mp4");
recorder.setSampleRate(sampleAudioRateInHz);
// Set in the surface changed method
recorder.setFrameRate(frameRate);
Log.i(LOG_TAG, "recorder initialize success");
audioRecordRunnable = new AudioRecordRunnable();
audioThread = new Thread(audioRecordRunnable);
}
public void startRecording() {
try {
recorder.start();
startTime = System.currentTimeMillis();
recording = true;
audioThread.start();
} catch (FFmpegFrameRecorder.Exception e) {
e.printStackTrace();
}
}
public void stopRecording() {
runAudioThread = false;
if (recorder != null && recording) {
recording = false;
Log.v(LOG_TAG,
"Finishing recording, calling stop and release on recorder");
try {
recorder.stop();
recorder.release();
} catch (FFmpegFrameRecorder.Exception e) {
e.printStackTrace();
}
recorder = null;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (recording) {
stopRecording();
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
// ---------------------------------------------
// audio thread, gets and encodes audio data
// ---------------------------------------------
class AudioRecordRunnable implements Runnable {
@Override
public void run() {
android.os.Process
.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
// Audio
int bufferSize;
short[] audioData;
int bufferReadResult;
bufferSize = AudioRecord
.getMinBufferSize(sampleAudioRateInHz,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
sampleAudioRateInHz, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize);
audioData = new short[bufferSize];
Log.d(LOG_TAG, "audioRecord.startRecording()");
audioRecord.startRecording();
/* ffmpeg_audio encoding loop */
while (runAudioThread) {
// Log.v(LOG_TAG,"recording? " + recording);
bufferReadResult = audioRecord.read(audioData, 0,
audioData.length);
if (bufferReadResult > 0) {
// Log.v(LOG_TAG, "bufferReadResult: " + bufferReadResult);
// If "recording" isn't true when start this thread, it
// never get's set according to this if statement...!!!
// Why? Good question...
if (recording) {
try {
recorder.record(ShortBuffer.wrap(audioData, 0,
bufferReadResult));
// Log.v(LOG_TAG,"recording " + 1024*i + " to " +
// 1024*i+1024);
} catch (FFmpegFrameRecorder.Exception e) {
Log.v(LOG_TAG, e.getMessage());
e.printStackTrace();
}
}
}
}
Log.v(LOG_TAG, "AudioThread Finished, release audioRecord");
/* encoding finish, release recorder */
if (audioRecord != null) {
audioRecord.stop();
audioRecord.release();
audioRecord = null;
Log.v(LOG_TAG, "audioRecord released");
}
}
}
// ---------------------------------------------
// camera thread, gets and encodes video data
// ---------------------------------------------
class CameraView extends SurfaceView implements SurfaceHolder.Callback,
PreviewCallback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraView(Context context, Camera camera) {
super(context);
Log.w("camera", "camera view");
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(CameraView.this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mCamera.setPreviewCallback(CameraView.this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
stopPreview();
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.v(LOG_TAG, "Setting imageWidth: " + imageWidth
+ " imageHeight: " + imageHeight + " frameRate: "
+ frameRate);
Camera.Parameters camParams = mCamera.getParameters();
camParams.setPreviewSize(imageWidth, imageHeight);
Log.v(LOG_TAG,
"Preview Framerate: " + camParams.getPreviewFrameRate());
camParams.setPreviewFrameRate(frameRate);
mCamera.setParameters(camParams);
startPreview();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
try {
mHolder.addCallback(null);
mCamera.setPreviewCallback(null);
} catch (RuntimeException e) {
// The camera has probably just been released, ignore.
}
}
public void startPreview() {
if (!isPreviewOn && mCamera != null) {
isPreviewOn = true;
mCamera.startPreview();
}
}
public void stopPreview() {
if (isPreviewOn && mCamera != null) {
isPreviewOn = false;
mCamera.stopPreview();
}
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
/* get video data */
if (yuvIplimage != null && recording) {
int cap = yuvIplimage.getByteBuffer().capacity();
int dataLen = data.length;
Log.d("FFmpeg", "cap: " + cap + " data: " + dataLen);
yuvIplimage.getByteBuffer().put(data);
Log.v(LOG_TAG, "Writing Frame");
try {
long t = 1000 * (System.currentTimeMillis() - startTime);
if (t > recorder.getTimestamp()) {
recorder.setTimestamp(t);
}
recorder.record(yuvIplimage, AV_PIX_FMT_NONE);
} catch (FFmpegFrameRecorder.Exception e) {
Log.v(LOG_TAG, e.getMessage());
e.printStackTrace();
}
}
}
}
@Override
public void onClick(View v) {
if (!recording) {
startRecording();
Log.w(LOG_TAG, "Start Button Pushed");
btnRecorderControl.setText("Stop");
} else {
// This will trigger the audio recording loop to stop and then set
// isRecorderStart = false;
stopRecording();
Log.w(LOG_TAG, "Stop Button Pushed");
btnRecorderControl.setText("Start");
}
}
}Thanks in advance !
-
FFMPEG audio transcoding using libav* libraries
10 février 2014, par vinvinodI am writing an audio transcoding application using ffmpeg libraries.
Here is my code/*
* File: main.cpp
* Author: vinod
* Compile with "g++ -std=c++11 -o audiotranscode main.cpp -lavformat -lavcodec -lavutil -lavfilter"
*
*/
#if !defined PRId64 || PRI_MACROS_BROKEN
#undef PRId64
#define PRId64 "lld"
#endif
#define __STDC_FORMAT_MACROS
#ifdef __cplusplus
extern "C" {
#endif
#include
#include
#include <sys></sys>types.h>
#include
#include <libavutil></libavutil>imgutils.h>
#include <libavutil></libavutil>samplefmt.h>
#include <libavutil></libavutil>frame.h>
#include <libavutil></libavutil>timestamp.h>
#include <libavformat></libavformat>avformat.h>
#include <libavfilter></libavfilter>avfilter.h>
#include <libavfilter></libavfilter>buffersrc.h>
#include <libavfilter></libavfilter>buffersink.h>
#include <libswscale></libswscale>swscale.h>
#include <libavutil></libavutil>opt.h>
#ifdef __cplusplus
}
#endif
#include <iostream>
using namespace std;
int select_stream, got_frame, got_packet;
AVFormatContext *in_fmt_ctx = NULL, *out_fmt_ctx = NULL;
AVCodec *dec_codec = NULL, * enc_codec = NULL;
AVStream *audio_st = NULL;
AVCodecContext *enc_ctx = NULL, *dec_ctx = NULL;
AVFrame *pFrame = NULL, * pFrameFiltered = NULL;
AVFilterGraph *filter_graph = NULL;
AVFilterContext *buffersrc_ctx = NULL;
AVFilterContext *buffersink_ctx = NULL;
AVPacket packet;
string inFileName = "/home/vinod/vinod/Media/univac.webm";
string outFileName = "audio_extracted.m4a";
int target_bit_rate = 128000,
sample_rate = 22050,
channels = 1;
AVSampleFormat sample_fmt = AV_SAMPLE_FMT_S16;
string filter_description = "aresample=22050,aformat=sample_fmts=s16:channel_layouts=mono";
int log_averror(int errcode)
{
char *errbuf = (char *) calloc(AV_ERROR_MAX_STRING_SIZE, sizeof(char));
av_strerror(errcode, errbuf, AV_ERROR_MAX_STRING_SIZE);
std::cout << "Error - " << errbuf << std::endl;
delete [] errbuf;
return -1;
}
/**
* Initialize conversion filter */
int initialize_audio_filter()
{
char args[512];
int ret;
AVFilter *buffersrc = avfilter_get_by_name("abuffer");
AVFilter *buffersink = avfilter_get_by_name("abuffersink");
AVFilterInOut *outputs = avfilter_inout_alloc();
AVFilterInOut *inputs = avfilter_inout_alloc();
filter_graph = avfilter_graph_alloc();
const enum AVSampleFormat out_sample_fmts[] = {sample_fmt, AV_SAMPLE_FMT_NONE};
const int64_t out_channel_layouts[] = {av_get_default_channel_layout(out_fmt_ctx -> streams[0] -> codec -> channels), -1};
const int out_sample_rates[] = {out_fmt_ctx -> streams[0] -> codec -> sample_rate, -1};
if (!dec_ctx->channel_layout)
dec_ctx->channel_layout = av_get_default_channel_layout(dec_ctx->channels);
snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%" PRIx64,
in_fmt_ctx -> streams[select_stream] -> time_base.num, in_fmt_ctx -> streams[select_stream] -> time_base.den,
dec_ctx->sample_rate,
av_get_sample_fmt_name(dec_ctx->sample_fmt),
dec_ctx->channel_layout);
ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in", args, NULL, filter_graph);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
return -1;
}
ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out", NULL, NULL, filter_graph);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
return ret;
}
ret = av_opt_set_int_list(buffersink_ctx, "sample_fmts", out_sample_fmts, -1,
AV_OPT_SEARCH_CHILDREN);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n");
return ret;
}
ret = av_opt_set_int_list(buffersink_ctx, "channel_layouts", out_channel_layouts, -1,
AV_OPT_SEARCH_CHILDREN);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n");
return ret;
}
ret = av_opt_set_int_list(buffersink_ctx, "sample_rates", out_sample_rates, -1,
AV_OPT_SEARCH_CHILDREN);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n");
return ret;
}
/* Endpoints for the filter graph. */
outputs -> name = av_strdup("in");
outputs -> filter_ctx = buffersrc_ctx;
outputs -> pad_idx = 0;
outputs -> next = NULL;
/* Endpoints for the filter graph. */
inputs -> name = av_strdup("out");
inputs -> filter_ctx = buffersink_ctx;
inputs -> pad_idx = 0;
inputs -> next = NULL;
string filter_desc = filter_description;
if ((ret = avfilter_graph_parse_ptr(filter_graph, filter_desc.c_str(), &inputs, &outputs, NULL)) < 0) {
log_averror(ret);
exit(1);
}
if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0) {
log_averror(ret);
exit(1);
}
/* Print summary of the sink buffer
* Note: args buffer is reused to store channel layout string */
AVFilterLink *outlink = buffersink_ctx->inputs[0];
av_get_channel_layout_string(args, sizeof(args), -1, outlink->channel_layout);
av_log(NULL, AV_LOG_INFO, "Output: srate:%dHz fmt:%s chlayout:%s\n",
(int) outlink->sample_rate,
(char *) av_x_if_null(av_get_sample_fmt_name((AVSampleFormat) outlink->format), "?"),
args);
return 0;
}
/*
*
*/
int main(int argc, char **argv)
{
int ret;
cout << "Hello World" << endl;
printf("abcd");
avcodec_register_all();
av_register_all();
avfilter_register_all();
/* open input file, and allocate format context */
if (avformat_open_input(&in_fmt_ctx, inFileName.c_str(), NULL, NULL) < 0) {
std::cout << "error opening input file - " << inFileName << std::endl;
return -1;
}
/* retrieve stream information */
if (avformat_find_stream_info(in_fmt_ctx, NULL) < 0) {
std::cerr << "Could not find stream information in the input file " << inFileName << std::endl;
}
/* Dump format details */
printf("\n ---------------------------------------------------------------------- \n");
av_dump_format(in_fmt_ctx, 0, inFileName.c_str(), 0);
printf("\n ---------------------------------------------------------------------- \n");
/* Choose a audio stream */
select_stream = av_find_best_stream(in_fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &dec_codec, 0);
if (select_stream == AVERROR_STREAM_NOT_FOUND) {
std::cerr << "No audio stream found" << std::endl;
return -1;
}
if (select_stream == AVERROR_DECODER_NOT_FOUND) {
std::cerr << "No suitable decoder found" << std::endl;
return -1;
}
dec_ctx = in_fmt_ctx -> streams[ select_stream] -> codec;
av_opt_set_int(dec_ctx, "refcounted_frames", 1, 0);
/* init the audio decoder */
if ((ret = avcodec_open2(dec_ctx, dec_codec, NULL)) < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot open audio decoder\n");
return ret;
}
/* allocate output context */
ret = avformat_alloc_output_context2(&out_fmt_ctx, NULL, NULL,
outFileName.c_str());
if (ret < 0) {
std::cerr << "Could not create output context for the file " << outFileName << std::endl;
return -1;
}
/* find the encoder */
enum AVCodecID codec_id = out_fmt_ctx -> oformat -> audio_codec;
enc_codec = avcodec_find_encoder(codec_id);
if (!(enc_codec)) {
std::cerr << "Could not find encoder for - " << avcodec_get_name(codec_id) << std::endl;
return -1;
}
/* add a new stream */
audio_st = avformat_new_stream(out_fmt_ctx, enc_codec);
if (!audio_st) {
std::cerr << "Could not add audio stream - " << std::endl;
}
/* Initialise audio codec */
audio_st -> id = out_fmt_ctx -> nb_streams - 1;
enc_ctx = audio_st -> codec;
enc_ctx -> codec_id = codec_id;
enc_ctx -> codec_type = AVMEDIA_TYPE_AUDIO;
enc_ctx -> bit_rate = target_bit_rate;
enc_ctx -> sample_rate = sample_rate;
enc_ctx -> sample_fmt = sample_fmt;
enc_ctx -> channels = channels;
enc_ctx -> channel_layout = av_get_default_channel_layout(enc_ctx -> channels);
/* Some formats want stream headers to be separate. */
if (out_fmt_ctx -> oformat -> flags & AVFMT_GLOBALHEADER) {
enc_ctx -> flags |= CODEC_FLAG_GLOBAL_HEADER;
}
ret = avcodec_open2(out_fmt_ctx -> streams[0] -> codec, enc_codec, NULL);
if (ret < 0) {
std::cerr << "Could not create codec context for the file " << outFileName << std::endl;
return -1;
}
/* Initialize filter */
initialize_audio_filter();
if (!(out_fmt_ctx -> oformat -> flags & AVFMT_NOFILE)) {
int ret = avio_open(& out_fmt_ctx -> pb, outFileName.c_str(),
AVIO_FLAG_WRITE);
if (ret < 0) {
log_averror(ret);
return -1;
}
}
/* Write header */
if (avformat_write_header(out_fmt_ctx, NULL) < 0) {
if (ret < 0) {
log_averror(ret);
return -1;
}
}
/* Allocate frame */
pFrame = av_frame_alloc();
if (!pFrame) {
std::cerr << "Could not allocate frame\n";
return -1;
}
pFrameFiltered = av_frame_alloc();
if (!pFrameFiltered) {
std::cerr << "Could not allocate frame\n";
return -1;
}
av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;
/* Read packet from the stream */
while (av_read_frame(in_fmt_ctx, &packet) >= 0) {
if (packet.stream_index == select_stream) {
avcodec_get_frame_defaults(pFrame);
ret = avcodec_decode_audio4(dec_ctx, pFrame, &got_frame, &packet);
if (ret < 0) {
log_averror(ret);
return ret;
}
printf("Decoded packet pts : %ld ", packet.pts);
printf("Frame Best Effor pts : %ld \n", pFrame->best_effort_timestamp);
/* Set frame pts */
pFrame -> pts = av_frame_get_best_effort_timestamp(pFrame);
if (got_frame) {
/* push the decoded frame into the filtergraph */
ret = av_buffersrc_add_frame_flags(buffersrc_ctx, pFrame, AV_BUFFERSRC_FLAG_KEEP_REF);
if (ret < 0) {
log_averror(ret);
return ret;
}
/* pull filtered frames from the filtergraph */
while (1) {
ret = av_buffersink_get_frame(buffersink_ctx, pFrameFiltered);
if ((ret == AVERROR(EAGAIN)) || (ret == AVERROR_EOF)) {
break;
}
if (ret < 0) {
printf("Error while getting filtered frames from filtergraph\n");
log_averror(ret);
return -1;
}
/* Initialize the packets */
AVPacket encodedPacket = {0};
av_init_packet(&encodedPacket);
ret = avcodec_encode_audio2(out_fmt_ctx -> streams[0] -> codec, &encodedPacket, pFrameFiltered, &got_packet);
if (!ret && got_packet && encodedPacket.size) {
/* Set correct pts and dts */
if (encodedPacket.pts != AV_NOPTS_VALUE) {
encodedPacket.pts = av_rescale_q(encodedPacket.pts, buffersink_ctx -> inputs[0] -> time_base,
out_fmt_ctx -> streams[0] -> time_base);
}
if (encodedPacket.dts != AV_NOPTS_VALUE) {
encodedPacket.dts = av_rescale_q(encodedPacket.dts, buffersink_ctx -> inputs[0] -> time_base,
out_fmt_ctx -> streams[0] -> time_base);
}
printf("Encoded packet pts %ld\n", encodedPacket.pts);
/* Write the compressed frame to the media file. */
ret = av_interleaved_write_frame(out_fmt_ctx, &encodedPacket);
if (ret < 0) {
log_averror(ret);
return -1;
}
} else if (ret < 0) {
log_averror(ret);
return -1;
}
av_frame_unref(pFrameFiltered);
}
av_frame_unref(pFrame);
}
}
}
/* Flush delayed frames from encoder*/
got_packet=1;
while (got_packet) {
AVPacket encodedPacket = {0};
av_init_packet(&encodedPacket);
ret = avcodec_encode_audio2(out_fmt_ctx -> streams[0] -> codec, &encodedPacket, NULL, &got_packet);
if (!ret && got_packet && encodedPacket.size) {
/* Set correct pts and dts */
if (encodedPacket.pts != AV_NOPTS_VALUE) {
encodedPacket.pts = av_rescale_q(encodedPacket.pts, buffersink_ctx -> inputs[0] -> time_base,
out_fmt_ctx -> streams[0] -> time_base);
}
if (encodedPacket.dts != AV_NOPTS_VALUE) {
encodedPacket.dts = av_rescale_q(encodedPacket.dts, buffersink_ctx -> inputs[0] -> time_base,
out_fmt_ctx -> streams[0] -> time_base);
}
printf("Encoded packet pts %ld\n", encodedPacket.pts);
/* Write the compressed frame to the media file. */
ret = av_interleaved_write_frame(out_fmt_ctx, &encodedPacket);
if (ret < 0) {
log_averror(ret);
return -1;
}
} else if (ret < 0) {
log_averror(ret);
return -1;
}
}
/* Write Trailer */
av_write_trailer(out_fmt_ctx);
avfilter_graph_free(&filter_graph);
if (dec_ctx)
avcodec_close(dec_ctx);
avformat_close_input(&in_fmt_ctx);
av_frame_free(&pFrame);
av_frame_free(&pFrameFiltered);
if (!(out_fmt_ctx -> oformat -> flags & AVFMT_NOFILE))
avio_close(out_fmt_ctx -> pb);
avcodec_close(out_fmt_ctx->streams[0]->codec);
avformat_free_context(out_fmt_ctx);
return 0;
}
</iostream>The audio file after transcoding is same duration as the input. But its completely noisy. Can somebody tell me what I am doing wrong here !