Example #1
0
static int probe_file(const char *filename)
{
    InputFile ifile;
    int ret, i;

    ret = open_input_file(&ifile, filename);
    if (ret < 0)
        return ret;

    if (do_show_format)
        show_format(&ifile);

    if (do_show_streams) {
        probe_array_header("streams", 0);
        for (i = 0; i < ifile.nb_streams; i++)
            show_stream(&ifile, &ifile.streams[i]);
        probe_array_footer("streams", 0);
    }

    if (do_show_packets)
        show_packets(&ifile);

    close_input_file(&ifile);
    return 0;
}
static Tuple * read_tuple (const gchar * filename, VFSFile * file)
{
    Tuple * tuple = NULL;
    AVFormatContext * ic = open_input_file (filename, file);

    if (ic)
    {
        CodecInfo cinfo;

        if (find_codec (ic, & cinfo))
        {
            tuple = tuple_new_from_filename (filename);

            tuple_set_int (tuple, FIELD_LENGTH, ic->duration / 1000);
            tuple_set_int (tuple, FIELD_BITRATE, ic->bit_rate / 1000);

            if (cinfo.codec->long_name)
                tuple_set_str (tuple, FIELD_CODEC, cinfo.codec->long_name);

            if (ic->metadata)
                read_metadata_dict (tuple, ic->metadata);
            if (cinfo.stream->metadata)
                read_metadata_dict (tuple, cinfo.stream->metadata);
        }

        close_input_file (ic);
    }

    return tuple;
}
Example #3
0
static int
probe_file(const char *filename)
{
	AVFormatContext *c;
	int ret, i;
	AVDictionary *d;
	AVDictionaryEntry *tag;

	if(ret = open_input_file(&c, filename))
		return ret;

	if(c->metadata != NULL)
		d = c->metadata;
	else
		d = c->streams[0]->metadata;

	printf("codec	%s\n", c->iformat->name);
	printf("length	%lld\n", c->duration / AV_TIME_BASE);
	printf("bitrate	%d\n", c->bit_rate);
	tag = av_dict_get(d, "title", NULL, 0);
	printf("title	%s\n", tag != NULL ? tag->value : "");
	tag = av_dict_get(d, "artist", NULL, 0);
	printf("artist	%s\n", tag != NULL ? tag->value : "");
	tag = av_dict_get(d, "album", NULL, 0);
	printf("album	%s\n", tag != NULL ? tag->value : "");

//	for(tag=NULL; (tag = av_dict_get(d, "", tag, AV_DICT_IGNORE_SUFFIX)); )
//		printf("%s	%s\n", tag->key, tag->value);

	av_close_input_file(c);
	return 0;
}
Example #4
0
Processor<sint, sgf2n>::Processor(int thread_num,Data_Files<sint, sgf2n>& DataF,Player& P,
        typename sgf2n::MAC_Check& MC2,typename sint::MAC_Check& MCp,
        Machine<sint, sgf2n>& machine,
        const Program& program)
