bool AbstractFFMpegLoader::open(qint64 &position) {
	if (!AudioPlayerLoader::openFile()) {
		return false;
	}

	int res = 0;
	char err[AV_ERROR_MAX_STRING_SIZE] = { 0 };

	ioBuffer = (uchar*)av_malloc(AVBlockSize);
	if (!_data.isEmpty()) {
		ioContext = avio_alloc_context(ioBuffer, AVBlockSize, 0, reinterpret_cast<void*>(this), &AbstractFFMpegLoader::_read_data, 0, &AbstractFFMpegLoader::_seek_data);
	} else if (!_bytes.empty()) {
		ioContext = avio_alloc_context(ioBuffer, AVBlockSize, 0, reinterpret_cast<void*>(this), &AbstractFFMpegLoader::_read_bytes, 0, &AbstractFFMpegLoader::_seek_bytes);
	} else {
		ioContext = avio_alloc_context(ioBuffer, AVBlockSize, 0, reinterpret_cast<void*>(this), &AbstractFFMpegLoader::_read_file, 0, &AbstractFFMpegLoader::_seek_file);
	}
	fmtContext = avformat_alloc_context();
	if (!fmtContext) {
		DEBUG_LOG(("Audio Read Error: Unable to avformat_alloc_context for file '%1', data size '%2'").arg(_file.name()).arg(_data.size()));
		return false;
	}
	fmtContext->pb = ioContext;

	if ((res = avformat_open_input(&fmtContext, 0, 0, 0)) < 0) {
		ioBuffer = 0;

		DEBUG_LOG(("Audio Read Error: Unable to avformat_open_input for file '%1', data size '%2', error %3, %4").arg(_file.name()).arg(_data.size()).arg(res).arg(av_make_error_string(err, sizeof(err), res)));
		return false;
	}
	_opened = true;

	if ((res = avformat_find_stream_info(fmtContext, 0)) < 0) {
		DEBUG_LOG(("Audio Read Error: Unable to avformat_find_stream_info for file '%1', data size '%2', error %3, %4").arg(_file.name()).arg(_data.size()).arg(res).arg(av_make_error_string(err, sizeof(err), res)));
		return false;
	}

	streamId = av_find_best_stream(fmtContext, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
	if (streamId < 0) {
		LOG(("Audio Error: Unable to av_find_best_stream for file '%1', data size '%2', error %3, %4").arg(_file.name()).arg(_data.size()).arg(streamId).arg(av_make_error_string(err, sizeof(err), streamId)));
		return false;
	}

	_samplesFrequency = fmtContext->streams[streamId]->codecpar->sample_rate;
	if (fmtContext->streams[streamId]->duration == AV_NOPTS_VALUE) {
		_samplesCount = (fmtContext->duration * _samplesFrequency) / AV_TIME_BASE;
	} else {
		_samplesCount = (fmtContext->streams[streamId]->duration * _samplesFrequency * fmtContext->streams[streamId]->time_base.num) / fmtContext->streams[streamId]->time_base.den;
	}

	return true;
}
Example #2
0
void VideoDecoder::loadFile(FillFileBufferFunc func, void* funcData, CleanupFunc cleanupFunc, VideoBufferInfo* bufferInfo) {
    if(fileLoaded) {
        logError("[VideoPlayer::loadFile] Tried to load a new file. Ignoring...\n");
        return;
    }

    if(func == NULL) {
        logError("[VideoPlayer::loadFile] Invalid arguments supplied!\n");
        throw std::invalid_argument("FillFileBufferFunc should be a valid function");
    }

    fillFileBufferFunc = func;
    customFileBufferFuncData = funcData;
    this->cleanupFunc = cleanupFunc;

    avioBuffer = (u_int8_t*)av_malloc(CUSTOMIO_BUFFER_SIZE);
    avioContext = avio_alloc_context(avioBuffer, CUSTOMIO_BUFFER_SIZE, 0, (void*)this, &readFunction, NULL, NULL);

    formatContext = avformat_alloc_context();
    formatContext->pb = avioContext;

    int err = avformat_open_input(&formatContext, "dummyFileName", NULL, NULL);if(err < 0) {
        char error[1024];
        av_strerror(err, error, 1024);
        logError("[VideoPlayer::loadFile] Error opening file: %s\n", error);
        throw std::runtime_error("Could not open file!");
    }
    loadContainer(bufferInfo);
}
Example #3
0
FFMPEG* EXPORT ffmpegOpenEx (void* handle, int seekable, int bufsize,  int(*read)(void*,void*,int),  long long(*seek)(void*,long long,int),  void(*close)(void*)  ) {
void* buf = av_malloc(bufsize);
if (!buf) return NULL;
AVFormatContext* fmtctx = avformat_alloc_context();
if (!fmtctx) return NULL;
AVIOContext* io = avio_alloc_context(buf, bufsize, 0, handle, read, NULL, seek);
if (!io) return NULL;
io->seekable = seekable;
fmtctx->iformat = NULL;
fmtctx->oformat = NULL;
fmtctx->priv_data=NULL;
fmtctx->pb = io;
fmtctx->ctx_flags = 0;
fmtctx->flags = AVFMT_FLAG_CUSTOM_IO | AVFMT_FLAG_NOBUFFER | AVFMT_FLAG_DISCARD_CORRUPT;
fmtctx->debug = 0;
strcpy(fmtctx->filename, "Any dummy filename");
printf("probsize = %d\r\n", fmtctx->probesize);
FFMPEG* ff = ffmpegOpenImpl(NULL, fmtctx);
if (ff) {
ff->close = close;
ff->customHandle = handle;
ff->customBuffer = buf;
ff->custom = 1;
}
return ff;
}
Example #4
0
// Open a file with a (possibly) Unicode filename
int ufile_fopen(AVIOContext **s, const wxString & name, int flags)
{
   wxFile::OpenMode mode;

   auto f = std::make_unique<wxFile>();
   if (!f) {
      return -ENOMEM;
   }

   if (flags == (AVIO_FLAG_READ | AVIO_FLAG_WRITE)) {
      return -EINVAL;
   } else if (flags == AVIO_FLAG_WRITE) {
      mode = wxFile::write;
   } else {
      mode = wxFile::read;
   }

   if (!f->Open(name, mode)) {
      return -ENOENT;
   }

   *s = avio_alloc_context((unsigned char*)av_malloc(32768), 32768,
                           flags & AVIO_FLAG_WRITE,
                           /*opaque*/f.get(),
                           ufile_read,
                           ufile_write,
                           ufile_seek);
   if (!*s) {
      return -ENOMEM;
   }

   f.release(); // s owns the file object now

   return 0;
}
Example #5
0
AVIOContext* QAVIOContext::context()
{
    // buffer will be released in av_probe_input_buffer2=>ffio_rewind_with_probe_data. always is? may be another context
    unsigned char* m_ucDataBuffer = (unsigned char*)av_malloc(IODATA_BUFFER_SIZE);
    m_avio = avio_alloc_context(m_ucDataBuffer, IODATA_BUFFER_SIZE, 0, this, &read, 0, &seek);
    return m_avio;
}
AUD_FFMPEGReader::AUD_FFMPEGReader(boost::shared_ptr<AUD_Buffer> buffer) :
		m_pkgbuf(AVCODEC_MAX_AUDIO_FRAME_SIZE<<1),
		m_membuffer(buffer),
		m_membufferpos(0)
{
	m_membuf = reinterpret_cast<data_t*>(av_malloc(FF_MIN_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE));

	m_aviocontext = avio_alloc_context(m_membuf, FF_MIN_BUFFER_SIZE, 0, this,
									   read_packet, NULL, seek_packet);

	if(!m_aviocontext)
	{
		av_free(m_aviocontext);
		AUD_THROW(AUD_ERROR_FILE, fileopen_error);
	}

	m_formatCtx = avformat_alloc_context();
	m_formatCtx->pb = m_aviocontext;
	if(avformat_open_input(&m_formatCtx, "", NULL, NULL)!=0)
	{
		av_free(m_aviocontext);
		AUD_THROW(AUD_ERROR_FILE, streamopen_error);
	}

	try
	{
		init();
	}
	catch(AUD_Exception&)
	{
		avformat_close_input(&m_formatCtx);
		av_free(m_aviocontext);
		throw;
	}
}
Example #7
0
static int mpjpeg_read_probe(AVProbeData *p)
{
    AVIOContext *pb;
    char line[128] = { 0 };
    int ret = 0;

    if (p->buf_size < 2 || p->buf[0] != '-' || p->buf[1] != '-')
        return 0;

    pb = avio_alloc_context(p->buf, p->buf_size, 0, NULL, NULL, NULL, NULL);
    if (!pb)
        return AVERROR(ENOMEM);

    while (!pb->eof_reached) {
        ret = get_line(pb, line, sizeof(line));
        if (ret < 0)
            break;

        ret = check_content_type(line);
        if (!ret) {
            ret = AVPROBE_SCORE_MAX;
            break;
        }
    }

    av_free(pb);

    return ret;
}
Example #8
0
status_t
AVFormatWriter::Init(const media_file_format* fileFormat)
{
	TRACE("AVFormatWriter::Init()\n");

	uint8* buffer = static_cast<uint8*>(av_malloc(kIOBufferSize));
	if (buffer == NULL)
		return B_NO_MEMORY;

	// Allocate I/O context and initialize it with buffer
	// and hook functions, pass ourself as cookie.
	fIOContext = avio_alloc_context(buffer, kIOBufferSize, 1, this,
			0, _Write, _Seek);
	if (fIOContext == NULL) {
		TRACE("av_alloc_put_byte() failed!\n");
		return B_ERROR;
	}

	// Setup I/O hooks. This seems to be enough.
	fContext->pb = fIOContext;

	// Set the AVOutputFormat according to fileFormat...
	fContext->oformat = av_guess_format(fileFormat->short_name,
		fileFormat->file_extension, fileFormat->mime_type);
	if (fContext->oformat == NULL) {
		TRACE("  failed to find AVOuputFormat for %s\n",
			fileFormat->short_name);
		return B_NOT_SUPPORTED;
	}

	TRACE("  found AVOuputFormat for %s: %s\n", fileFormat->short_name,
		fContext->oformat->name);

	return B_OK;
}
Example #9
0
FilePtr openAVData(const char *name, char *buffer, size_t buffer_len)
{
    FilePtr file;

    if(!done_init) {av_register_all();
    av_log_set_level(AV_LOG_ERROR);
    done_init = 1;}

    if(!name)
        name = "";

    file = (FilePtr)calloc(1, sizeof(*file));
    if(file && (file->FmtCtx=avformat_alloc_context()) != NULL)
    {
        file->membuf.buffer = buffer;
        file->membuf.length = buffer_len;
        file->membuf.pos = 0;

        file->FmtCtx->pb = avio_alloc_context(NULL, 0, 0, &file->membuf,
                                              MemData_read, MemData_write,
                                              MemData_seek);
        if(file->FmtCtx->pb && avformat_open_input(&file->FmtCtx, name, NULL, NULL) == 0)
        {
            if(avformat_find_stream_info(file->FmtCtx, NULL) >= 0)
                return file;
            avformat_close_input(&file->FmtCtx);
        }
        if(file->FmtCtx)
            avformat_free_context(file->FmtCtx);
        file->FmtCtx = NULL;
    }

    free(file);
    return NULL;
}
Example #10
0
FilePtr openAVCustom(const char *name, void *user_data,
                     int (*read_packet)(void *user_data, uint8_t *buf, int buf_size),
                     int (*write_packet)(void *user_data, uint8_t *buf, int buf_size),
                     int64_t (*seek)(void *user_data, int64_t offset, int whence))
{
    FilePtr file;

    if(!done_init) {av_register_all();
    av_log_set_level(AV_LOG_ERROR);
    done_init = 1;}

    if(!name)
        name = "";

    file = (FilePtr)calloc(1, sizeof(*file));
    if(file && (file->FmtCtx=avformat_alloc_context()) != NULL)
    {
        file->FmtCtx->pb = avio_alloc_context(NULL, 0, 0, user_data,
                                              read_packet, write_packet, seek);
        if(file->FmtCtx->pb && avformat_open_input(&file->FmtCtx, name, NULL, NULL) == 0)
        {
            if(avformat_find_stream_info(file->FmtCtx, NULL) >= 0)
                return file;
            avformat_close_input(&file->FmtCtx);
        }
        if(file->FmtCtx)
            avformat_free_context(file->FmtCtx);
        file->FmtCtx = NULL;
    }

    free(file); 
    return NULL;
}
status_t
StreamBase::Open()
{
	BAutolock _(fStreamLock);

	// Init probing data
	size_t bufferSize = 32768;
	uint8* buffer = static_cast<uint8*>(av_malloc(bufferSize));
	if (buffer == NULL)
		return B_NO_MEMORY;

	// Allocate I/O context with buffer and hook functions, pass ourself as
	// cookie.
	memset(buffer, 0, bufferSize);
	fIOContext = avio_alloc_context(buffer, bufferSize, 0, this, _Read, 0,
		_Seek);
	if (fIOContext == NULL) {
		TRACE("StreamBase::Open() - avio_alloc_context() failed!\n");
		return B_ERROR;
	}

	fContext = avformat_alloc_context();
	fContext->pb = fIOContext;

	// Allocate our context and probe the input format
	if (avformat_open_input(&fContext, "", NULL, NULL) < 0) {
		TRACE("StreamBase::Open() - avformat_open_input() failed!\n");
		// avformat_open_input() frees the context in case of failure
		return B_NOT_SUPPORTED;
	}

	TRACE("StreamBase::Open() - "
		"avformat_open_input(): %s\n", fContext->iformat->name);
	TRACE("  flags:%s%s%s%s%s\n",
		(fContext->iformat->flags & AVFMT_GLOBALHEADER) ? " AVFMT_GLOBALHEADER" : "",
		(fContext->iformat->flags & AVFMT_NOTIMESTAMPS) ? " AVFMT_NOTIMESTAMPS" : "",
		(fContext->iformat->flags & AVFMT_GENERIC_INDEX) ? " AVFMT_GENERIC_INDEX" : "",
		(fContext->iformat->flags & AVFMT_TS_DISCONT) ? " AVFMT_TS_DISCONT" : "",
		(fContext->iformat->flags & AVFMT_VARIABLE_FPS) ? " AVFMT_VARIABLE_FPS" : ""
	);


	// Retrieve stream information
	if (avformat_find_stream_info(fContext, NULL) < 0) {
		TRACE("StreamBase::Open() - avformat_find_stream_info() failed!\n");
		return B_NOT_SUPPORTED;
	}

	fSeekByBytes = (fContext->iformat->flags & AVFMT_TS_DISCONT) != 0;
	fStreamBuildsIndexWhileReading
		= (fContext->iformat->flags & AVFMT_GENERIC_INDEX) != 0
			|| fSeekByBytes;

	TRACE("StreamBase::Open() - "
		"av_find_stream_info() success! Seeking by bytes: %d\n",
		fSeekByBytes);

	return B_OK;
}
Example #12
0
int main(int argc, char **argv)
{
    int ret;
    uint8_t *buffer = av_malloc(AVP_BUFFSIZE);

    if (!buffer)
        exit(1);

    register_exit(avprobe_cleanup);

    options = real_options;
    parse_loglevel(argc, argv, options);
    av_register_all();
    avformat_network_init();
    init_opts();
#if CONFIG_AVDEVICE
    avdevice_register_all();
#endif

    show_banner();

    octx.print_header = ini_print_header;
    octx.print_footer = ini_print_footer;

    octx.print_array_header = ini_print_array_header;
    octx.print_array_footer = ini_print_array_footer;
    octx.print_object_header = ini_print_object_header;

    octx.print_integer = ini_print_integer;
    octx.print_string = ini_print_string;

    parse_options(NULL, argc, argv, options, opt_input_file);

    if (!input_filename) {
        show_usage();
        fprintf(stderr, "You have to specify one input file.\n");
        fprintf(stderr,
                "Use -h to get full help or, even better, run 'man %s'.\n",
                program_name);
        exit_program(1);
    }

    probe_out = avio_alloc_context(buffer, AVP_BUFFSIZE, 1, NULL, NULL,
                                 probe_buf_write, NULL);
    if (!probe_out)
        exit_program(1);

    probe_header();
    ret = probe_file(input_filename);
    probe_footer();
    avio_flush(probe_out);
    av_freep(&probe_out);
    av_freep(&buffer);
    uninit_opts();
    avformat_network_deinit();

    return ret;
}
Example #13
0
void FFmpeg_Decoder::open(const std::string &fname)
{
    close();
    mDataStream = mResourceMgr.openResource(fname);

    if((mFormatCtx=avformat_alloc_context()) == NULL)
        fail("Failed to allocate context");

    mFormatCtx->pb = avio_alloc_context(NULL, 0, 0, this, readPacket, writePacket, seek);
    if(!mFormatCtx->pb || avformat_open_input(&mFormatCtx, fname.c_str(), NULL, NULL) != 0)
    {
        avformat_free_context(mFormatCtx);
        mFormatCtx = NULL;
        fail("Failed to allocate input stream");
    }

    try
    {
        if(avformat_find_stream_info(mFormatCtx, NULL) < 0)
            fail("Failed to find stream info in "+fname);

        for(size_t j = 0;j < mFormatCtx->nb_streams;j++)
        {
            if(mFormatCtx->streams[j]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
            {
                std::auto_ptr<MyStream> stream(new MyStream);
                stream->mCodecCtx = mFormatCtx->streams[j]->codec;
                stream->mStreamIdx = j;
                stream->mPackets = NULL;

                AVCodec *codec = avcodec_find_decoder(stream->mCodecCtx->codec_id);
                if(!codec)
                {
                    std::stringstream ss("No codec found for id ");
                    ss << stream->mCodecCtx->codec_id;
                    fail(ss.str());
                }
                if(avcodec_open(stream->mCodecCtx, codec) < 0)
                    fail("Failed to open audio codec " + std::string(codec->long_name));

                stream->mDecodedData = (char*)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
                stream->mDecodedDataSize = 0;

                stream->mParent = this;
                mStreams.push_back(stream.release());
                break;
            }
        }
        if(mStreams.empty())
            fail("No audio streams in "+fname);
    }
    catch(std::exception &e)
    {
        av_close_input_file(mFormatCtx);
        mFormatCtx = NULL;
        throw;
    }
}
Example #14
0
/**
 * SPDIFEncoder constructor
 * Args:
 *   QString muxer       : name of the muxer.
 *                         Use "spdif" for IEC 958 or IEC 61937 encapsulation
 *                         (AC3, DTS, E-AC3, TrueHD, DTS-HD-MA)
 *                         Use "adts" for ADTS encpsulation (AAC)
 *   AVCodecContext *ctx : CodecContext to be encaspulated
 */
SPDIFEncoder::SPDIFEncoder(QString muxer, int codec_id)
    : m_complete(false), m_oc(NULL), m_stream(NULL), m_size(0)
{
    QByteArray dev_ba     = muxer.toAscii();
    AVOutputFormat *fmt;

    avcodeclock->lock();
    av_register_all();
    avcodeclock->unlock();

    fmt = av_guess_format(dev_ba.constData(), NULL, NULL);
    if (!fmt)
    {
        LOG(VB_AUDIO, LOG_ERR, LOC + "av_guess_format");
        return;
    }

    m_oc = avformat_alloc_context();
    if (!m_oc)
    {
        LOG(VB_AUDIO, LOG_ERR, LOC + "avformat_alloc_context");
        return;
    }
    m_oc->oformat = fmt;

    m_oc->pb = avio_alloc_context(m_buffer, sizeof(m_buffer), 0,
                                  this, NULL, funcIO, NULL);
    if (!m_oc->pb)
    {
        LOG(VB_AUDIO, LOG_ERR, LOC + "avio_alloc_context");
        Destroy();
        return;
    }

    m_oc->pb->seekable    = 0;
    m_oc->flags          |= AVFMT_NOFILE | AVFMT_FLAG_IGNIDX;

    m_stream = avformat_new_stream(m_oc, NULL);
    if (!m_stream)
    {
        LOG(VB_AUDIO, LOG_ERR, LOC + "avformat_new_stream");
        Destroy();
        return;
    }

    m_stream->id          = 1;

    AVCodecContext *codec = m_stream->codec;

    codec->codec_id       = (CodecID)codec_id;
    avformat_write_header(m_oc, NULL);

    LOG(VB_AUDIO, LOG_INFO, LOC + QString("Creating %1 encoder (for %2)")
            .arg(muxer).arg(ff_codec_id_string((CodecID)codec_id)));

    m_complete = true;
}
Example #15
0
bool MediaEngine::openContext() {
#ifdef USE_FFMPEG

#ifdef _DEBUG
	av_log_set_level(AV_LOG_VERBOSE);
	av_log_set_callback(&ffmpeg_logger);
#endif 

	u8* tempbuf = (u8*)av_malloc(m_bufSize);

	AVFormatContext *pFormatCtx = avformat_alloc_context();
	m_pFormatCtx = (void*)pFormatCtx;
	m_pIOContext = (void*)avio_alloc_context(tempbuf, m_bufSize, 0, (void*)this, _MpegReadbuffer, NULL, _MpegSeekbuffer);
	pFormatCtx->pb = (AVIOContext*)m_pIOContext;
  
	// Open video file
	if(avformat_open_input((AVFormatContext**)&m_pFormatCtx, NULL, NULL, NULL) != 0)
		return false;

	if(avformat_find_stream_info(pFormatCtx, NULL) < 0)
		return false;

	// Find the first video stream
	for(int i = 0; i < (int)pFormatCtx->nb_streams; i++) {
		if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
			m_videoStream = i;
			break;
		}
	}
	if(m_videoStream == -1)
		return false;

	// Get a pointer to the codec context for the video stream
	m_pCodecCtx = (void*)pFormatCtx->streams[m_videoStream]->codec;
	AVCodecContext *pCodecCtx = (AVCodecContext*)m_pCodecCtx;
  
	// Find the decoder for the video stream
	AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
	if(pCodec == NULL)
		return false;
  
	// Open codec
	AVDictionary *optionsDict = 0;
	if(avcodec_open2(pCodecCtx, pCodec, &optionsDict)<0)
		return false; // Could not open codec

	setVideoDim();
	int mpegoffset = bswap32(*(int*)(m_pdata + 8));
	m_demux = new MpegDemux(m_pdata, m_streamSize, mpegoffset);
	m_demux->setReadSize(m_readSize);
	m_demux->demux();
	m_audioPos = 0;
	m_audioContext = Atrac3plus_Decoder::OpenContext();
	m_isVideoEnd = false;
#endif // USE_FFMPEG
	return true;
}
int Pixel_to_JPG(const unsigned char *pixelBuff, int pixelSize, int pixelFmt, int pixelWidth, int pixelHeight, unsigned char *jpgBuff, int *jpgSize) {
	AVFormatContext *formatContext;
	AVOutputFormat *outputFormat;
	AVIOContext *ioContext;
	AVStream *stream;
	AVCodecContext *codecContext;
	AVCodec *codec;
	AVFrame *frame;
	AVPacket packet;
	int ioRet;
	int codecRet;
	int gotPacket;
	int pixelSizeMin;
	int result = -1;

	av_register_all();
	formatContext = avformat_alloc_context();
	outputFormat = av_guess_format("mjpeg", NULL, NULL);
	ioContext = avio_alloc_context(jpgBuff, *jpgSize, 0, NULL, NULL, NULL, NULL);
	formatContext->oformat = outputFormat;
	formatContext->pb = ioContext;
	stream = av_new_stream(formatContext, 0);
	codecContext = stream->codec;
	codecContext->codec_id = outputFormat->video_codec;
	codecContext->codec_type = AVMEDIA_TYPE_VIDEO;
	codecContext->pix_fmt = (enum AVPixelFormat)PF(pixelFmt);
	codecContext->width = pixelWidth;  
	codecContext->height = pixelHeight;
	codecContext->time_base.num = 1;  
	codecContext->time_base.den = 25;   
	codec = avcodec_find_encoder(codecContext->codec_id);
	avcodec_open2(codecContext, codec, NULL);

	avformat_write_header(formatContext, NULL);
	pixelSizeMin = avpicture_get_size(codecContext->pix_fmt, codecContext->width, codecContext->height);
	if (pixelSizeMin <= pixelSize) {
		av_new_packet(&packet, pixelSizeMin);
		frame = avcodec_alloc_frame();
		avpicture_fill((AVPicture *)frame, pixelBuff, codecContext->pix_fmt, codecContext->width, codecContext->height);
		codecRet = avcodec_encode_video2(codecContext, &packet, frame, &gotPacket);
		if (0 <= codecRet && 1 == gotPacket) {
			av_write_frame(formatContext, &packet);
			if (packet.size <= *jpgSize) {
				*jpgSize = packet.size;
				result = *jpgSize;
			}
		}
		avcodec_free_frame(&frame);
		av_free_packet(&packet);
	}
	av_write_trailer(formatContext);

	av_free(ioContext);
	avcodec_close(codecContext);
	avformat_free_context(formatContext);
	return result;
}
Example #17
0
static void
audio_setup_spdif_muxer(audio_decoder_t *ad, AVCodec *codec,
			media_queue_t *mq)
{
  AVOutputFormat *ofmt = av_guess_format("spdif", NULL, NULL);
  if(ofmt == NULL)
    return;

  const int mux_buffer_size = 16384;
  assert(ad->ad_mux_buffer == NULL);
  ad->ad_mux_buffer = malloc(mux_buffer_size);

  AVFormatContext *fctx = avformat_alloc_context();
  fctx->oformat = ofmt;
  fctx->pb = avio_alloc_context(ad->ad_mux_buffer, mux_buffer_size,
				1, ad, NULL, spdif_mux_write, NULL);
  AVStream *s = avformat_new_stream(fctx, codec);
  s->codec->sample_rate = 48000; // ???
  if(avcodec_open2(s->codec, codec, NULL)) {

    TRACE(TRACE_ERROR, "audio", "Unable to open %s codec for SPDIF",
	  codec->name);
  bad:
    av_free(fctx->pb);
    free(ad->ad_mux_buffer);
    ad->ad_mux_buffer = NULL;
    avformat_free_context(fctx);
    return;
  }
  
  if(avformat_write_header(fctx, NULL)) {
    TRACE(TRACE_ERROR, "audio", "Unable to open SPDIF muxer",
	  codec->name);
    goto bad;
  }
  ad->ad_spdif_muxer = fctx;
  TRACE(TRACE_DEBUG, "audio", "SPDIF muxer opened");

  const char *name;
  switch(codec->id) {
  case AV_CODEC_ID_DTS:  name = "DTS"; break;
  case AV_CODEC_ID_AC3:  name = "AC3"; break;
  case AV_CODEC_ID_EAC3: name = "EAC3"; break;
  default:
    name = "";
    break;
  }

  char str[64];
  snprintf(str, sizeof(str), "%s%sPass-Through", name, *name ? " " : "");
  prop_set_string(mq->mq_prop_codec, str);

  ad->ad_in_sample_rate = 0;
  ad->ad_in_sample_format = 0;
  ad->ad_in_channel_layout = 0;
  prop_set(ad->ad_mp->mp_prop_ctrl, "canAdjustVolume", PROP_SET_INT, 0);
}
Example #18
0
/* slightly difference scanning function here so can't re-use lookup_default */
struct codec_ent encode_getcontainer(const char* const requested,
	int dst, const char* remote)
{
	AVFormatContext* ctx;
	struct codec_ent res = {0};

	if (requested && strcmp(requested, "stream") == 0){
		res.storage.container.format = av_guess_format("flv", NULL, NULL);

		if (!res.storage.container.format)
			LOG("(encode) couldn't setup streaming output.\n");
		else {
			ctx = avformat_alloc_context();
			ctx->oformat = res.storage.container.format;
			res.storage.container.context = ctx;
			res.setup.muxer = default_format_setup;
			int rv = avio_open2(&ctx->pb, remote, AVIO_FLAG_WRITE, NULL, NULL);
			LOG("(encode) attempting to open: %s, result: %d\n", remote, rv);
		}

		return res;
	}

	if (requested)
		res.storage.container.format = av_guess_format(requested, NULL, NULL);

	if (!res.storage.container.format){
		LOG("(encode) couldn't find a suitable container matching (%s),"
			"	reverting to matroska (MKV)\n", requested);
		res.storage.container.format = av_guess_format("matroska", NULL, NULL);
	} else
		LOG("(encode) requested container (%s) found.\n", requested);

/* no stream, nothing requested that matched and default didn't work.
 * Give up and cascade. */
	if (!res.storage.container.format){
		LOG("(encode) couldn't find a suitable container.\n");
		return res;
	}

	avformat_alloc_output_context2(&ctx, res.storage.container.format,
	NULL, NULL);

/*
 * Since there's no sane way for us to just pass a file descriptor and
 * not be limited to pipe behaviors, we have to provide an entire
 * custom avio class..
 */
	int* fdbuf = malloc(sizeof(int));
	*fdbuf = dst;
	ctx->pb = avio_alloc_context(av_malloc(4096), 4096, 1, fdbuf, fdr, fdw, fds);

	res.storage.container.context = ctx;
	res.setup.muxer = default_format_setup;

	return res;
}
StreamIOContext::StreamIOContext(std::istream& stream, std::size_t buffer_size)
    :m_fin(stream),
     m_io_buffer(static_cast<unsigned char*>(av_malloc(buffer_size)), [](void*) { /* will be freed by the io_context */ }),
     m_io_context_storage(avio_alloc_context(m_io_buffer.get(), static_cast<int>(buffer_size), 0, this,
                                             StreamIOContext::static_io_read_packet, nullptr,
                                             StreamIOContext::static_io_seek),
                          [](AVIOContext* ctx) { av_free(ctx->buffer); av_free(ctx); })
{
}
Example #20
0
BOOL DecodeCDInit(PLAYERINFO* playerinfo)
{
	PLAYERDECODE* decode = &playerinfo->decode;
	CDTRACK* cdtrack = &playerinfo->cdtrack;
	CDTrackInit(cdtrack);
	
	decode->io = avio_alloc_context(NULL, 0, 0, cdtrack, ReadCDPacket, NULL, SeekCDPacket);
	if (decode->io != NULL)
	{
		AVInputFormat* input = NULL;
		int ret = av_probe_input_buffer(decode->io, &input, NULL, NULL, 0, 0);
		if (ret == 0)
		{
			decode->format = avformat_alloc_context();
			if (decode->format != NULL)
			{
				decode->format->pb = decode->io;
				ret = avformat_open_input(&decode->format, NULL, input, NULL);				
				if (ret == 0)
				{		
					ret = avformat_find_stream_info(decode->format, NULL);
					if (ret >= 0)
					{			
						int index = -1;
						for (unsigned int i = 0; i < decode->format->nb_streams; i++)
						{
							if (decode->format->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
							{
								decode->context = decode->format->streams[i]->codec;
								index = i;
								break;
							}
						}

						if (index > -1)
						{
							decode->codec = avcodec_find_decoder(decode->context->codec_id);
							if (decode->codec != NULL)
							{
								ret = avcodec_open2(decode->context, decode->codec, NULL);
								if (ret == 0)
								{					
									av_init_packet(&decode->packet);
									return TRUE;
								}					
							}				
						}			
					}
				}
			}
		}
	}

	return FALSE;
}
Example #21
0
bool MediaConverter::initializeInput(const LPRImage *pRawImage)
{
	//LPRImage *pImage = NULL;
	//LPRDecodeImage(&pImage, pRawImage->pData, pRawImage->imageSize, LPR_ENCODE_FORMAT_JPG, 0);
	//mOutputWidth = pImage->width;
	//mOutputHeight = pImage->height;
	//LPRReleaseImage(pImage);
	//// pRawImage现在还没有输出到视频,还不能释放
	if (NULL == mInputFmtPtr)
	{
		AVProbeData pd = {"fake.jpg", NULL, 0};
		mInputFmtPtr = av_probe_input_format(&pd, 0);
		mInputFmtPtr->flags = 0;
	}
	AVIOContext *pIOCtx = avio_alloc_context(pRawImage->pData, pRawImage->imageSize, 0, NULL, NULL, NULL, NULL);
	AVFormatContext *pInputFormatCtx = avformat_alloc_context();
	pInputFormatCtx->pb = pIOCtx;
	if (avformat_open_input(&pInputFormatCtx, "fake.jpg", mInputFmtPtr, NULL) != 0)
	{
		printf("Failed to open %s.\n", "fake.jpg");
		return false;
	}
	if (avformat_find_stream_info(pInputFormatCtx, NULL) < 0)
	{
		printf("Failed to parse %s.\n", "fake.jpg");
		return false;
	}
	av_dump_format(pInputFormatCtx, 0, "fake.jpg", 0);
	int videoStreamIndex = -1;
	for (size_t i = 0; i < pInputFormatCtx->nb_streams; ++ i)
	{
		if (pInputFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
		{
			videoStreamIndex = i;
			break;
		}
	}
	if (videoStreamIndex == -1)
	{
		printf("Could not find a video stream.\n");
		return false;
	}
	AVCodecContext *pInputCodecCtx = pInputFormatCtx->streams[videoStreamIndex]->codec;
	// 输入媒体的宽高和输出媒体的宽高保持一致
	mOutputWidth = pInputCodecCtx->width;
	mOutputHeight = pInputCodecCtx->height;
	//////////////////////////////////////////////////////////////////////////
	// 参数已经读取完毕,释放资源
	avcodec_close(pInputCodecCtx);
	av_free(pIOCtx);
	avformat_close_input(&pInputFormatCtx);

	mInputFramePtr = avcodec_alloc_frame();
	return true;
}
Example #22
0
STDMETHODIMP CBDDemuxer::SetTitle(int idx)
{
  HRESULT hr = S_OK;
  int ret; // return values
  if (m_pTitle) {
    bd_free_title_info(m_pTitle);
  }

  // Init Event Queue
  bd_get_event(m_pBD, nullptr);

  // Select title
  m_pTitle = bd_get_title_info(m_pBD, idx, 0);
  ret = bd_select_title(m_pBD, idx);
  if (ret == 0) {
    return E_FAIL;
  }

  if (m_pb) {
    av_free(m_pb->buffer);
    av_free(m_pb);
  }

  uint8_t *buffer = (uint8_t *)av_mallocz(BD_READ_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
  m_pb = avio_alloc_context(buffer, BD_READ_BUFFER_SIZE, 0, this, BDByteStreamRead, nullptr, BDByteStreamSeek);

  SafeRelease(&m_lavfDemuxer);
  SAFE_CO_FREE(m_rtOffset);

  m_lavfDemuxer = new CLAVFDemuxer(m_pLock, m_pSettings);
  m_lavfDemuxer->AddRef();
  m_lavfDemuxer->SetBluRay(this);
  if (FAILED(hr = m_lavfDemuxer->OpenInputStream(m_pb, nullptr, "mpegts", TRUE))) {
    SafeRelease(&m_lavfDemuxer);
    return hr;
  }

  m_lavfDemuxer->SeekByte(0, 0);

  // Process any events that occured during opening
  ProcessBDEvents();

  // Reset EOS protection
  m_EndOfStreamPacketFlushProtection = FALSE;

  // space for storing stream offsets
  m_rtOffset = (REFERENCE_TIME *)CoTaskMemAlloc(sizeof(REFERENCE_TIME) * m_lavfDemuxer->GetNumStreams());
  if (!m_rtOffset)
    return E_OUTOFMEMORY;
  memset(m_rtOffset, 0, sizeof(REFERENCE_TIME) * m_lavfDemuxer->GetNumStreams());

  DbgLog((LOG_TRACE, 20, L"Opened BD title with %d clips and %d chapters", m_pTitle->clip_count, m_pTitle->chapter_count));
  return S_OK;
}
void FFmpegMuxer::allocAVIOContext() {
    AVIOContext *avioc = avio_alloc_context(
        _internalBuffer,
        INTERNAL_BUFFER_SIZE,
        AVIO_FLAG_WRITE,
        _stream.get(),
        customRead,
        customWrite,
        customSeek);

    _fmtContext->pb = avioc;
}
Example #24
0
bool MediaEngine::openContext() {
#ifdef USE_FFMPEG
	InitFFmpeg();

	if (m_pFormatCtx || !m_pdata)
		return false;
	m_mpegheaderReadPos = 0;
	m_decodingsize = 0;

	u8* tempbuf = (u8*)av_malloc(m_bufSize);

	m_pFormatCtx = avformat_alloc_context();
	m_pIOContext = avio_alloc_context(tempbuf, m_bufSize, 0, (void*)this, _MpegReadbuffer, NULL, 0);
	m_pFormatCtx->pb = m_pIOContext;

	// Open video file
	if (avformat_open_input((AVFormatContext**)&m_pFormatCtx, NULL, NULL, NULL) != 0)
		return false;

	if (avformat_find_stream_info(m_pFormatCtx, NULL) < 0) {
		closeContext();
		return false;
	}

	if (m_videoStream >= (int)m_pFormatCtx->nb_streams) {
		WARN_LOG_REPORT(ME, "Bad video stream %d", m_videoStream);
		m_videoStream = -1;
	}

	if (m_videoStream == -1) {
		// Find the first video stream
		for(int i = 0; i < (int)m_pFormatCtx->nb_streams; i++) {
			if(m_pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
				m_videoStream = i;
				break;
			}
		}
		if(m_videoStream == -1)
			return false;
	}

	if (!setVideoStream(m_videoStream, true))
		return false;

	setVideoDim();
	m_audioContext = AT3Create();
	m_isVideoEnd = false;
	m_noAudioData = false;
	m_mpegheaderReadPos++;
	av_seek_frame(m_pFormatCtx, m_videoStream, 0, 0);
#endif // USE_FFMPEG
	return true;
}
Example #25
0
AVIOContext *av_alloc_put_byte(
                  unsigned char *buffer,
                  int buffer_size,
                  int write_flag,
                  void *opaque,
                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
                  int64_t (*seek)(void *opaque, int64_t offset, int whence))
{
    return avio_alloc_context(buffer, buffer_size, write_flag, opaque,
                              read_packet, write_packet, seek);
}
Example #26
0
static int open_null_ctx(AVIOContext **ctx)
{
    int buf_size = 32768;
    uint8_t *buf = av_malloc(buf_size);
    if (!buf)
        return AVERROR(ENOMEM);
    *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
    if (!*ctx) {
        av_free(buf);
        return AVERROR(ENOMEM);
    }
    return 0;
}
Example #27
0
AVIOContext *
fa_libav_open(const char *url, int buf_size, char *errbuf, size_t errlen)
{
  fa_handle_t *fh;

  if((fh = fa_open(url, errbuf, errlen)) == NULL)
    return NULL;

  if(buf_size == 0)
    buf_size = 32768;
  void *buf = malloc(buf_size);
  return avio_alloc_context(buf, buf_size, 0, fh, fa_libav_read, NULL, 
			    fa_libav_seek);
}
Example #28
0
// call->master_lock held in W
int media_player_play_blob(struct media_player *mp, const str *blob) {
#ifdef WITH_TRANSCODING
	const char *err;
	int av_ret = 0;

	if (media_player_play_init(mp))
		return -1;

	mp->blob = str_dup(blob);
	err = "out of memory";
	if (!mp->blob)
		goto err;
	mp->read_pos = *mp->blob;

	err = "could not allocate AVFormatContext";
	mp->fmtctx = avformat_alloc_context();
	if (!mp->fmtctx)
		goto err;

	void *avio_buf = av_malloc(DEFAULT_AVIO_BUFSIZE);
	err = "failed to allocate AVIO buffer";
	if (!avio_buf)
		goto err;

	mp->avioctx = avio_alloc_context(avio_buf, DEFAULT_AVIO_BUFSIZE, 0, mp, __mp_avio_read,
			NULL, __mp_avio_seek);
	err = "failed to allocate AVIOContext";
	if (!mp->avioctx)
		goto err;

	mp->fmtctx->pb = mp->avioctx;

	// consumes allocated mp->fmtctx
	err = "failed to open AVFormatContext input";
	av_ret = avformat_open_input(&mp->fmtctx, "dummy", NULL, NULL);
	if (av_ret < 0)
		goto err;

	media_player_play_start(mp);

	return 0;

err:
	ilog(LOG_ERR, "Failed to start media playback from memory: %s", err);
	if (av_ret)
		ilog(LOG_ERR, "Error returned from libav: %s", av_error(av_ret));
#endif
	return -1;
}
Example #29
0
// Allocate object
VALUE reader_alloc(VALUE klass) {
	ReaderInternal * internal = (ReaderInternal *)av_mallocz(sizeof(ReaderInternal));
	if (!internal) rb_raise(rb_eNoMemError, "Failed to allocate internal structure");

	internal->format = avformat_alloc_context();
	if (!internal->format) rb_raise(rb_eNoMemError, "Failed to allocate FFMPEG format context");

	internal->protocol = avio_alloc_context(av_malloc(reader_READ_BUFFER_SIZE), reader_READ_BUFFER_SIZE, 0, internal, read_packet, NULL, NULL);
	if (!internal->protocol) rb_raise(rb_eNoMemError, "Failed to allocate FFMPEG IO context");

	internal->protocol->seekable = 0;
	internal->format->pb = internal->protocol;

	return Data_Wrap_Struct(klass, reader_mark, reader_free, (void *)internal);
}
Example #30
0
HRESULT CLAVAudio::InitBitstreaming()
{
  // Alloc buffer for the AVIO context
  BYTE *buffer = (BYTE *)CoTaskMemAlloc(LAV_BITSTREAM_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
  if(!buffer)
    return E_OUTOFMEMORY;
  
  // Create AVIO context
  m_avioBitstream = avio_alloc_context(buffer, LAV_BITSTREAM_BUFFER_SIZE, 1, this, NULL, BSWriteBuffer, NULL);
  if(!m_avioBitstream) {
    SAFE_CO_FREE(buffer);
    return E_FAIL;
  }

  return S_OK;
}