2 * Copyright (c) 2008 Luca Abeni
4 * This is free software; see GPL.txt
6 #include "libavformat/avformat.h"
7 #include "libavcodec/avcodec.h"
8 #include "libswscale/swscale.h"
10 struct resample_data {
11 struct SwsContext *resample_ctx;
13 AVFrame resampled_frame;
16 int codec_open(AVFormatContext *ctx)
21 for (i = 0; i < ctx->nb_streams; i++) {
22 codec = avcodec_find_decoder(ctx->streams[i]->codec->codec_id);
24 fprintf(stderr, "Cannot find codec %d for input stream %d\n",
25 ctx->streams[i]->codec->codec_id, i);
28 res = avcodec_open(ctx->streams[i]->codec, codec);
30 fprintf(stderr, "Cannot open codec for input stream %d\n", i);
39 int out_codec_open(AVFormatContext *ctx)
44 for (i = 0; i < ctx->nb_streams; i++) {
45 codec = avcodec_find_encoder(ctx->streams[i]->codec->codec_id);
47 fprintf(stderr, "Cannot find codec %d for output stream %d\n",
48 ctx->streams[i]->codec->codec_id, i);
51 res = avcodec_open(ctx->streams[i]->codec, codec);
53 fprintf(stderr, "Cannot open codec for input stream %d\n", i);
63 AVFrame *pkt_decode(AVFormatContext *ctx, AVPacket *pkt)
68 avcodec_get_frame_defaults(&frame);
69 res = avcodec_decode_video(ctx->streams[pkt->stream_index]->codec,
70 &frame, &got, pkt->data, pkt->size);
77 struct resample_data *r;
79 r = ctx->streams[pkt->stream_index]->codec->opaque;
81 sws_scale(r->resample_ctx, frame.data, frame.linesize, 0,
82 ctx->streams[pkt->stream_index]->codec->height,
83 r->resampled_frame.data, r->resampled_frame.linesize);
84 res = &r->resampled_frame;
95 int codec_connect(AVCodecContext *ic, AVCodecContext *oc)
97 struct resample_data *r;
99 if ((ic->width == oc->width) && (ic->height == oc->height) && (ic->pix_fmt == oc->pix_fmt)) {
103 r = av_malloc(sizeof(struct resample_data));
104 r->resample_ctx = sws_getContext(ic->width, ic->height, ic->pix_fmt,
105 oc->width, oc->height, oc->pix_fmt,
106 SWS_BICUBIC, NULL, NULL, NULL);
107 if (r->resample_ctx == NULL) {
112 avcodec_get_frame_defaults(&r->resampled_frame);
113 avpicture_alloc((AVPicture*)&r->resampled_frame,
114 oc->pix_fmt, oc->width, oc->height);
120 AVPacket *pkt_encode(AVFormatContext *ctx, AVFrame *frame)
122 AVCodecContext *c = ctx->streams[0]->codec;
126 pkt.size = 256 * 1024;
127 if (pkt.data == NULL) {
128 pkt.data = av_malloc(pkt.size);
130 res = avcodec_encode_video(c, pkt.data, pkt.size, frame);
131 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
132 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, ctx->streams[0]->time_base);