: ArithmeticProcessor(machine.opts, thread_num),DataF(DataF),P(P),
  MC2(MC2),MCp(MCp),machine(machine),
  Proc2(*this,MC2,DataF.DataF2,P),Procp(*this,MCp,DataF.DataFp,P),
  privateOutput2(Proc2),privateOutputp(Procp),
  external_clients(ExternalClients(P.my_num(), machine.prep_dir_prefix)),
  binary_file_io(Binary_File_IO())
{
  reset(program,0);

  public_input.open(get_filename("Programs/Public-Input/",false).c_str());
  private_input_filename = (get_filename(PREP_DIR "Private-Input-",true));
  private_input.open(private_input_filename.c_str());
  public_output.open(get_filename(PREP_DIR "Public-Output-",true).c_str(), ios_base::out);
  private_output.open(get_filename(PREP_DIR "Private-Output-",true).c_str(), ios_base::out);

  open_input_file(P.my_num(), thread_num);

  secure_prng.ReSeed();

  out.activate(P.my_num() == 0 or machine.opts.interactive);
}
Example #5
0
void no_output_file(char *input_file, struct list_s *list, int reverse)
{
    int fd_in;
    fd_in = open_input_file(input_file);
    read_input(fd_in, list);
    sort(list, reverse);
    print_list(list);
    close(fd_in);
}
Example #6
0
// when both input file and output file are provided.
void general_case(char *input_file, char *output_file, struct list_s *list, int reverse)
{
    int fd_in, fd_out;
    fd_in = open_input_file(input_file);
    fd_out = open_output_file(output_file);
    read_input(fd_in, list);
    sort(list, reverse);
    write_to_file(fd_out, list);
    close(fd_in);
    close(fd_out);
}
Example #7
0
ErrorCode MinizipUtils::archive_stats(const std::string &path,
                                      MinizipUtils::ArchiveStats *stats,
                                      std::vector<std::string> ignore)
{
    assert(stats != nullptr);

    UnzCtx *ctx = open_input_file(path);

    if (!ctx) {
        LOGE("miniunz: Failed to open for reading: %s", path.c_str());
        return ErrorCode::ArchiveReadOpenError;
    }

    uint64_t count = 0;
    uint64_t total_size = 0;
    std::string name;
    unz_file_info64 fi;
    memset(&fi, 0, sizeof(fi));

    int ret = unzGoToFirstFile(ctx->uf);
    if (ret != UNZ_OK) {
        LOGE("miniunz: Failed to move to first file: %s",
             unz_error_string(ret).c_str());
        close_input_file(ctx);
        return ErrorCode::ArchiveReadHeaderError;
    }

    do {
        if (!get_info(ctx->uf, &fi, &name)) {
            close_input_file(ctx);
            return ErrorCode::ArchiveReadHeaderError;
        }

        if (std::find(ignore.begin(), ignore.end(), name) == ignore.end()) {
            ++count;
            total_size += fi.uncompressed_size;
        }
    } while ((ret = unzGoToNextFile(ctx->uf)) == UNZ_OK);

    if (ret != UNZ_END_OF_LIST_OF_FILE) {
        LOGE("miniunz: Finished before EOF: %s",
             unz_error_string(ret).c_str());
        close_input_file(ctx);
        return ErrorCode::ArchiveReadHeaderError;
    }

    close_input_file(ctx);

    stats->files = count;
    stats->total_size = total_size;

    return ErrorCode::NoError;
}
Example #8
0
static int parse_input_file( DLLSPEC *spec )
{
    FILE *input_file = open_input_file( NULL, spec_file_name );
    char *extension = strrchr( spec_file_name, '.' );
    int result;

    spec->src_name = xstrdup( input_file_name );
    if (extension && !strcmp( extension, ".def" ))
        result = parse_def_file( input_file, spec );
    else
        result = parse_spec_file( input_file, spec );
    close_input_file( input_file );
    return result;
}
Example #9
0
int main(int argc, char **argv)
{
    av_register_all();
    avformat_network_init();
    
    AVFormatContext *fmt_ctx;
    const char* input_filename = argv[1];
    int ret = open_input_file(&fmt_ctx, input_filename);
    if (0 == ret)
    {
        printf("format name: %s\n",fmt_ctx->iformat->name);
        close_input_file(&fmt_ctx);
    } 
    avformat_network_deinit();
    return 0;
}
Example #10
0
int main(int argc, char *argv[])
{
	char *tmp_path;	
	
	// Find an untaken tmp path.
	tmp_path = get_tmp_path();
	
	// Save STDIN input to that tmp file.
	save_input_to_tmp(tmp_path);
	
	// Open tmp file in Safari.
	open_input_file(tmp_path);
	
	// Cleanup and exit.
	free(tmp_path);
	return 0;
}
Example #11
0
static int probe_file(const char *filename)
{
    AVFormatContext *fmt_ctx;
    int ret, i;

    if ((ret = open_input_file(&fmt_ctx, filename)))
        return ret;

    if (do_show_streams)
        for (i = 0; i < fmt_ctx->nb_streams; i++)
            show_stream(fmt_ctx, i);

    if (do_show_format)
        show_format(fmt_ctx);

    av_close_input_file(fmt_ctx);
    return 0;
}
void checksum_of_archive(char *file_name, void **csip)
{
    FILE *arc_fp;
    arc_fp = open_input_file(file_name, TRUE);
    if (arc_fp) {
        char buf[1024];
        unsigned int readlen;
        unsigned int buf_sz = sizeof(buf);

        initialize_checksum_info(csip);        
        while((readlen = fread(buf, sizeof(char), buf_sz, arc_fp)) > 0) {
            update_checksum_with_buf(buf, readlen, *csip);
        }
        finalize_checksum_info(*csip);  

        fclose(arc_fp);
    }
}
Example #13
0
int main(int argc, char **argv)
{
    AVFrame *src_frame = av_frame_alloc();
    if (!src_frame) {
        perror("Could not allocate frame");
        return 1;
    }

    avcodec_register_all();
    av_register_all();

    AVPacket packet;
    int ret;
    if ((ret = open_input_file(argv[1])) >= 0)
    {
	/* read all packets */
	while ((ret = av_read_frame(pFormatContext, &packet)) >= 0) {
	  if (packet.stream_index != iAudioStream)
	      continue;
	  avcodec_get_frame_defaults(src_frame);
	  int got_frame = 0;
	  ret = avcodec_decode_audio4(pDecoderContext, src_frame, &got_frame, &packet);
	  if (ret < 0) {
	      av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n");
	      continue;
	  }
	  if (got_frame) {
	      emit_frame(src_frame);
	  }
	  av_free_packet(&packet);
      }
    }
    if (pDecoderContext)
        avcodec_close(pDecoderContext);
    avformat_close_input(&pFormatContext);
    // av_frame_free(&src_frame); // This causes a segfault "double free or corruption (!prev)."
    if (ret < 0 && ret != AVERROR_EOF) {
        char buf[1024];
        av_strerror(ret, buf, sizeof(buf));
        fprintf(stderr, "Error occurred: %s\n", buf);
        return 1;
    }
    return 0;
}
Example #14
0
/* read in the list of exported symbols of an import library */
static int read_import_lib( struct import *imp )
{
    FILE *f;
    int i, ret;
    struct stat stat;
    struct import *prev_imp;
    DLLSPEC *spec = imp->spec;
    int delayed = is_delayed_import( spec->file_name );

    f = open_input_file( NULL, imp->full_name );
    fstat( fileno(f), &stat );
    imp->dev = stat.st_dev;
    imp->ino = stat.st_ino;
    ret = parse_def_file( f, spec );
    close_input_file( f );
    if (!ret) return 0;

    /* check if we already imported that library from a different file */
    if ((prev_imp = is_already_imported( spec->file_name )))
    {
        if (prev_imp->dev != imp->dev || prev_imp->ino != imp->ino)
            fatal_error( "%s and %s have the same export name '%s'\n",
                         prev_imp->full_name, imp->full_name, spec->file_name );
        return 0;  /* the same file was already loaded, ignore this one */
    }

    if (delayed)
    {
        imp->delay = 1;
        nb_delayed++;
    }

    if (spec->nb_entry_points)
    {
        imp->exports = xmalloc( spec->nb_entry_points * sizeof(*imp->exports) );
        for (i = 0; i < spec->nb_entry_points; i++)
            imp->exports[imp->nb_exports++] = &spec->entry_points[i];
        qsort( imp->exports, imp->nb_exports, sizeof(*imp->exports), func_cmp );
    }
    return 1;
}
Example #15
0
int main(int argc, char* argv[]){
  char** ap;
  initialize_syntax();
  ap = argv+1;
  stdout_stream = make_file_output_stream(stdout,"");
  stdin_stream = make_file_input_stream(stdin,NULL);
  output_stream = stdout_stream;
  if ( argc >= 3 && stricmp(*ap,"-prim") == 0 ) {
    CIStream ps;
    ap++;
    ps = open_input_file( *ap, FALSE );
    if ( ps != NULL ) {
      read_patterns(ps, "", FALSE);
      cis_close(ps);
    }
    ap++;
  }
  else initialize_argv_domain();
  do_args(ap);
  return (int)exit_status;
}
Example #16
0
int main ( int argc, char** argv )
{
    FILE* fh;
    byte_t* buf;
    size_t flen;
    class_t cls;
    flags_t flags;
    if ( get_options ( argc, argv, &flags ) )
        return 1;
    if ( ! ( buf = alloc_buffer ( ) ) )
        return 1;
    if ( ! ( fh = open_input_file ( argv [ argc - 1 ] ) ) )
        return 1;
    if ( ! ( flen = load_file ( buf, fh ) ) )
        return 1;
    if ( classify_image ( &cls, buf, flen ) )
        return 1;

    if ( flags.action == ACTION_CONVERT )
        return action_convert ( &cls, buf, flen, argv [ argc - 1 ] );
    else
        return action_print ( &cls );
}
Example #17
0
static int probe_file(const char *filename)
{
    AVFormatContext *fmt_ctx;
    int ret, i;

    if ((ret = open_input_file(&fmt_ctx, filename)))
        return ret;

    if (do_show_format)
        show_format(fmt_ctx);

    if (do_show_streams) {
        probe_array_header("streams", 0);
        for (i = 0; i < fmt_ctx->nb_streams; i++)
            show_stream(fmt_ctx, i);
        probe_array_footer("streams", 0);
    }

    if (do_show_packets)
        show_packets(fmt_ctx);

    close_input_file(&fmt_ctx);
    return 0;
}
/*
** o initialize server socket
** o fstat and open our sending-file
** o block in socket and wait for client
** o sendfile(2), write(2), ...
** o print diagnostic info
*/
void tipc_trans_mode(void)
{
	int connected_fd, file_fd;

	msg(GENTLE, "transmit mode (file: %s  -  hostname: %s)",
		opts.infile, opts.hostname);

	/* check if the transmitted file is present and readable */
	file_fd = open_input_file();
	connected_fd = init_tipc_trans();

	/* fetch sockopt before the first byte  */
	get_sock_opts(connected_fd, &net_stat);

	/* construct and send netsend header to peer */
	meta_exchange_snd(connected_fd, file_fd);

	/* take the transmit start time for diff */
	gettimeofday(&opts.starttime, NULL);

	trans_start(file_fd, connected_fd);

	gettimeofday(&opts.endtime, NULL);
}
Example #19
0
int main(int argc, char **argv)
{
    int ret;
    AVPacket packet = { .data = NULL, .size = 0 };
    AVFrame *frame = NULL;
    enum AVMediaType type;
    unsigned int stream_index;
    unsigned int i;
    int got_frame;
    int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *);

    if (argc != 3)
    {
        av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file> <output file>\n", argv[0]);
        return 1;
    }

    av_register_all();
    avfilter_register_all();

    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = open_output_file(argv[2])) < 0)
        goto end;
    if ((ret = init_filters()) < 0)
        goto end;

    /* read all packets */
    while (1)
    {
        if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
            break;
        stream_index = packet.stream_index;
        type = ifmt_ctx->streams[packet.stream_index]->codec->codec_type;
        av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n",
               stream_index);

        if (filter_ctx[stream_index].filter_graph)
        {
            av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
            frame = av_frame_alloc();
            if (!frame)
            {
                ret = AVERROR(ENOMEM);
                break;
            }
            av_packet_rescale_ts(&packet,
                                 ifmt_ctx->streams[stream_index]->time_base,
                                 ifmt_ctx->streams[stream_index]->codec->time_base);
            dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
                       avcodec_decode_audio4;
            ret = dec_func(ifmt_ctx->streams[stream_index]->codec, frame,
                           &got_frame, &packet);
            if (ret < 0)
            {
                av_frame_free(&frame);
                av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
                break;
            }

            if (got_frame)
            {
                frame->pts = av_frame_get_best_effort_timestamp(frame);
                ret = filter_encode_write_frame(frame, stream_index);
                av_frame_free(&frame);
                if (ret < 0)
                    goto end;
            }
            else
            {
                av_frame_free(&frame);
            }
        }
        else
        {
            /* remux this frame without reencoding */
            av_packet_rescale_ts(&packet,
                                 ifmt_ctx->streams[stream_index]->time_base,
                                 ofmt_ctx->streams[stream_index]->time_base);

            ret = av_interleaved_write_frame(ofmt_ctx, &packet);
            if (ret < 0)
                goto end;
        }
        av_packet_unref(&packet);
    }

    /* flush filters and encoders */
    for (i = 0; i < ifmt_ctx->nb_streams; i++)
    {
        /* flush filter */
        if (!filter_ctx[i].filter_graph)
            continue;
        ret = filter_encode_write_frame(NULL, i);
        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "Flushing filter failed\n");
            goto end;
        }

        /* flush encoder */
        ret = flush_encoder(i);
        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n");
            goto end;
        }
    }

    av_write_trailer(ofmt_ctx);
