1 #include "libavformat/avformat.h"
2 #include "libavcodec/avcodec.h"
3 #include "libswscale/swscale.h"
6 struct SwsContext *resample_ctx;
8 AVFrame resampled_frame;
11 int codec_open(AVFormatContext *ctx)
16 for (i = 0; i < ctx->nb_streams; i++) {
17 codec = avcodec_find_decoder(ctx->streams[i]->codec->codec_id);
19 fprintf(stderr, "Cannot find codec %d for input stream %d\n",
20 ctx->streams[i]->codec->codec_id, i);
23 res = avcodec_open(ctx->streams[i]->codec, codec);
25 fprintf(stderr, "Cannot open codec for input stream %d\n", i);
34 int out_codec_open(AVFormatContext *ctx)
39 for (i = 0; i < ctx->nb_streams; i++) {
40 codec = avcodec_find_encoder(ctx->streams[i]->codec->codec_id);
42 fprintf(stderr, "Cannot find codec %d for output stream %d\n",
43 ctx->streams[i]->codec->codec_id, i);
46 res = avcodec_open(ctx->streams[i]->codec, codec);
48 fprintf(stderr, "Cannot open codec for input stream %d\n", i);
58 AVFrame *pkt_decode(AVFormatContext *ctx, AVPacket *pkt)
63 avcodec_get_frame_defaults(&frame);
64 res = avcodec_decode_video(ctx->streams[pkt->stream_index]->codec,
65 &frame, &got, pkt->data, pkt->size);
72 struct resample_data *r;
74 r = ctx->streams[pkt->stream_index]->codec->opaque;
76 sws_scale(r->resample_ctx, frame.data, frame.linesize, 0,
77 ctx->streams[pkt->stream_index]->codec->height,
78 r->resampled_frame.data, r->resampled_frame.linesize);
79 res = &r->resampled_frame;
90 int codec_connect(AVCodecContext *ic, AVCodecContext *oc)
92 struct resample_data *r;
94 if ((ic->width == oc->width) && (ic->height == oc->height) && (ic->pix_fmt == oc->pix_fmt)) {
98 r = av_malloc(sizeof(struct resample_data));
99 r->resample_ctx = sws_getContext(ic->width, ic->height, ic->pix_fmt,
100 oc->width, oc->height, oc->pix_fmt,
101 SWS_BICUBIC, NULL, NULL, NULL);
102 if (r->resample_ctx == NULL) {
107 avcodec_get_frame_defaults(&r->resampled_frame);
108 avpicture_alloc((AVPicture*)&r->resampled_frame,
109 oc->pix_fmt, oc->width, oc->height);
115 AVPacket *pkt_encode(AVFormatContext *ctx, AVFrame *frame)
117 AVCodecContext *c = ctx->streams[0]->codec;
121 pkt.size = 256 * 1024;
122 if (pkt.data == NULL) {
123 pkt.data = av_malloc(pkt.size);
125 res = avcodec_encode_video(c, pkt.data, pkt.size, frame);
126 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
127 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, ctx->streams[0]->time_base);