Ejemplo n.º 1
1
/*
* Return media file duration or return NULL if couldn't open file
*/
int CBaseOperation::GetFileDuration(PCHAR filename){
	av_register_all();
	AVFormatContext *fmtCtx = avformat_alloc_context();
	AVPacket packet;
	int64_t duration = 0;
	av_init_packet(&packet);
	if (avformat_open_input(&fmtCtx, filename, nullptr, nullptr) != 0){
		return NULL;
	}
	if (avformat_find_stream_info(fmtCtx, nullptr) < 0){
		return NULL;
	}
	auto videoStreamIndex = av_find_best_stream(fmtCtx, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
	if (videoStreamIndex < 0){
		return NULL;
	}
	auto codecCtx = fmtCtx->streams[videoStreamIndex]->codec;
	if (avcodec_open2(codecCtx, avcodec_find_decoder(codecCtx->codec_id), nullptr) < 0){
		return NULL;
	}
	av_read_frame(fmtCtx, &packet);
	auto startPts = packet.pts;
	while (!av_read_frame(fmtCtx, &packet))
	{
		duration += packet.pts - startPts;
		av_packet_unref(&packet);
		av_free_packet(&packet);
	}
	duration *= av_q2d(fmtCtx->streams[videoStreamIndex]->time_base);
	av_packet_unref(&packet);
	av_free_packet(&packet);
	avformat_close_input(&fmtCtx);
	return duration;
}
Ejemplo n.º 2
0
int setDataSource(const char* url)
{
    int ret = -1;
    if (m_pFormatContext)
    {
        avformat_free_context(m_pFormatContext);
        m_pFormatContext = NULL;
    }

    m_pFormatContext = avformat_alloc_context();
    if (!m_pFormatContext)
    {
        return -1;
    }
    ret = avformat_open_input(&m_pFormatContext, url, NULL, NULL);
    if (ret != 0)
    {
        delete m_pFormatContext;
        return ret;
    }

    ret = avformat_find_stream_info(m_pFormatContext, NULL);
    if (ret != 0)
    {
        delete m_pFormatContext;
        return ret;
    }

    m_nStreamIndex[AVMEDIA_TYPE_VIDEO] = av_find_best_stream(m_pFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
    m_nStreamIndex[AVMEDIA_TYPE_AUDIO] = av_find_best_stream(m_pFormatContext, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);

    return ret;
}
Ejemplo n.º 3
0
SCM make_ffmpeg_input(SCM scm_file_name, SCM scm_debug)
{
  SCM retval;
  struct ffmpeg_t *self;
  scm_dynwind_begin(0);
  const char *file_name = scm_to_locale_string(scm_file_name);
  scm_dynwind_free(file_name);
  self = (struct ffmpeg_t *)scm_gc_calloc(sizeof(struct ffmpeg_t), "ffmpeg");
  self->video_stream_idx = -1;
  self->audio_stream_idx = -1;
  SCM_NEWSMOB(retval, ffmpeg_tag, self);

  int err;
  err = avformat_open_input(&self->fmt_ctx, file_name, NULL, NULL);
  if (err < 0) {
    ffmpeg_destroy(retval);
    scm_misc_error("make-ffmpeg-input", "Error opening file '~a': ~a", scm_list_2(scm_file_name, get_error_text(err)));
  };

  err = avformat_find_stream_info(self->fmt_ctx, NULL);
  if (err < 0) {
    ffmpeg_destroy(retval);
    scm_misc_error("make-ffmpeg-input", "No stream information in file '~a': ~a", scm_list_2(scm_file_name, get_error_text(err)));
  };

  // TODO: only open desired streams
  // Open video stream
  self->video_stream_idx = av_find_best_stream(self->fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
  if (self->video_stream_idx >= 0)
    self->video_codec_ctx = open_decoder(retval, scm_file_name, video_stream(self), "video");

  // Open audio stream
  self->audio_stream_idx = av_find_best_stream(self->fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
  if (self->audio_stream_idx >= 0)
    self->audio_codec_ctx = open_decoder(retval, scm_file_name, audio_stream(self), "audio");

  // Print debug information
  if (scm_is_true(scm_debug)) av_dump_format(self->fmt_ctx, 0, file_name, 0);

  // Allocate input frames
  self->video_target_frame = allocate_frame(retval);
  self->audio_target_frame = allocate_frame(retval);

  // Initialise data packet
  av_init_packet(&self->pkt);
  self->pkt.data = NULL;
  self->pkt.size = 0;

  scm_dynwind_end();
  return retval;
}
Ejemplo n.º 4
0
static int open_input_file(const char *filename)
{
    int ret;
    AVCodec *dec;

    if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
        return ret;
    }

    if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
        return ret;
    }

    /* select the audio stream */
    ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot find a audio stream in the input file\n");
        return ret;
    }
    audio_stream_index = ret;
    dec_ctx = fmt_ctx->streams[audio_stream_index]->codec;

    /* init the audio decoder */
    if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open audio decoder\n");
        return ret;
    }

    return 0;
}
Ejemplo n.º 5
0
static int open_codec_context(AVFormatContext* fmt_ctx, int *stream_idx, AVMediaType media_type)
{
    int ret;
    AVStream *st;
    AVCodecContext *dec_ctx = NULL;
    AVCodec *dec = NULL;
    AVDictionary *opts = NULL;

    ret = av_find_best_stream(fmt_ctx, media_type, -1, -1, NULL, 0);
    if (ret < 0) {
		LOGE("Could not find best %s stream in input file",
			av_get_media_type_string(media_type));
        return ret;
    } else {
        *stream_idx = ret;
        st = fmt_ctx->streams[*stream_idx];

        /* find decoder for the stream */
        dec_ctx = st->codec;
        dec = avcodec_find_decoder(dec_ctx->codec_id);
        if (!dec) {
            LOGE("Failed to find %s codec", av_get_media_type_string(media_type));
            return AVERROR(EINVAL);
        }

        /* Init the decoders, with or without reference counting */
        av_dict_set(&opts, "refcounted_frames", "1", 0);
        if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) {
            LOGE("Failed to open %s codec", av_get_media_type_string(media_type));
            return ret;
        }
    }

    return 0;
}
Ejemplo n.º 6
0
    bool BaseMpegLoader::open() 
    {
        av_register_all();
        int res = 0;
        FmtContext_ = avformat_alloc_context();
        if (!FmtContext_) 
            return false;

        if ((res = avformat_open_input(&FmtContext_,File_.toStdString().c_str(), 0, 0)) < 0)
            return false;

        Opened_ = true;

        if ((res = avformat_find_stream_info(FmtContext_, 0)) < 0)
            return false;

        StreamId_ = av_find_best_stream(FmtContext_, AVMEDIA_TYPE_AUDIO, -1, -1, &Codec_, 0);
        if (StreamId_ < 0)
            return false;

        Freq_ = FmtContext_->streams[StreamId_]->codec->sample_rate;
        if (FmtContext_->streams[StreamId_]->duration == AV_NOPTS_VALUE)
            Len_ = (FmtContext_->duration * Freq_) / AV_TIME_BASE;
        else
            Len_ = (FmtContext_->streams[StreamId_]->duration * Freq_ * FmtContext_->streams[StreamId_]->time_base.num) / FmtContext_->streams[StreamId_]->time_base.den;

        return true;
    }