end:
    av_packet_unref(&packet);
    av_frame_free(&frame);
    for (i = 0; i < ifmt_ctx->nb_streams; i++)
    {
        avcodec_close(ifmt_ctx->streams[i]->codec);
        if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && ofmt_ctx->streams[i]->codec)
            avcodec_close(ofmt_ctx->streams[i]->codec);
        if (filter_ctx && filter_ctx[i].filter_graph)
            avfilter_graph_free(&filter_ctx[i].filter_graph);
    }
    av_free(filter_ctx);
    avformat_close_input(&ifmt_ctx);
    if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
        avio_closep(&ofmt_ctx->pb);
    avformat_free_context(ofmt_ctx);

    if (ret < 0)
        av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));

    return ret ? 1 : 0;
}
Example #20
0
/** Convert an audio file to an AAC file in an MP4 container. */
int compress(int argc, char **argv)
{
    AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
    AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
    SwrContext *resample_context = NULL;
    AVAudioFifo *fifo = NULL;
    int ret = AVERROR_EXIT;

    if (argc < 3) {
        fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
        exit(1);
    }

    const char *input_filename = argv[1];
    const char *output_filename = argv[2];

    /** Register all codecs and formats so that they can be used. */
    av_register_all();
    /** Open the input file for reading. */
    if (open_input_file(input_filename, &input_format_context, &input_codec_context))
        goto cleanup;

    /** Open the output file for writing. */
    if (open_output_file(output_filename, input_codec_context, &output_format_context, &output_codec_context))
        goto cleanup;

    /** Initialize the resampler to be able to convert audio sample formats. */
    if (init_resampler(input_codec_context, output_codec_context, &resample_context))
        goto cleanup;

    /** Initialize the FIFO buffer to store audio samples to be encoded. */
    if (init_fifo(&fifo, output_codec_context))
        goto cleanup;

    /** Write the header of the output file container. */
    if (write_output_file_header(output_format_context))
        goto cleanup;

    /**
     * Loop as long as we have input samples to read or output samples
     * to write; abort as soon as we have neither.
     */
    while (1) {
        /** Use the encoder's desired frame size for processing. */
        const int output_frame_size = output_codec_context->frame_size;
        int finished                = 0;

        /**
         * Make sure that there is one frame worth of samples in the FIFO
         * buffer so that the encoder can do its work.
         * Since the decoder's and the encoder's frame size may differ, we
         * need to FIFO buffer to store as many frames worth of input samples
         * that they make up at least one frame worth of output samples.
         */
        while (av_audio_fifo_size(fifo) < output_frame_size) {
            /**
             * Decode one frame worth of audio samples, convert it to the
             * output sample format and put it into the FIFO buffer.
             */
            if (read_decode_convert_and_store(fifo, input_format_context,
                                              input_codec_context,
                                              output_codec_context,
                                              resample_context, &finished))
                goto cleanup;

            /**
             * If we are at the end of the input file, we continue
             * encoding the remaining audio samples to the output file.
             */
            if (finished)
                break;
        }

        /**
         * If we have enough samples for the encoder, we encode them.
         * At the end of the file, we pass the remaining samples to
         * the encoder.
         */
        while (av_audio_fifo_size(fifo) >= output_frame_size ||
               (finished && av_audio_fifo_size(fifo) > 0))
            /**
             * Take one frame worth of audio samples from the FIFO buffer,
             * encode it and write it to the output file.
             */
            if (load_encode_and_write(fifo, output_format_context, output_codec_context))
                goto cleanup;

        /**
         * If we are at the end of the input file and have encoded
         * all remaining samples, we can exit this loop and finish.
         */
        if (finished) {
            int data_written;
            /** Flush the encoder as it may have delayed frames. */
            do {
                if (encode_audio_frame(NULL, output_format_context, output_codec_context, &data_written))
                    goto cleanup;
            } while (data_written);
            break;
        }
    }

    /** Write the trailer of the output file container. */
    if (write_output_file_trailer(output_format_context))
        goto cleanup;
    ret = 0;

cleanup:
    if (fifo)
        av_audio_fifo_free(fifo);
    swr_free(&resample_context);
    if (output_codec_context)
        avcodec_close(output_codec_context);
    if (output_format_context) {
        avio_closep(&output_format_context->pb);
        avformat_free_context(output_format_context);
    }
    if (input_codec_context)
        avcodec_close(input_codec_context);
    if (input_format_context)
        avformat_close_input(&input_format_context);

    return ret;
}
    /*
     * Class:     com_jpou_meditor_ffmpeg_trans
     * Method:    startTrans
     * Signature: (Ljava/lang/String;Ljava/lang/String;)Z
     */
    JNIEXPORT jboolean JNICALL Java_com_jpou_ffmpeg_Transcoding_startTrans
        (JNIEnv *env, jobject clazz, jstring input, jstring output) {
            int ret;
            AVPacket packet = { .data = NULL, .size = 0 };
            AVFrame *frame = NULL;
            enum AVMediaType type;
            unsigned int stream_index;
            unsigned int i;
            int got_frame;
            int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *);

            char *input_str, *output_str;
            input_str = (*env)->GetStringUTFChars(env, input, 0);
            output_str = (*env)->GetStringUTFChars(env, output, 0);
            LOGI("input_str ~ : %s -------------------", input_str);
            LOGI("output_str ~ : %s -------------------", output_str);


            if ((input == NULL) || (output == NULL)) {
                LOGI("input_str or output_str is null");
                return (jboolean)0;
            }

            av_register_all();
            avfilter_register_all();

            if ((ret = open_input_file(input_str)) < 0) {
                LOGI("open_input_file error");
                goto end;
            }
            if ((ret = open_output_file(output_str)) < 0) {
                LOGI("open_output_file error");
                goto end;
            }
            LOGI("init_filters ----------------");
            if ((ret = init_filters()) < 0) {
                LOGI("init_filters error");
                goto end;
            }

            /* read all packets */
            LOGI("start av_read_frame ----------------");
            while (1) {
                if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
                    break;
                stream_index = packet.stream_index;
                type = ifmt_ctx->streams[packet.stream_index]->codec->codec_type;
                LOGI("Demuxer gave frame of stream_index %u\n",
                        stream_index);

                if (filter_ctx[stream_index].filter_graph) {
                    av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
                    frame = av_frame_alloc();
                    if (!frame) {
                        ret = AVERROR(ENOMEM);
                        break;
                    }
                    av_packet_rescale_ts(&packet,
                            ifmt_ctx->streams[stream_index]->time_base,
                            ifmt_ctx->streams[stream_index]->codec->time_base);
                    dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
                        avcodec_decode_audio4;
                    ret = dec_func(ifmt_ctx->streams[stream_index]->codec, frame,
                            &got_frame, &packet);
                    if (ret < 0) {
                        av_frame_free(&frame);
                        LOGI("Decoding failed\n");
                        break;
                    }

                    if (got_frame) {
                        frame->pts = av_frame_get_best_effort_timestamp(frame);
                        ret = filter_encode_write_frame(frame, stream_index);
                        av_frame_free(&frame);
                        if (ret < 0)
                            goto end;
                    } else {
                        av_frame_free(&frame);
                    }
                } else {
                    /* remux this frame without reencoding */
                    av_packet_rescale_ts(&packet,
                            ifmt_ctx->streams[stream_index]->time_base,
                            ofmt_ctx->streams[stream_index]->time_base);

                    ret = av_interleaved_write_frame(ofmt_ctx, &packet);
                    if (ret < 0)
                        goto end;
                }
                av_free_packet(&packet);
            }

            /* flush filters and encoders */
            for (i = 0; i < ifmt_ctx->nb_streams; i++) {
                /* flush filter */
                if (!filter_ctx[i].filter_graph)
                    continue;
                ret = filter_encode_write_frame(NULL, i);
                if (ret < 0) {
                    LOGI("Flushing filter failed\n");
                    goto end;
                }

                /* flush encoder */
                ret = flush_encoder(i);
                if (ret < 0) {
                    LOGI("Flushing encoder failed\n");
                    goto end;
                }
            }

            av_write_trailer(ofmt_ctx);
            return (jboolean)1;
