
Recherche avancée
Médias (3)
-
Exemple de boutons d’action pour une collection collaborative
27 février 2013, par
Mis à jour : Mars 2013
Langue : français
Type : Image
-
Exemple de boutons d’action pour une collection personnelle
27 février 2013, par
Mis à jour : Février 2013
Langue : English
Type : Image
-
Collections - Formulaire de création rapide
19 février 2013, par
Mis à jour : Février 2013
Langue : français
Type : Image
Autres articles (54)
-
Soumettre améliorations et plugins supplémentaires
10 avril 2011Si vous avez développé une nouvelle extension permettant d’ajouter une ou plusieurs fonctionnalités utiles à MediaSPIP, faites le nous savoir et son intégration dans la distribution officielle sera envisagée.
Vous pouvez utiliser la liste de discussion de développement afin de le faire savoir ou demander de l’aide quant à la réalisation de ce plugin. MediaSPIP étant basé sur SPIP, il est également possible d’utiliser le liste de discussion SPIP-zone de SPIP pour (...) -
Participer à sa traduction
10 avril 2011Vous pouvez nous aider à améliorer les locutions utilisées dans le logiciel ou à traduire celui-ci dans n’importe qu’elle nouvelle langue permettant sa diffusion à de nouvelles communautés linguistiques.
Pour ce faire, on utilise l’interface de traduction de SPIP où l’ensemble des modules de langue de MediaSPIP sont à disposition. ll vous suffit de vous inscrire sur la liste de discussion des traducteurs pour demander plus d’informations.
Actuellement MediaSPIP n’est disponible qu’en français et (...) -
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 (...)
Sur d’autres sites (4175)
-
FFMpeg undefined reference to get_buffer
14 juin 2012, par KevinI'm trying to upgrade the FFMpeg source used with one of our projects but get_buffer has gone away. I'm not 100% sure on which method to replace it with. Here are two contexts in which its used, any help is appreciated.
I look forward to hearing from you soon,
Thanks,
Kevincur_offset = avio_tell(pb);
if (!para->playctrl_info.read_end_flag && (0 == pkt->data_size)) {
rev_byte = get_buffer(pb, pbuf, para->max_raw_size);
if ((rev_byte > 0) && (cur_offset <= para->pFormatCtx->data_offset)) {
try_count = 0;
pkt->data_size = rev_byte;
para->read_size.total_bytes += rev_byte;
pkt->avpkt_newflag = 1;
pkt->avpkt_isvalid = 1;
do {
read_length = get_buffer(s->pb, data + 12, read_size);
if ((read_length <= 0) || (sync_flag == 1024)) {
if (read_length == AVERROR(EAGAIN)) {
continue;
} else {
FREE(data);
log_error("[%s]get data failed. ret=%d\n", __FUNCTION__, read_length);
return 0;
}
} else {
break;
}
} while (retry_get_data < am_p->playctrl_info.read_max_retry_cnt);
pkt = data; -
Problems with Streaming a Multicast RTSP Stream with Live555
16 juin 2014, par ALM865I am having trouble setting up a Multicast RTSP session using Live555. The examples included with Live555 are mostly irrelevant as they deal with reading in files and my code differs because it reads in encoded frames generated from a FFMPEG thread within my own program (no pipes, no saving to disk, it is genuinely passing pointers to memory that contain the encoded frames for Live555 to stream).
My Live555 project that uses a custom Server Media Subsession so that I can receive data from an FFMPEG thread within my program (instead of Live555’s default reading from a file, yuk !). This is a requirement of my program as it reads in a GigEVision stream in one thread, sends the decoded raw RGB packets to the FFMPEG thread, which then in turn sends the encoded frames off to Live555 for RTSP streaming.
For the life of me I can’t work out how to send the RTSP stream as multicast instead of unicast !
Just a note, my program works perfectly at the moment streaming Unicast, so there is nothing wrong with my Live555 implementation (before you go crazy picking out irrelevant errors !). I just need to know how to modify my existing code to stream Multicast instead of Unicast.
My program is way too big to upload and share so I’m just going to share the important bits :
Live_AnalysingServerMediaSubsession.h
#ifndef _ANALYSING_SERVER_MEDIA_SUBSESSION_HH
#define _ANALYSING_SERVER_MEDIA_SUBSESSION_HH
#include
#include "Live_AnalyserInput.h"
class AnalysingServerMediaSubsession: public OnDemandServerMediaSubsession {
public:
static AnalysingServerMediaSubsession*
createNew(UsageEnvironment& env, AnalyserInput& analyserInput, unsigned estimatedBitrate,
Boolean iFramesOnly = False,
double vshPeriod = 5.0
/* how often (in seconds) to inject a Video_Sequence_Header,
if one doesn't already appear in the stream */);
protected: // we're a virtual base class
AnalysingServerMediaSubsession(UsageEnvironment& env, AnalyserInput& AnalyserInput, unsigned estimatedBitrate, Boolean iFramesOnly, double vshPeriod);
virtual ~AnalysingServerMediaSubsession();
protected:
AnalyserInput& fAnalyserInput;
unsigned fEstimatedKbps;
private:
Boolean fIFramesOnly;
double fVSHPeriod;
// redefined virtual functions
virtual FramedSource* createNewStreamSource(unsigned clientSessionId, unsigned& estBitrate);
virtual RTPSink* createNewRTPSink(Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, FramedSource* inputSource);
};
#endifAnd "Live_AnalysingServerMediaSubsession.cpp"
#include "Live_AnalysingServerMediaSubsession.h"
#include
#include
#include
AnalysingServerMediaSubsession* AnalysingServerMediaSubsession::createNew(UsageEnvironment& env, AnalyserInput& wisInput, unsigned estimatedBitrate,
Boolean iFramesOnly,
double vshPeriod) {
return new AnalysingServerMediaSubsession(env, wisInput, estimatedBitrate,
iFramesOnly, vshPeriod);
}
AnalysingServerMediaSubsession
::AnalysingServerMediaSubsession(UsageEnvironment& env, AnalyserInput& analyserInput, unsigned estimatedBitrate, Boolean iFramesOnly, double vshPeriod)
: OnDemandServerMediaSubsession(env, True /*reuse the first source*/),
fAnalyserInput(analyserInput), fIFramesOnly(iFramesOnly), fVSHPeriod(vshPeriod) {
fEstimatedKbps = (estimatedBitrate + 500)/1000;
}
AnalysingServerMediaSubsession
::~AnalysingServerMediaSubsession() {
}
FramedSource* AnalysingServerMediaSubsession ::createNewStreamSource(unsigned /*clientSessionId*/, unsigned& estBitrate) {
estBitrate = fEstimatedKbps;
// Create a framer for the Video Elementary Stream:
//LOG_MSG("Create Net Stream Source [%d]", estBitrate);
return MPEG1or2VideoStreamDiscreteFramer::createNew(envir(), fAnalyserInput.videoSource());
}
RTPSink* AnalysingServerMediaSubsession ::createNewRTPSink(Groupsock* rtpGroupsock, unsigned char /*rtpPayloadTypeIfDynamic*/, FramedSource* /*inputSource*/) {
setVideoRTPSinkBufferSize();
/*
struct in_addr destinationAddress;
destinationAddress.s_addr = inet_addr("239.255.12.42");
rtpGroupsock->addDestination(destinationAddress,8888);
rtpGroupsock->multicastSendOnly();
*/
return MPEG1or2VideoRTPSink::createNew(envir(), rtpGroupsock);
}Live_AnalyserSouce.h
#ifndef _ANALYSER_SOURCE_HH
#define _ANALYSER_SOURCE_HH
#ifndef _FRAMED_SOURCE_HH
#include "FramedSource.hh"
#endif
class FFMPEG;
// The following class can be used to define specific encoder parameters
class AnalyserParameters {
public:
FFMPEG * Encoding_Source;
};
class AnalyserSource: public FramedSource {
public:
static AnalyserSource* createNew(UsageEnvironment& env, FFMPEG * E_Source);
static unsigned GetRefCount();
public:
static EventTriggerId eventTriggerId;
protected:
AnalyserSource(UsageEnvironment& env, FFMPEG * E_Source);
// called only by createNew(), or by subclass constructors
virtual ~AnalyserSource();
private:
// redefined virtual functions:
virtual void doGetNextFrame();
private:
static void deliverFrame0(void* clientData);
void deliverFrame();
private:
static unsigned referenceCount; // used to count how many instances of this class currently exist
FFMPEG * Encoding_Source;
unsigned int Last_Sent_Frame_ID;
};
#endifLive_AnalyserSource.cpp
#include "Live_AnalyserSource.h"
#include // for "gettimeofday()"
#include "FFMPEGClass.h"
AnalyserSource* AnalyserSource::createNew(UsageEnvironment& env, FFMPEG * E_Source) {
return new AnalyserSource(env, E_Source);
}
EventTriggerId AnalyserSource::eventTriggerId = 0;
unsigned AnalyserSource::referenceCount = 0;
AnalyserSource::AnalyserSource(UsageEnvironment& env, FFMPEG * E_Source) : FramedSource(env), Encoding_Source(E_Source) {
if (referenceCount == 0) {
// Any global initialization of the device would be done here:
}
++referenceCount;
// Any instance-specific initialization of the device would be done here:
Last_Sent_Frame_ID = 0;
/* register us with the Encoding thread so we'll get notices when new frame data turns up.. */
Encoding_Source->RegisterRTSP_Source(&(env.taskScheduler()), this);
// We arrange here for our "deliverFrame" member function to be called
// whenever the next frame of data becomes available from the device.
//
// If the device can be accessed as a readable socket, then one easy way to do this is using a call to
// envir().taskScheduler().turnOnBackgroundReadHandling( ... )
// (See examples of this call in the "liveMedia" directory.)
//
// If, however, the device *cannot* be accessed as a readable socket, then instead we can implement is using 'event triggers':
// Create an 'event trigger' for this device (if it hasn't already been done):
if (eventTriggerId == 0) {
eventTriggerId = envir().taskScheduler().createEventTrigger(deliverFrame0);
}
}
AnalyserSource::~AnalyserSource() {
// Any instance-specific 'destruction' (i.e., resetting) of the device would be done here:
/* de-register this source from the Encoding thread, since we no longer need notices.. */
Encoding_Source->Un_RegisterRTSP_Source(this);
--referenceCount;
if (referenceCount == 0) {
// Any global 'destruction' (i.e., resetting) of the device would be done here:
// Reclaim our 'event trigger'
envir().taskScheduler().deleteEventTrigger(eventTriggerId);
eventTriggerId = 0;
}
}
unsigned AnalyserSource::GetRefCount() {
return referenceCount;
}
void AnalyserSource::doGetNextFrame() {
// This function is called (by our 'downstream' object) when it asks for new data.
//LOG_MSG("Do Next Frame..");
// Note: If, for some reason, the source device stops being readable (e.g., it gets closed), then you do the following:
//if (0 /* the source stops being readable */ /*%%% TO BE WRITTEN %%%*/) {
unsigned int FrameID = Encoding_Source->GetFrameID();
if (FrameID == 0){
//LOG_MSG("No Data. Close");
handleClosure(this);
return;
}
// If a new frame of data is immediately available to be delivered, then do this now:
if (Last_Sent_Frame_ID != FrameID){
deliverFrame();
//DEBUG_MSG("Frame ID: %d",FrameID);
}
// No new data is immediately available to be delivered. We don't do anything more here.
// Instead, our event trigger must be called (e.g., from a separate thread) when new data becomes available.
}
void AnalyserSource::deliverFrame0(void* clientData) {
((AnalyserSource*)clientData)->deliverFrame();
}
void AnalyserSource::deliverFrame() {
if (!isCurrentlyAwaitingData()) return; // we're not ready for the data yet
static u_int8_t* newFrameDataStart;
static unsigned newFrameSize = 0;
/* get the data frame from the Encoding thread.. */
if (Encoding_Source->GetFrame(&newFrameDataStart, &newFrameSize, &Last_Sent_Frame_ID)){
if (newFrameDataStart!=NULL) {
/* This should never happen, but check anyway.. */
if (newFrameSize > fMaxSize) {
fFrameSize = fMaxSize;
fNumTruncatedBytes = newFrameSize - fMaxSize;
} else {
fFrameSize = newFrameSize;
}
gettimeofday(&fPresentationTime, NULL); // If you have a more accurate time - e.g., from an encoder - then use that instead.
// If the device is *not* a 'live source' (e.g., it comes instead from a file or buffer), then set "fDurationInMicroseconds" here.
/* move the data to be sent off.. */
memmove(fTo, newFrameDataStart, fFrameSize);
/* release the Mutex we had on the Frame's buffer.. */
Encoding_Source->ReleaseFrame();
}
else {
//AM Added, something bad happened
//ALTRACE("LIVE555: FRAME NULL\n");
fFrameSize=0;
fTo=NULL;
handleClosure(this);
}
}
else {
//LOG_MSG("Closing Connection due to Frame Error..");
handleClosure(this);
}
// After delivering the data, inform the reader that it is now available:
FramedSource::afterGetting(this);
}Live_AnalyserInput.cpp
#include "Live_AnalyserInput.h"
#include "Live_AnalyserSource.h"
////////// WISInput implementation //////////
AnalyserInput* AnalyserInput::createNew(UsageEnvironment& env, FFMPEG *Encoder) {
if (!fHaveInitialized) {
//if (!initialize(env)) return NULL;
fHaveInitialized = True;
}
return new AnalyserInput(env, Encoder);
}
FramedSource* AnalyserInput::videoSource() {
if (fOurVideoSource == NULL || AnalyserSource::GetRefCount() == 0) {
fOurVideoSource = AnalyserSource::createNew(envir(), m_Encoder);
}
return fOurVideoSource;
}
AnalyserInput::AnalyserInput(UsageEnvironment& env, FFMPEG *Encoder): Medium(env), m_Encoder(Encoder) {
}
AnalyserInput::~AnalyserInput() {
/* When we get destroyed, make sure our source is also destroyed.. */
if (fOurVideoSource != NULL && AnalyserSource::GetRefCount() != 0) {
AnalyserSource::handleClosure(fOurVideoSource);
}
}
Boolean AnalyserInput::fHaveInitialized = False;
int AnalyserInput::fOurVideoFileNo = -1;
FramedSource* AnalyserInput::fOurVideoSource = NULL;Live_AnalyserInput.h
#ifndef _ANALYSER_INPUT_HH
#define _ANALYSER_INPUT_HH
#include
#include "FFMPEGClass.h"
class AnalyserInput: public Medium {
public:
static AnalyserInput* createNew(UsageEnvironment& env, FFMPEG *Encoder);
FramedSource* videoSource();
private:
AnalyserInput(UsageEnvironment& env, FFMPEG *Encoder); // called only by createNew()
virtual ~AnalyserInput();
private:
friend class WISVideoOpenFileSource;
static Boolean fHaveInitialized;
static int fOurVideoFileNo;
static FramedSource* fOurVideoSource;
FFMPEG *m_Encoder;
};
// Functions to set the optimal buffer size for RTP sink objects.
// These should be called before each RTPSink is created.
#define VIDEO_MAX_FRAME_SIZE 300000
inline void setVideoRTPSinkBufferSize() { OutPacketBuffer::maxSize = VIDEO_MAX_FRAME_SIZE; }
#endifAnd finally the relevant code from my Live555 worker thread that starts the whole process :
Stop_RTSP_Loop=0;
// MediaSession *ms;
TaskScheduler *scheduler;
UsageEnvironment *env ;
// RTSPClient *rtsp;
// MediaSubsession *Video_Sub;
char RTSP_Address[1024];
RTSP_Address[0]=0x00;
if (m_Encoder == NULL){
//DEBUG_MSG("No Video Encoder registered for the RTSP Encoder");
return 0;
}
scheduler = BasicTaskScheduler::createNew();
env = BasicUsageEnvironment::createNew(*scheduler);
UserAuthenticationDatabase* authDB = NULL;
#ifdef ACCESS_CONTROL
// To implement client access control to the RTSP server, do the following:
if (m_Enable_Pass){
authDB = new UserAuthenticationDatabase;
authDB->addUserRecord(UserN, PassW);
}
////////// authDB = new UserAuthenticationDatabase;
////////// authDB->addUserRecord((char*)"Admin", (char*)"Admin"); // replace these with real strings
// Repeat the above with each <username>, <password> that you wish to allow
// access to the server.
#endif
// Create the RTSP server:
RTSPServer* rtspServer = RTSPServer::createNew(*env, 554, authDB);
ServerMediaSession* sms;
AnalyserInput* inputDevice;
if (rtspServer == NULL) {
TRACE("LIVE555: Failed to create RTSP server: %s\n", env->getResultMsg());
return 0;
}
else {
char const* descriptionString = "Session streamed by \"IMC Server\"";
// Initialize the WIS input device:
inputDevice = AnalyserInput::createNew(*env, m_Encoder);
if (inputDevice == NULL) {
TRACE("Live555: Failed to create WIS input device\n");
return 0;
}
else {
// A MPEG-1 or 2 video elementary stream:
/* Increase the buffer size so we can handle the high res stream.. */
OutPacketBuffer::maxSize = 300000;
// NOTE: This *must* be a Video Elementary Stream; not a Program Stream
sms = ServerMediaSession::createNew(*env, RTSP_Address, RTSP_Address, descriptionString);
//sms->addSubsession(MPEG1or2VideoFileServerMediaSubsession::createNew(*env, inputFileName, reuseFirstSource, iFramesOnly));
sms->addSubsession(AnalysingServerMediaSubsession::createNew(*env, *inputDevice, m_Encoder->Get_Bitrate()));
//sms->addSubsession(WISMPEG1or2VideoServerMediaSubsession::createNew(sms->envir(), inputDevice, videoBitrate));
rtspServer->addServerMediaSession(sms);
//announceStream(rtspServer, sms, streamName, inputFileName);
//LOG_MSG("Play this stream using the URL %s", rtspServer->rtspURL(sms));
}
}
Stop_RTSP_Loop=0;
for (;;)
{
/* The actual work is all carried out inside the LIVE555 Task scheduler */
env->taskScheduler().doEventLoop(&Stop_RTSP_Loop); // does not return
if (mStop) {
break;
}
}
Medium::close(rtspServer); // will also reclaim "sms" and its "ServerMediaSubsession"s
Medium::close(inputDevice);
</password></username> -
Recording video on Android using JavaCV (Updated 2014 02 17)
25 septembre 2014, 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.
(UPDATE) I have reverted my code and kept exactly like in the example, just changing imageWidth and imageHeight to 640x360.
Now I’m getting the video like this image :
http://bergmann.net.br/img/screenshot_video_error.pngHere is my code :
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.helpers.Helpers;
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;
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 = 480;
private int finalImageWidth = 640;
private int finalImageHeight = 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 = 1280;
private final int live_height = 960;
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(finalImageWidth, finalImageHeight,
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, finalImageWidth,
finalImageHeight, 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) {
// yuvIplimage.getByteBuffer().put(data);
final int startY = 640 * (480 - 360) / 2;
final int lenY = 640 * 360;
yuvIplimage.getByteBuffer().put(data, startY, lenY);
final int startVU = 640 * 480 + 320 * 2 * (240 - 180) / 2;
final int lenVU = 320 * 180 * 2;
yuvIplimage.getByteBuffer().put(data, startVU, lenVU);
Log.v(LOG_TAG, "Writing Frame");
try {
long t = 1000 * (System.currentTimeMillis() - startTime);
if (t > recorder.getTimestamp()) {
recorder.setTimestamp(t);
}
recorder.record(yuvIplimage);
} 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");
}
}
}