Ejemplo n.º 7
0
int DLL_EXPORT open_input_file(char* inputVideoFileName,double* nb_frames,double* img_height,double* img_width)
{
    //GC_INIT();
    //GC_allow_register_threads();
    av_register_all();
    avcodec_register_all();
    ::AVFormatContext * ctx = NULL;
    AVCodec * codec = NULL;
    int strm = -1;
    AVCodecContext * codecCtx = NULL;
    int err = avformat_open_input(&ctx, inputVideoFileName, NULL, NULL);
    CHECK_ERR_INT(err);
    err = avformat_find_stream_info(ctx,NULL);
    CHECK_ERR_INT(err);
    strm = av_find_best_stream(ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);

    codecCtx = ctx->streams[strm]->codec;
    //printf("%d",ctx->streams[strm]->nb_frames);
    err = avcodec_open2(codecCtx, codec, NULL);
    CHECK_ERR_INT(err);
    *nb_frames=ctx->streams[strm]->nb_frames;
    *img_height=codecCtx->height;
    *img_width=codecCtx->width;
    video_file_name=(char*)malloc(strlen(inputVideoFileName)*(sizeof(char)+1));
    strcpy(video_file_name,inputVideoFileName);
    total_frames = ctx->streams[strm]->nb_frames;
    tiff_data_size_array = (int*) malloc((total_frames+1)*sizeof(int));
    tiff_data_array=(uint8_t**)malloc((total_frames+1)*sizeof(uint8_t*));
    avcodec_close(codecCtx);
    for(int i=0;i<MAX_THREADS;i++)
        frames_decoded[i]=0;
    avformat_close_input(&ctx);
    av_free(ctx);
    return 0;
}
Ejemplo n.º 8
0
int open_input_file(const char *filename)
{
    int ret;
    if ((ret = avformat_open_input(&pFormatContext, filename, NULL, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
        return ret;
    }
    if ((ret = avformat_find_stream_info(pFormatContext, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
        return ret;
    }

    AVCodec *dec = NULL;
    ret = av_find_best_stream(pFormatContext, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot find a audio stream in the input file\n");
        return ret;
    }
    iAudioStream = ret;
    pDecoderContext = pFormatContext->streams[iAudioStream]->codec;
    timebase        = pFormatContext->streams[iAudioStream]->time_base;

    if ((ret = avcodec_open2(pDecoderContext, dec, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open audio decoder\n");
        return ret;
    }
    return 0;
}
Ejemplo n.º 9
0
void AVFile::open(const char *url)
{
    if (formatCtx)
        throw AVException("Programming error: i already did it");

    if (avformat_open_input(&formatCtx, url, 0, 0) < 0)
        throw AVException("Unable to open media");

    if (avformat_find_stream_info(formatCtx, 0) < 0)
        throw AVException("Unable to find streams in media");

    AVCodec *codec;
    audioStream = av_find_best_stream(formatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
    if (audioStream < 0)
        throw AVException("No audio stream found");    

    codecCtx = formatCtx->streams[audioStream]->codec;
    if (avcodec_open2(codecCtx, codec, 0) < 0)
        throw AVException("Could not open codec");

    if (!codecCtx->channel_layout)
        codecCtx->channel_layout = av_get_default_channel_layout(codecCtx->channels);

    _updateSWR();
}
Ejemplo n.º 10
0
int open_codec_context(int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaType type, const char *src_filename) {
  int ret;
  AVStream *st;
  AVCodecContext *dec_ctx = NULL;
  AVCodec *dec = NULL;
  AVDictionary *opts = NULL;

  ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
  if (ret < 0) {
    fprintf(stderr, "Could not find %s stream in input file '%s'\n", av_get_media_type_string(type), src_filename);
    return ret;
  } else {
    *stream_idx = ret;
    st = fmt_ctx->streams[*stream_idx];

    /* find decoder for the stream */
    dec_ctx = st->codec;
    dec = avcodec_find_decoder(dec_ctx->codec_id);
    if (!dec) {
      fprintf(stderr, "Failed to find %s codec\n", av_get_media_type_string(type));
      return ret;
    }

    /* Init the decoders, with or without reference counting */
//     if (api_mode == API_MODE_NEW_API_REF_COUNT)
//       av_dict_set(&opts, "refcounted_frames", "1", 0);
    if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) {
      fprintf(stderr, "Failed to open %s codec\n", av_get_media_type_string(type));
      return ret;
    }
  }

  return 0;
}
Ejemplo n.º 11
0
static int open_codec_context(int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaType type)
{
    int ret;
    AVStream *st;
    AVCodecContext *dec_ctx = NULL;
    AVCodec *dec = NULL;
    ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
    if (ret < 0) {
		MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Could not find stream %s in input!", av_get_media_type_string(type));
        return ret;
    } else {
        *stream_idx = ret;
        st = fmt_ctx->streams[*stream_idx];
        /* find decoder for the stream */
        dec_ctx = st->codec;
        dec = avcodec_find_decoder(dec_ctx->codec_id);
        if (!dec) {
    		MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Failed to find %s codec!", av_get_media_type_string(type));
            return ret;
        }
        if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
    		MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Failed to open %s codec!", av_get_media_type_string(type));
            return ret;
        }
    }
    return 0;
}
Ejemplo n.º 12
0
int open_codec_context(int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaType type) {
    int ret;
    AVStream *st;
    AVCodecContext *dec_ctx = NULL;
    AVCodec *dec = NULL;
    AVDictionary *opts = NULL;
    
    ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
    if (ret < 0) {
        LOGE("can't find %s stream in input file\n", av_get_media_type_string(type));
        return ret;
    } else {
        *stream_idx = ret;
        st = fmt_ctx->streams[*stream_idx];
        
        dec_ctx = st->codec;
        dec = avcodec_find_decoder(dec_ctx->codec_id);
        if (!dec) {
            LOGE("failed to find %s codec\n", av_get_media_type_string(type));
            return ret;
        }
        
        av_dict_set(&opts, "refcounted_frames", "1", 0);
        if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) {
            LOGE("failed to open %s codec\n", av_get_media_type_string(type));
            return ret;
        }
    }
    
    return 0;
}
Ejemplo n.º 13
0
/**
 * Find a decoder and open it for the given AVFormatContext and AVMediaType.
 *
 * @param[out]  stream_index  index of the stream the decoder was opened for
 * @param[in]   format_context     format context
 * @param       type        media type - for this library typically audio
 */
static int open_codec_context(int *stream_index,
        AVFormatContext *format_context,
        AVCodecContext *context,
        enum AVMediaType type) {

    int res = 0;
    AVStream *stream;
    AVCodec *decoder = NULL;

    res = av_find_best_stream(format_context, type, -1, -1, NULL, 0);
    if (res < 0) {
        goto bail;
    }
    *stream_index = res;
    stream = format_context->streams[*stream_index];

    // find decoder for the stream
    decoder = avcodec_find_decoder(stream->codecpar->codec_id);
    if (!decoder) {
        goto bail;
    }
    context = avcodec_alloc_context3(decoder);
    if (!context) {
        goto bail;
    }

    res = avcodec_open2(context, decoder, NULL);
    if (res < 0) {
        goto bail;
    }
    return res;

bail:
    return res;
}
static int open_input_file(const char *filename)
{
    int ret;
    AVCodec *dec;

    if ((ret = avformat_open_input(&pFormatCtx, filename, NULL, NULL)) < 0) {
        printf( "Cannot open input file\n");
        return ret;
    }

    if ((ret = avformat_find_stream_info(pFormatCtx, NULL)) < 0) {
        printf( "Cannot find stream information\n");
        return ret;
    }

    /* select the video stream */
    ret = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
    if (ret < 0) {
        printf( "Cannot find a video stream in the input file\n");
        return ret;
    }
    video_stream_index = ret;
    pCodecCtx = pFormatCtx->streams[video_stream_index]->codec;

    /* init the video decoder */
    if ((ret = avcodec_open2(pCodecCtx, dec, NULL)) < 0) {
        printf( "Cannot open video decoder\n");
        return ret;
    }

    return 0;
}
Ejemplo n.º 15
0
jint setData(JNIEnv *env,jclass clz,jstring name){
	pause=1;
	i=0;
	tni=0;
	LOGI("%s","setData");
	const char *file=(*env)->GetStringUTFChars(env,name,0);
	if(avformat_open_input(&pFormatCtx,file,NULL,NULL)!=0)return -1;
	if(avformat_find_stream_info(pFormatCtx,NULL)<0)return -2;
	av_dump_format(pFormatCtx,-1,file,0);
	audioIndex=-1;
	int index;
	audioIndex=av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, &pCodec, 0);
	if(audioIndex<0)return -3;
	pCodecCtx = pFormatCtx->streams[audioIndex]->codec;
	av_log(NULL,AV_LOG_INFO,"解码器:%s",pCodec->name);
	ran= pFormatCtx->streams[audioIndex]->time_base;
	duration = pFormatCtx->streams[audioIndex]->duration;
	if(avcodec_open2(pCodecCtx,pCodec,NULL)<0)return -4;
	pFrame=av_frame_alloc();
	if(pFrame==NULL)return -5;
	packet = (AVPacket *)av_malloc(sizeof(AVPacket));
	av_init_packet(packet);
	ret=av_read_frame(pFormatCtx,packet);
	init_swr();
	i=1;
	(*env)->ReleaseStringUTFChars(env,name,file);
	return 0;
}
Ejemplo n.º 16
0
static int open_input_file(const char *filename)
{
    int ret;
    AVCodec *dec;

    if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
        return ret;
    }

    if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
        return ret;
    }

    /* select the video stream */
    ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");
        return ret;
    }
    video_stream_index = ret;
    dec_ctx = fmt_ctx->streams[video_stream_index]->codec;
    av_opt_set_int(dec_ctx, "refcounted_frames", 1, 0);

    /* init the video decoder */
    if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
        return ret;
    }

    return 0;
}
static int open_codec_context(int *stream_idx,
                              AVFormatContext *fmt_ctx, enum AVMediaType type)
{
    int ret, stream_index;
    AVStream *st;
    AVCodecContext *dec_ctx = NULL;
    AVCodec *dec = NULL;
    AVDictionary *opts = NULL;
    ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
    if (ret < 0) {
        fprintf(stderr, "Could not find %s stream in input file '%s'\n",
                av_get_media_type_string(type), src_filename);
        return ret;
    } else {
        stream_index = ret;
        st = fmt_ctx->streams[stream_index];
        /* find decoder for the stream */
        dec_ctx = st->codec;
        dec = avcodec_find_decoder(dec_ctx->codec_id);
        if (!dec) {
            fprintf(stderr, "Failed to find %s codec\n",
                    av_get_media_type_string(type));
            return AVERROR(EINVAL);
        }
        /* Init the decoders, with or without reference counting */
        av_dict_set(&opts, "refcounted_frames", refcount ? "1" : "0", 0);
        if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) {
            fprintf(stderr, "Failed to open %s codec\n",
                    av_get_media_type_string(type));
            return ret;
        }
        *stream_idx = stream_index;
    }
    return 0;
}
Ejemplo n.º 18
0
/*----------------------------------------------------------------------
|    open_code_context
+---------------------------------------------------------------------*/
static int open_codec_context(int* stream_idx, AVFormatContext* fmt_ctx, AVMediaType type)
{
    int ret;
    AVStream* st;
    AVCodecContext* dec_ctx = NULL;
    AVCodec* dec = NULL;

    ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
    if (ret < 0) {
        LOG_ERROR(LOG_TAG, "Could not find %s stream in input file.", av_get_media_type_string(type));
        return ret;
    }

    *stream_idx = ret;
    st = fmt_ctx->streams[*stream_idx];

    // Find decoder for the stream.
    dec_ctx = st->codec;
    dec = avcodec_find_decoder(dec_ctx->codec_id);
    if (!dec) {
        LOG_ERROR(LOG_TAG, "Failed to find %s codec.", av_get_media_type_string(type));
        return ret;
    }

    if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
        LOG_ERROR(LOG_TAG, "Failed to open %s codec.", av_get_media_type_string(type));
        return ret;
    }

    return ret;
}
Ejemplo n.º 19
0
static bool ffmpeg_image_open_decoder_context(struct ffmpeg_image *info)
{
	int ret = av_find_best_stream(info->fmt_ctx, AVMEDIA_TYPE_VIDEO,
			-1, 1, NULL, 0);
	if (ret < 0) {
		blog(LOG_WARNING, "Couldn't find video stream in file '%s': %s",
				info->file, av_err2str(ret));
		return false;
	}

	info->stream_idx  = ret;
	info->stream      = info->fmt_ctx->streams[ret];
	info->decoder_ctx = info->stream->codec;
	info->decoder     = avcodec_find_decoder(info->decoder_ctx->codec_id);

	if (!info->decoder) {
		blog(LOG_WARNING, "Failed to find decoder for file '%s'",
				info->file);
		return false;
	}

	ret = avcodec_open2(info->decoder_ctx, info->decoder, NULL);
	if (ret < 0) {
		blog(LOG_WARNING, "Failed to open video codec for file '%s': "
		                  "%s", info->file, av_err2str(ret));
		return false;
	}

	return true;
}
Ejemplo n.º 20
0
static int open_codec_context(int *stream_idx,
                              AVFormatContext *fmt_ctx, enum AVMediaType type)
{
    int ret;
    AVStream *st;
    AVCodecContext *dec_ctx = NULL;
    AVCodec *dec = NULL;

    ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
    if (ret < 0) {
        fprintf(stderr, "Could not find %s stream in input file '%s'\n",
                av_get_media_type_string(type), src_filename);
        return ret;
    } else {
        *stream_idx = ret;
        st = fmt_ctx->streams[*stream_idx];

        /* find decoder for the stream */
        dec_ctx = st->codec;
        dec = avcodec_find_decoder(dec_ctx->codec_id);
        if (!dec) {
            fprintf(stderr, "Failed to find %s codec\n",
                    av_get_media_type_string(type));
            return ret;
        }

        if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
            fprintf(stderr, "Failed to open %s codec\n",
                    av_get_media_type_string(type));
            return ret;
        }
    }

    return 0;
}
Ejemplo n.º 21
0
void Buffer::open(const QString &filename)
{
#ifdef HAVE_SOUNDTOUCH
    // Initialize FFmpeg

    stop();
    if (m_formatContext)
    {
        avformat_free_context( m_formatContext );
        m_formatContext = NULL;
    }

    av_register_all();

    if (avformat_open_input(&m_formatContext, filename.toStdString().c_str(), NULL, NULL) != 0)
    {
        qWarning() << "Error opening the file" << filename;
        return;
    }


    if (avformat_find_stream_info(m_formatContext, NULL) < 0)
    {
        qWarning() << "Error finding the stream info";
        return;
    }


    // Find the audio stream
    AVCodec* cdc = nullptr;
    m_streamIndex = av_find_best_stream(m_formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, &cdc, 0);
    if (m_streamIndex < 0)
    {
        qWarning() << "Could not find any audio stream in the file";
        return;
    }

    m_audioStream = m_formatContext->streams[m_streamIndex];
    m_codecContext = m_audioStream->codec;
    m_codecContext->codec = cdc;

    if (avcodec_open2(m_codecContext, m_codecContext->codec, NULL) != 0)
    {
        qWarning() << "Couldn't open the context with the decoder";
        return;
    }

    m_audioFormat = ::audioFormat( m_codecContext->channels, m_codecContext->sample_rate, m_codecContext->sample_fmt );
    if ( m_codecContext->channels != 1 && m_codecContext->channels != 2 )
    {
        qWarning() << m_codecContext->channels << " Channel formats are not supported. Use Mono or Stereo.";
        return;
    }
#else
    Q_UNUSED( filename );
#endif
}
Ejemplo n.º 22
0
static bool openStream (player_t * const player) {
	assert (player != NULL);
	/* no leak? */
	assert (player->fctx == NULL);

	int ret;

	/* stream setup */
	player->fctx = avformat_alloc_context ();
	player->fctx->interrupt_callback.callback = intCb;
	player->fctx->interrupt_callback.opaque = player;

	assert (player->url != NULL);
	if ((ret = avformat_open_input (&player->fctx, player->url, NULL, NULL)) < 0) {
		softfail ("Unable to open audio file");
	}

	if ((ret = avformat_find_stream_info (player->fctx, NULL)) < 0) {
		softfail ("find_stream_info");
	}

	/* ignore all streams, undone for audio stream below */
	for (size_t i = 0; i < player->fctx->nb_streams; i++) {
		player->fctx->streams[i]->discard = AVDISCARD_ALL;
	}

	player->streamIdx = av_find_best_stream (player->fctx, AVMEDIA_TYPE_AUDIO,
			-1, -1, NULL, 0);
	if (player->streamIdx < 0) {
		softfail ("find_best_stream");
	}

	player->st = player->fctx->streams[player->streamIdx];
	AVCodecContext * const cctx = player->st->codec;
	player->st->discard = AVDISCARD_DEFAULT;

	/* decoder setup */
	AVCodec * const decoder = avcodec_find_decoder (cctx->codec_id);
	if (decoder == NULL) {
		softfail ("find_decoder");
	}

	if ((ret = avcodec_open2 (cctx, decoder, NULL)) < 0) {
		softfail ("codec_open2");
	}

	if (player->lastTimestamp > 0) {
		av_seek_frame (player->fctx, player->streamIdx, player->lastTimestamp, 0);
	}

	player->songPlayed = 0;
	player->songDuration = av_q2d (player->st->time_base) *
			(double) player->st->duration;

	return true;
}
Ejemplo n.º 23
0
bool movie_player::load(const char* szFilepath)
{
    int iError = 0;
    AVCodec* m_pVideoCodec;
    AVCodec* m_pAudioCodec;

    unload(); //Unload any currently loaded video to free memory
    aborting = false;

    iError = avformat_open_input(&format_context, szFilepath, nullptr, nullptr);
    if(iError < 0)
    {
        av_strerror(iError, error_buffer, movie_error_buffer_capacity);
        last_error = std::string(error_buffer);
        return false;
    }

    iError = avformat_find_stream_info(format_context, nullptr);
    if(iError < 0)
    {
        av_strerror(iError, error_buffer, movie_error_buffer_capacity);
        last_error = std::string(error_buffer);
        return false;
    }

    video_stream_index = av_find_best_stream(format_context, AVMEDIA_TYPE_VIDEO, -1, -1, &m_pVideoCodec, 0);
    if (video_stream_index < 0) {
        av_strerror(video_stream_index, error_buffer, movie_error_buffer_capacity);
        last_error = std::string(error_buffer);
        return false;
    }
    video_codec_context = get_codec_context_for_stream(m_pVideoCodec, format_context->streams[video_stream_index]);
    avcodec_open2(video_codec_context, m_pVideoCodec, nullptr);

    audio_stream_index = av_find_best_stream(format_context, AVMEDIA_TYPE_AUDIO, -1, -1, &m_pAudioCodec, 0);
    if(audio_stream_index >= 0)
    {
        audio_codec_context = get_codec_context_for_stream(m_pAudioCodec, format_context->streams[audio_stream_index]);
        avcodec_open2(audio_codec_context, m_pAudioCodec, nullptr);
    }

    return true;
}
Ejemplo n.º 24
0
InputContext * input_context_new (const char * filename) {
    int ok = 0;

    // open file
    AVFormatContext * pfc = NULL;
    ok = avformat_open_input(&pfc, filename, NULL, NULL);
    if (ok != 0) {
        goto failed;
    }

    // find stream
    int stnb = av_find_best_stream(pfc, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
    AVStream * pst = pfc->streams[stnb];
    AVRational * ptb = &pst->time_base;
    int64_t duration = av_rescale(pst->duration, ptb->num, ptb->den);

    // find codec
    AVCodec * pc = avcodec_find_decoder(pst->codecpar->codec_id);
    if (!pc) {
        goto close_demuxer;
    }
    AVCodecContext * pcc = avcodec_alloc_context3(pc);
    if (!pcc) {
        goto close_demuxer;
    }
    ok = avcodec_parameters_to_context(pcc, pst->codecpar);
    if (ok < 0) {
        goto close_decoder;
    }
    ok = avcodec_open2(pcc, pc, NULL);
    if (ok != 0) {
        goto close_decoder;
    }

    InputContext * context = malloc(sizeof(InputContext));
    context->format_context = pfc;
    context->stream = pst;
    context->codec = pc;
    context->codec_context = pcc;
    context->stream_index = stnb;
    context->time_base = ptb;
    context->duration = duration;

    return context;

close_decoder:
    avcodec_free_context(&pcc);
close_demuxer:
    avformat_close_input(&pfc);
failed:
    return NULL;
}
Ejemplo n.º 25
0
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;
}
Ejemplo n.º 26
0
bool THMovie::load(const char* szFilepath)
{
    int iError = 0;
    AVCodec* m_pVideoCodec;
    AVCodec* m_pAudioCodec;

    unload(); //Unload any currently loaded video to free memory
    m_fAborting = false;

    iError = avformat_open_input(&m_pFormatContext, szFilepath, nullptr, nullptr);
    if(iError < 0)
    {
        av_strerror(iError, m_szErrorBuffer, ms_movieErrorBufferSize);
        m_sLastError = std::string(m_szErrorBuffer);
        return false;
    }

    iError = avformat_find_stream_info(m_pFormatContext, nullptr);
    if(iError < 0)
    {
        av_strerror(iError, m_szErrorBuffer, ms_movieErrorBufferSize);
        m_sLastError = std::string(m_szErrorBuffer);
        return false;
    }

    m_iVideoStream = av_find_best_stream(m_pFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, &m_pVideoCodec, 0);
    m_pVideoCodecContext = m_pFormatContext->streams[m_iVideoStream]->codec;
    avcodec_open2(m_pVideoCodecContext, m_pVideoCodec, nullptr);

    m_iAudioStream = av_find_best_stream(m_pFormatContext, AVMEDIA_TYPE_AUDIO, -1, -1, &m_pAudioCodec, 0);
    if(m_iAudioStream >= 0)
    {
        m_pAudioCodecContext = m_pFormatContext->streams[m_iAudioStream]->codec;
        avcodec_open2(m_pAudioCodecContext, m_pAudioCodec, nullptr);
    }

    return true;
}
Ejemplo n.º 27
0
static int open_input_file(const char *filename)
{
    int ret;
    AVCodec *decoder = NULL;
    AVStream *video = NULL;

    if ((ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL)) < 0) {
        fprintf(stderr, "Cannot open input file '%s', Error code: %s\n",
                filename, av_err2str(ret));
        return ret;
    }

    if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
        fprintf(stderr, "Cannot find input stream information. Error code: %s\n",
                av_err2str(ret));
        return ret;
    }

    ret = av_find_best_stream(ifmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &decoder, 0);
    if (ret < 0) {
        fprintf(stderr, "Cannot find a video stream in the input file. "
                "Error code: %s\n", av_err2str(ret));
        return ret;
    }
    video_stream = ret;

    if (!(decoder_ctx = avcodec_alloc_context3(decoder)))
        return AVERROR(ENOMEM);

    video = ifmt_ctx->streams[video_stream];
    if ((ret = avcodec_parameters_to_context(decoder_ctx, video->codecpar)) < 0) {
        fprintf(stderr, "avcodec_parameters_to_context error. Error code: %s\n",
                av_err2str(ret));
        return ret;
    }

    decoder_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
    if (!decoder_ctx->hw_device_ctx) {
        fprintf(stderr, "A hardware device reference create failed.\n");
        return AVERROR(ENOMEM);
    }
    decoder_ctx->get_format    = get_vaapi_format;

    if ((ret = avcodec_open2(decoder_ctx, decoder, NULL)) < 0)
        fprintf(stderr, "Failed to open codec for decoding. Error code: %s\n",
                av_err2str(ret));

    return ret;
}
Ejemplo n.º 28
0
int Capture::openCodeContext(AVFormatContext *fmt_ctx, enum AVMediaType type, int & streamIndex)
{
	int ret;
	AVStream *st;
	AVCodecContext *dec_ctx = nullptr;
	AVCodec *dec = nullptr;
	AVDictionary *opts = nullptr;

	ret = av_find_best_stream(fmt_ctx, type, -1, -1, nullptr, 0);
	if (ret < 0)
	{
		sgct::MessageHandler::instance()->print(sgct::MessageHandler::NOTIFY_ERROR, "Could not find %s stream!\n", av_get_media_type_string(type));
		return ret;
	}
	else
	{
		streamIndex = ret;
		st = fmt_ctx->streams[streamIndex];

		/* find decoder for the stream */
		dec_ctx = st->codec;
		dec_ctx->thread_count = 0; //auto number of threads
		dec_ctx->flags |= CODEC_FLAG_LOW_DELAY;
		dec_ctx->flags2 |= CODEC_FLAG2_FAST;

		dec = avcodec_find_decoder(dec_ctx->codec_id);

		if (!dec)
		{
			sgct::MessageHandler::instance()->print(sgct::MessageHandler::NOTIFY_ERROR, "Could not find %s codec!\n", av_get_media_type_string(type));
			return AVERROR(EINVAL);
		}

		/* Init the decoders, with or without reference counting */
#if USE_REF_COUNTER
		av_dict_set(&opts, "refcounted_frames", "1", 0);
#else
		av_dict_set(&opts, "refcounted_frames", "0", 0);
#endif
		if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0)
		{
			sgct::MessageHandler::instance()->print(sgct::MessageHandler::NOTIFY_ERROR, "Could not open %s codec!\n", av_get_media_type_string(type));
			return ret;
		}
	}

	return 0;
}
Ejemplo n.º 29
0
/*
 * Opens a url, reads its stream info, locates its audio stream index, and
 * loads the corresponding codec.
 */