end:
            av_free_packet(&packet);
            av_frame_free(&frame);
            for (i = 0; i < ifmt_ctx->nb_streams; i++) {
                avcodec_close(ifmt_ctx->streams[i]->codec);
                if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && ofmt_ctx->streams[i]->codec)
                    avcodec_close(ofmt_ctx->streams[i]->codec);
                if (filter_ctx && filter_ctx[i].filter_graph)
                    avfilter_graph_free(&filter_ctx[i].filter_graph);
            }
            av_free(filter_ctx);
            avformat_close_input(&ifmt_ctx);
            if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
                avio_closep(&ofmt_ctx->pb);
            avformat_free_context(ofmt_ctx);

            /**
              if (ret < 0)
              av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));
              */
            return (jboolean)0;

        }

#ifdef __cplusplus
}
Example #22
0
/* Dump out .data and .bss sections into a new executable.  */
void
unexec (const char *new_name, const char *old_name)
{
    file_data in_file, out_file;
    char out_filename[MAX_PATH], in_filename[MAX_PATH], new_name_a[MAX_PATH];
    unsigned long size;
    char *p;
    char *q;

    /* Ignore old_name, and get our actual location from the OS.  */
    if (!GetModuleFileNameA (NULL, in_filename, MAX_PATH))
        abort ();

    /* Can't use dostounix_filename here, since that needs its file name
       argument encoded in UTF-8.  */
    for (p = in_filename; *p; p = CharNextA (p))
        if (*p == '\\')
            *p = '/';

    strcpy (out_filename, in_filename);
    filename_to_ansi (new_name, new_name_a);

    /* Change the base of the output filename to match the requested name.  */
    if ((p = strrchr (out_filename, '/')) == NULL)
        abort ();
    /* The filenames have already been expanded, and will be in Unix
       format, so it is safe to expect an absolute name.  */
    if ((q = strrchr (new_name_a, '/')) == NULL)
        abort ();
    strcpy (p, q);

#ifdef ENABLE_CHECKING
    report_temacs_memory_usage ();
#endif

    /* Make sure that the output filename has the ".exe" extension...patch
       it up if not.  */
    p = out_filename + strlen (out_filename) - 4;
    if (strcmp (p, ".exe"))
        strcat (out_filename, ".exe");

    printf ("Dumping from %s\n", in_filename);
    printf ("          to %s\n", out_filename);

    /* Open the undumped executable file.  */
    if (!open_input_file (&in_file, in_filename))
    {
        printf ("Failed to open %s (%d)...bailing.\n",
                in_filename, GetLastError ());
        exit (1);
    }

    /* Get the interesting section info, like start and size of .bss...  */
    get_section_info (&in_file);

    /* The size of the dumped executable is the size of the original
       executable plus the size of the heap and the size of the .bss section.  */
    size = in_file.size +
           extra_bss_size +
           extra_bss_size_static;
    if (!open_output_file (&out_file, out_filename, size))
    {
        printf ("Failed to open %s (%d)...bailing.\n",
                out_filename, GetLastError ());
        exit (1);
    }

    /* Set the flag (before dumping).  */
    using_dynamic_heap = TRUE;

    copy_executable_and_dump_data (&in_file, &out_file);

    /* Unset it because it is plain wrong to keep it after dumping.
       Malloc can still occur!  */
    using_dynamic_heap = FALSE;

    /* Patch up header fields; profiler is picky about this. */
    {
        PIMAGE_DOS_HEADER dos_header;
        PIMAGE_NT_HEADERS nt_header;
        HANDLE hImagehelp = LoadLibrary ("imagehlp.dll");
        DWORD  headersum;
        DWORD  checksum;

        dos_header = (PIMAGE_DOS_HEADER) out_file.file_base;
        nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);

        nt_header->OptionalHeader.CheckSum = 0;
//    nt_header->FileHeader.TimeDateStamp = time (NULL);
//    dos_header->e_cp = size / 512;
//    nt_header->OptionalHeader.SizeOfImage = size;

        pfnCheckSumMappedFile = (void *) GetProcAddress (hImagehelp, "CheckSumMappedFile");
        if (pfnCheckSumMappedFile)
        {
//	nt_header->FileHeader.TimeDateStamp = time (NULL);
            pfnCheckSumMappedFile (out_file.file_base,
                                   out_file.size,
                                   &headersum,
                                   &checksum);
            nt_header->OptionalHeader.CheckSum = checksum;
        }
        FreeLibrary (hImagehelp);
    }

    close_file_data (&in_file);
    close_file_data (&out_file);
}
Example #23
0
/**
 * 
 * @param orig
 * @param dest
 * @return 
 */
int Transcode::transcode(string orig, string dest, TID3Tags *tags)
{
    AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
    AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
    SwrContext *resample_context = NULL;
    AVAudioFifo *fifo = NULL;
    int ret = AVERROR_EXIT;
    this->pts = 0;

    if (orig.empty() || dest.empty()) {
        fprintf(stderr, "Files to process not especified\n");
        return ret;
    }

    /* Register all codecs and formats so that they can be used. */
    av_register_all();
    /* Open the input file for reading. */
    if (open_input_file(orig.c_str(), &input_format_context,
                        &input_codec_context))
        goto cleanup;
    /* Open the output file for writing. */
    if (open_output_file(dest.c_str(), input_codec_context,
                         &output_format_context, &output_codec_context))
        goto cleanup;
    
    /**Copy the metadata if exist*/
    copy_metadata(input_format_context, output_format_context, tags);
    
    
    /* Initialize the resampler to be able to convert audio sample formats. */
    if (init_resampler(input_codec_context, output_codec_context,
                       &resample_context))
        goto cleanup;
    /* Initialize the FIFO buffer to store audio samples to be encoded. */
    if (init_fifo(&fifo, output_codec_context))
        goto cleanup;
    /* Write the header of the output file container. */
    if (write_output_file_header(output_format_context))
        goto cleanup;

    /* Loop as long as we have input samples to read or output samples
     * to write; abort as soon as we have neither. */
    while (1) {
        /* Use the encoder's desired frame size for processing. */
        const int output_frame_size = output_codec_context->frame_size;
        int finished                = 0;

        /* Make sure that there is one frame worth of samples in the FIFO
         * buffer so that the encoder can do its work.
         * Since the decoder's and the encoder's frame size may differ, we
         * need to FIFO buffer to store as many frames worth of input samples
         * that they make up at least one frame worth of output samples. */
        while (av_audio_fifo_size(fifo) < output_frame_size) {
            /* Decode one frame worth of audio samples, convert it to the
             * output sample format and put it into the FIFO buffer. */
            if (read_decode_convert_and_store(fifo, input_format_context,
                                              input_codec_context,
                                              output_codec_context,
                                              resample_context, &finished))
                goto cleanup;

            /* If we are at the end of the input file, we continue
             * encoding the remaining audio samples to the output file. */
            if (finished)
                break;
        }

        /* If we have enough samples for the encoder, we encode them.
         * At the end of the file, we pass the remaining samples to
         * the encoder. */
        while (av_audio_fifo_size(fifo) >= output_frame_size ||
               (finished && av_audio_fifo_size(fifo) > 0))
            /* Take one frame worth of audio samples from the FIFO buffer,
             * encode it and write it to the output file. */
            if (load_encode_and_write(fifo, output_format_context,
                                      output_codec_context))
                goto cleanup;

        /* If we are at the end of the input file and have encoded
         * all remaining samples, we can exit this loop and finish. */
        if (finished) {
            int data_written;
            /* Flush the encoder as it may have delayed frames. */
            do {
                if (encode_audio_frame(NULL, output_format_context,
                                       output_codec_context, &data_written))
                    goto cleanup;
            } while (data_written);
            break;
        }
    }

    /* Write the trailer of the output file container. */
    if (write_output_file_trailer(output_format_context))
        goto cleanup;
    ret = 0;

cleanup:
    if (fifo)
        av_audio_fifo_free(fifo);
    swr_free(&resample_context);
    if (output_codec_context)
        avcodec_free_context(&output_codec_context);
    if (output_format_context) {
        avio_closep(&output_format_context->pb);
        avformat_free_context(output_format_context);
    }
    if (input_codec_context)
        avcodec_free_context(&input_codec_context);
    if (input_format_context)
        avformat_close_input(&input_format_context);

    return ret;
}
Example #24
0
int
main(int argc, char **argv)
{
    twolame_options *encopts = NULL;
    SNDFILE         *inputfile = NULL;
    FILE            *outputfile = NULL;
    short int       *pcmaudio = NULL;
    int             samples_read = 0;
    unsigned int    frame_count = 0;
    unsigned char   *mp2buffer = NULL;
    int             mp2fill_size = 0;
    int             audioReadSize = 0;


    // Allocate memory for the PCM audio data
    if ((pcmaudio = (short int *) calloc(AUDIOBUFSIZE, sizeof(short int))) == NULL) {
        fprintf(stderr, "Error: pcmaudio memory allocation failed\n");
        exit(ERR_MEM_ALLOC);
    }
    
    // Allocate memory for the encoded MP2 audio data
    if ((mp2buffer = (unsigned char *) calloc(MP2BUFSIZE, sizeof(unsigned char))) == NULL) {
        fprintf(stderr, "Error: mp2buffer memory allocation failed\n");
        exit(ERR_MEM_ALLOC);
    }
    
    // Initialise Encoder Options Structure 
    encopts = twolame_init();
    if (encopts == NULL) {
        fprintf(stderr, "Error: initializing libtwolame encoder failed.\n");
        exit(ERR_MEM_ALLOC);
    }

    
    // Get options and parameters from the command line
    parse_args(argc, argv, encopts);


    // Open the input file
    inputfile = open_input_file( inputfilename );
    twolame_set_num_channels( encopts, sfinfo.channels );
    twolame_set_in_samplerate( encopts, sfinfo.samplerate );
        
    // Open the output file
    outputfile = open_output_file( outputfilename );
    
    // display file settings
	print_file_config( inputfile, twolame_get_verbosity(encopts) );

    // initialise twolame with this set of options
    if (twolame_init_params( encopts ) != 0) {
        fprintf(stderr, "Error: configuring libtwolame encoder failed.\n");
        exit(ERR_INVALID_PARAM);
    }

    // display encoder settings
	twolame_print_config( encopts );


	// Only encode a single frame of mpeg audio ?
    if (single_frame_mode) audioReadSize = 1152;
    else audioReadSize = AUDIOBUFSIZE;


    // Now do the reading/encoding/writing
    while ((samples_read = sf_read_short( inputfile, pcmaudio, audioReadSize )) > 0) {
        int bytes_out = 0;
        
        // Force byte swapping if requested
        if (byteswap) {
			int i;
			for (i = 0; i<samples_read; i++) {
				short tmp = pcmaudio[i];
				char *src = (char*)&tmp;
				char *dst = (char*)&pcmaudio[i];
				dst[0] = src[1];
				dst[1] = src[0];
			}
        }

		// Calculate the number of samples we have (per channel)
        samples_read /= sfinfo.channels;

        // Do swapping of left and right channels if requested
        if (channelswap && sfinfo.channels == 2) {
        	int i;
        	for(i=0; i<samples_read; i++) {
        		short tmp = pcmaudio[(2*i)];
        		pcmaudio[(2*i)] = pcmaudio[(2*i)+1];
        		pcmaudio[(2*i)+1] = tmp;
        	}
        }
        
        // Encode the audio to MP2
        mp2fill_size = twolame_encode_buffer_interleaved( encopts, pcmaudio, samples_read, mp2buffer, MP2BUFSIZE);
        
        // Stop if we don't have any bytes (probably don't have enough audio for a full frame of mpeg audio)
        if (mp2fill_size==0) break;
        if (mp2fill_size<0) {
            fprintf(stderr,"error while encoding audio: %d\n", mp2fill_size);
            exit(ERR_WRITING_OUTPUT);
        }

        // Write the encoded audio out
        bytes_out = fwrite(mp2buffer, sizeof(unsigned char), mp2fill_size, outputfile);
        if (bytes_out<=0) {
            perror("error while writing to output file");
            exit(ERR_WRITING_OUTPUT);
        }
        
        // Only single frame ?
        if (single_frame_mode) break;
        
        // Display Progress
        frame_count += (samples_read / 1152);
        if (twolame_get_verbosity(encopts)>0) {
        	fprintf(stderr, "[%04i", frame_count);
        	//fprintf(stderr, "/%04i", (int)(sfinfo.frames / sfinfo.channels  / 1152));
        	fprintf(stderr, "]\r");
        	fflush(stderr);
        }
    }

    //
    // flush any remaining audio. (don't send any new audio data) There
    // should only ever be a max of 1 frame on a flush. There may be zero
    // frames if the audio data was an exact multiple of 1152
    //
    mp2fill_size = twolame_encode_flush( encopts, mp2buffer, MP2BUFSIZE);
    if (mp2fill_size>0) {
        int bytes_out = fwrite(mp2buffer, sizeof(unsigned char), mp2fill_size, outputfile);
        if (bytes_out<=0) {
            perror("error while writing to output file");
            exit(ERR_WRITING_OUTPUT);
        }
    }
    
 	if (twolame_get_verbosity(encopts)>1) {
	    fprintf(stderr, "\nEncoding Finished.\n");
	}

    // Close input and output files
    sf_close( inputfile );
    fclose( outputfile );

	// Close the libtwolame encoder
    twolame_close(&encopts);
    
    
	// Free up memory
	free(pcmaudio);
	free(mp2buffer);


	
    return (ERR_NO_ERROR);
}
Example #25
0
int main(int argc, char **argv)
{
    //curses
    int color_pair;
    if(initscr() == NULL){
        fprintf(stderr, "init failure\n");
        exit(EXIT_FAILURE);
    }
    /* start_colorは色属性を使用するときは最初に必ず実行する.
       initscrの直後に実行するのがよい習慣らしい. */
    if(has_colors() == FALSE || start_color() == ERR){
        endwin();
        fprintf(stderr, "This term seems not to having Color\n");
        exit(EXIT_FAILURE);
    }

    if(signal(SIGINT, sig_handler) == SIG_ERR ||
            signal(SIGQUIT, sig_handler) == SIG_ERR){
        fprintf(stderr, "signal failure\n");
        exit(EXIT_FAILURE);
    }
    curs_set(0);

    /* 色のペアを作る */
    color_pair = 1;
    for(color_pair = 1; color_pair < 256; color_pair++){
        init_pair(color_pair, color_pair, color_pair);
    }

    refresh();

    char filter_descr[10000];
    int w, h;
    w = 80;//COLS;
    h = 25;//LINES;
    bak = malloc(sizeof (int) * LINES*COLS+1);
        sprintf(filter_descr, "scale=%d:%d", w, h);



    int ret;
    AVPacket packet;
    AVFrame frame;
    int got_frame;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s file\n", argv[0]);
        exit(1);
    }

    avcodec_register_all();
    av_register_all();
    avfilter_register_all();

    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = init_filters(filter_descr)) < 0)
        goto end;

    /* read all packets */
    while (1) {
        AVFilterBufferRef *picref;
        if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
            break;

        if (packet.stream_index == video_stream_index) {
            avcodec_get_frame_defaults(&frame);
            got_frame = 0;
            ret = avcodec_decode_video2(dec_ctx, &frame, &got_frame, &packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding video\n");
                break;
            }

            if (got_frame) {
                frame.pts = av_frame_get_best_effort_timestamp(&frame);

                /* push the decoded frame into the filtergraph */
                if (av_buffersrc_add_frame(buffersrc_ctx, &frame, 0) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
                    break;
                }

                /* pull filtered pictures from the filtergraph */
                while (repeat_flag) {
                    ret = av_buffersink_get_buffer_ref(buffersink_ctx, &picref, 0);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    if (ret < 0)
                        goto end;

                    if (picref) {
                        display_picref(picref, buffersink_ctx->inputs[0]->time_base);
                        avfilter_unref_bufferp(&picref);
                    }
                }
            }
        }
        av_free_packet(&packet);
    }