static int
openfile(const char *url)
{
	AVCodec *codec = NULL;
	int nr;

	if (url == NULL)
		return -1;

	nr = avformat_open_input(&avfmt, url, NULL, NULL);
	if (nr < 0) {
		xprintf("(%s:%d) avformat_open_input, error: %s",
		    __FILE__, __LINE__, avstrerror(nr));
		goto error;
	}
	nr = avformat_find_stream_info(avfmt, NULL);
	if (nr < 0) {
		xprintf("(%s:%d) avformat_find_stream, error: %s",
		    __FILE__, __LINE__, avstrerror(nr));
		goto error;
	}
	sti = av_find_best_stream(avfmt, AVMEDIA_TYPE_AUDIO, -1, -1,
	    &codec, 0);
	if (sti < 0) {
		xprintf("(%s:%d) av_find_best_stream, error: %s",
		    __FILE__, __LINE__, avstrerror(nr));
		goto error;
	}
	nr = avcodec_open2(avfmt->streams[sti]->codec, codec, NULL);
	if (nr < 0) {
		xprintf("(%s:%d) avcodec_open2, error: %s",
		    __FILE__, __LINE__, avstrerror(nr));
		goto error;
	}
	duration = (int)(av_q2d(avfmt->streams[sti]->time_base) *
	    (double)avfmt->streams[sti]->duration);
	return 0;
error:
	if (codec)
		avcodec_close(avfmt->streams[sti]->codec);
	if (avfmt) {
		avformat_close_input(&avfmt);
		avfmt = NULL;
	}
	return -1;
}
//------------------------------------------------------------------------------
bool openCodecContext(  AVFormatContext* p_formatContext, AVMediaType p_type, VideoInfo& p_videoInfo, 
                        int& p_outStreamIndex)
{
    AVStream* stream;
    AVCodecContext* decodeCodecContext = NULL;
    AVCodec* decodeCodec = NULL;
    
    // Find the stream
    p_outStreamIndex = av_find_best_stream(p_formatContext, p_type, -1, -1, NULL, 0);
    if (p_outStreamIndex < 0) 
    {
        p_videoInfo.error = "Could not find stream of type: ";
        p_videoInfo.error.append(av_get_media_type_string(p_type));
        return false;
    } 
    else 
    {
        stream = p_formatContext->streams[p_outStreamIndex];
        
        // Find decoder codec
        decodeCodecContext = stream->codec;
        decodeCodec = avcodec_find_decoder(decodeCodecContext->codec_id);
        if (!decodeCodec) 
        {
            p_videoInfo.error = "Failed to find codec: ";
            p_videoInfo.error.append(av_get_media_type_string(p_type));
            return false;
        }
        
//        if (p_type == AVMEDIA_TYPE_AUDIO)
//        {
//            decodeCodecContext->request_sample_fmt = AV_SAMPLE_FMT_S16;
//        }
        
        // Open decodec codec & context
        if (avcodec_open2(decodeCodecContext, decodeCodec, NULL) < 0) 
        {
            p_videoInfo.error = "Failed to open codec: ";
            p_videoInfo.error.append(av_get_media_type_string(p_type));
            return false;
        }
    }
    
    return true;
}