end:
    endwin();
    avfilter_graph_free(&filter_graph);
    if (dec_ctx)
        avcodec_close(dec_ctx);
    avformat_close_input(&fmt_ctx);

    if (ret < 0 && ret != AVERROR_EOF) {
        char buf[1024];
        av_strerror(ret, buf, sizeof(buf));
        fprintf(stderr, "Error occurred: %s\n", buf);
        exit(1);
    }

    exit(0);
}
Example #26
0
int
main(int argc, char * argv[], char * envp[])
{
  ParseDelimitedText *  parser;
  int                   input_file_fd;
  char                  input_file_buffer[PDT_BLK_SIZE];
  size_t                bytes_read;

  /* Parse command line parameters */
  set_params(argc, argv);
  
  /* Load the format file */
  printf("Reading format file %s\n", format_file->string);
  format = new_PDTFormat();
  format->m->read_file(format, format_file->string, format_file->length);
  format->columns->m->reset_each(format->columns);

  /* Open the input file */
  input_file_fd = open_input_file();
  parser = new_ParseDelimitedText(0);

  /* Set the parser's options */
  parser->m->apply_format(parser, format);
  parser->m->set_block_size(parser, PDT_BLK_SIZE);
  parser->m->set_field_callback(parser, header_field);
  parser->m->set_record_callback(parser, header_record);

  /* Initialize Globals */
  header_fields = new_Array();
  header_fields->auto_free = null_String->m->Array_free;
  valid = 1;
  field_count = 0;

  /* Validate the file header */
  while(parser->stop == 0
        && (bytes_read = read(input_file_fd, input_file_buffer, PDT_BLK_SIZE)) != 0) {
    parser->m->parse(parser, input_file_buffer, bytes_read);
  }
  parser->m->finish(parser);
  valid = validate_header();

  /* Validate the file body */
  if(valid == 1) {
    parser->m->set_field_callback(parser, field);
    parser->m->set_record_callback(parser, record);
    parser->stop = 0;
    while(parser->stop == 0
          && (bytes_read = read(input_file_fd, input_file_buffer, PDT_BLK_SIZE)) != 0) {
      parser->m->parse(parser, input_file_buffer, bytes_read);
    }
    parser->m->finish(parser);
  }

  /* Cleanup */
  close(input_file_fd);
  parser->m->free(parser);
  header_fields->m->free(header_fields);
  format->m->free(format);

  return (valid) ? SHELL_TRUE : SHELL_FALSE;
}
Example #27
0
int main(int argc, char **argv)
{
    int ret;
    AVPacket packet;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();
    int got_frame;

    if (!frame || !filt_frame) {
        perror("Could not allocate frame");
        exit(1);
    }
    if (argc != 2) {
        fprintf(stderr, "Usage: %s file\n", argv[0]);
        exit(1);
    }

    avcodec_register_all();
    av_register_all();
    avfilter_register_all();

    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = init_filters(filter_descr)) < 0)
        goto end;

    /* read all packets */
    while (1) {
        if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
            break;

        if (packet.stream_index == video_stream_index) {
            avcodec_get_frame_defaults(frame);
            got_frame = 0;
            ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, &packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding video\n");
                break;
            }

            if (got_frame) {
                frame->pts = av_frame_get_best_effort_timestamp(frame);

                /* push the decoded frame into the filtergraph */
                if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
                    break;
                }

                /* pull filtered frames from the filtergraph */
                while (1) {
                    ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    if (ret < 0)
                        goto end;
                    display_frame(filt_frame, buffersink_ctx->inputs[0]->time_base);
                    av_frame_unref(filt_frame);
                }
                av_frame_unref(frame);
            }
        }
        av_free_packet(&packet);
    }
end:
    avfilter_graph_free(&filter_graph);
    if (dec_ctx)
        avcodec_close(dec_ctx);
    avformat_close_input(&fmt_ctx);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);

    if (ret < 0 && ret != AVERROR_EOF) {
        char buf[1024];
        av_strerror(ret, buf, sizeof(buf));
        fprintf(stderr, "Error occurred: %s\n", buf);
        exit(1);
    }

    exit(0);
}
Example #28
0
int main(int argc, char **argv)
{
    int ret;
    AVPacket packet;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();

    if (!frame || !filt_frame) {
        perror("Could not allocate frame");
        exit(1);
    }
    if (argc != 2) {
        fprintf(stderr, "Usage: %s file | %s\n", argv[0], player);
        exit(1);
    }

    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = init_filters(filter_descr)) < 0)
        goto end;

    /* read all packets */
    while (1) {
        if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
            break;

        if (packet.stream_index == audio_stream_index) {
            ret = avcodec_send_packet(dec_ctx, &packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error while sending a packet to the decoder\n");
                break;
            }

            while (ret >= 0) {
                ret = avcodec_receive_frame(dec_ctx, frame);
                if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
                    break;
                } else if (ret < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error while receiving a frame from the decoder\n");
                    goto end;
                }

                if (ret >= 0) {
                    /* push the audio data from decoded frame into the filtergraph */
                    if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
                        av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n");
                        break;
                    }

                    /* pull filtered audio from the filtergraph */
                    while (1) {
                        ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
                        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                            break;
                        if (ret < 0)
                            goto end;
                        print_frame(filt_frame);
                        av_frame_unref(filt_frame);
                    }
                    av_frame_unref(frame);
                }
            }
        }
        av_packet_unref(&packet);
    }
end:
    avfilter_graph_free(&filter_graph);
    avcodec_free_context(&dec_ctx);
    avformat_close_input(&fmt_ctx);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);

    if (ret < 0 && ret != AVERROR_EOF) {
        fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));
        exit(1);
    }

    exit(0);
}
Example #29
0
int main(void)
{

	int frame = 0, ret = 0, got_picture = 0, frameFinished = 0, videoStream = 0, check_yuv = 0;
	int frame_size = 0, bitrate = 0;
	int streamIdx = 0;
	unsigned i=0;
	enum AVMediaType mediaType;
	struct SwsContext *sws_ctx = NULL;
	AVStream *video_st = NULL;
	AVCodecContext    *pCodecCtx = NULL, *ctxEncode = NULL;
	AVFrame           *pFrame = NULL;
	AVPacket          input_pkt, output_pkt;

	check_yuv = check_file();

	// Register all formats and codecs
	av_register_all();

	if (open_input_file(check_yuv) < 0) exit(1);
	if (open_output_file() < 0) exit(1);

	init_parameter(&input_pkt, &output_pkt); //init parameter function
	pictureEncoded_init();

	// initialize SWS context for software scaling
	sws_ctx = sws_getContext(inFmtCtx->streams[streamIdx]->codec->width, inFmtCtx->streams[streamIdx]->codec->height, inFmtCtx->streams[streamIdx]->codec->pix_fmt, clip_width, clip_height, PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL);

	while (av_read_frame(inFmtCtx, &input_pkt) >= 0) {

		streamIdx = input_pkt.stream_index;
		mediaType = inFmtCtx->streams[streamIdx]->codec->codec_type;

		av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n", streamIdx);
		av_log(NULL, AV_LOG_DEBUG, "Going to reencode \n");

		pFrame = av_frame_alloc();

		if (!pFrame)
		{
			ret = AVERROR(ENOMEM);
			break;
		}

		av_packet_rescale_ts(&input_pkt, inFmtCtx->streams[videoStream]->time_base, inFmtCtx->streams[streamIdx]->codec->time_base);


		if (mediaType == AVMEDIA_TYPE_VIDEO){


			ret = avcodec_decode_video2(inFmtCtx->streams[streamIdx]->codec, pFrame, &frameFinished, &input_pkt); 		// Decode video frame (input_pkt-> pFrame)


			if (ret < 0)
			{
				av_frame_free(&pFrame);
				av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
				break;
			}

		
		if (frameFinished){

			frame_num++;

			sws_scale(sws_ctx, (const uint8_t * const *)pFrame->data, pFrame->linesize, 0, clip_height, pictureEncoded->data, pictureEncoded->linesize);

			pictureEncoded->pts = av_frame_get_best_effort_timestamp(pFrame);

			//pictureEncoded-> output_pkt
			//avcodec_encode_video2(ctxEncode, &output_pkt, pictureEncoded, &got_picture);
			avcodec_encode_video2(ofmt_ctx->streams[streamIdx]->codec, &output_pkt, pictureEncoded, &got_picture);

			av_frame_free(&pFrame);

			//if the function is working
			if (got_picture){

				printf("Encoding %d \n", frame_use);

				frame_use++;
				

				av_packet_rescale_ts(&output_pkt, ofmt_ctx->streams[streamIdx]->codec->time_base, ofmt_ctx->streams[streamIdx]->time_base);

				//av_packet_rescale_ts(&output_pkt, ctxEncode->time_base, video_st->time_base);

				ret = av_interleaved_write_frame(ofmt_ctx, &output_pkt);

				if (ret < 0) {
					fprintf(stderr, "Error muxing packet\n");
					break;
				}
			}
		}

		av_free_packet(&input_pkt);
		av_free_packet(&output_pkt);

		}

	}

	//flush encoders
	for (i = 0; i < inFmtCtx->nb_streams; i++)
	{
		if (inFmtCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
			
			ret = flush_encoder(i);
			if (ret < 0)
			{
				av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n");
				exit(1);
			}
		}
	}

	printf("\n\n total frame_num : %d , frame_encode:  %d \n", frame_num-1, frame_use-1);


	/* Write the trailer, if any. The trailer must be written before you
	* close the CodecContexts open when you wrote the header; otherwise
	* av_write_trailer() may try to use memory that was freed on
	* av_codec_close(). */
	av_write_trailer(ofmt_ctx);

	// Free the YUV frame
	av_frame_free(&pFrame);
	av_frame_free(&pictureEncoded);

	// Close the codecs
	//avcodec_close(pCodecCtx);

	// Close the video file
	avformat_close_input(&inFmtCtx);
	//avcodec_close(ctxEncode);

	return 0;
}
Example #30
0
int main(int argc, char **argv)
{
    int ret;
    AVPacket packet0, packet;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();
    int got_frame;

    if (!frame || !filt_frame) {
        perror("Could not allocate frame");
        exit(1);
    }
    if (argc != 2) {
        fprintf(stderr, "Usage: %s file | %s\n", argv[0], player);
        exit(1);
    }

    avcodec_register_all();
    av_register_all();
    avfilter_register_all();

    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = init_filters(filter_descr)) < 0)
        goto end;

    /* read all packets */
    packet0.data = NULL;
    packet.data = NULL;
    while (1) {
        if (!packet0.data) {
            if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
                break;
            packet0 = packet;
        }

        if (packet.stream_index == audio_stream_index) {
            got_frame = 0;
            ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, &packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n");
                continue;
            }
            packet.size -= ret;
            packet.data += ret;

            if (got_frame) {
                /* push the audio data from decoded frame into the filtergraph */
                if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n");
                    break;
                }

                /* pull filtered audio from the filtergraph */
                while (1) {
                    ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    if (ret < 0)
                        goto end;
                    print_frame(filt_frame);
                    av_frame_unref(filt_frame);
                }
            }

            if (packet.size <= 0)
                av_free_packet(&packet0);
        } else {
            /* discard non-wanted packets */
            av_free_packet(&packet0);
        }
    }
end:
    avfilter_graph_free(&filter_graph);
    avcodec_close(dec_ctx);
    avformat_close_input(&fmt_ctx);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);

    if (ret < 0 && ret != AVERROR_EOF) {
        fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));
        exit(1);
    }

    exit(0);
}