FFmpeg
extract_mvs.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2012 Stefano Sabatini
3  * Copyright (c) 2014 Clément Bœsch
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy
6  * of this software and associated documentation files (the "Software"), to deal
7  * in the Software without restriction, including without limitation the rights
8  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9  * copies of the Software, and to permit persons to whom the Software is
10  * furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21  * THE SOFTWARE.
22  */
23 
24 /**
25  * @file libavcodec motion vectors extraction API usage example
26  * @example extract_mvs.c
27  *
28  * Read from input file, decode video stream and print a motion vectors
29  * representation to stdout.
30  */
31 
33 #include <libavcodec/avcodec.h>
34 #include <libavformat/avformat.h>
35 
39 static const char *src_filename = NULL;
40 
41 static int video_stream_idx = -1;
42 static AVFrame *frame = NULL;
43 static int video_frame_count = 0;
44 
45 static int decode_packet(const AVPacket *pkt)
46 {
48  if (ret < 0) {
49  fprintf(stderr, "Error while sending a packet to the decoder: %s\n", av_err2str(ret));
50  return ret;
51  }
52 
53  while (ret >= 0) {
55  if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
56  break;
57  } else if (ret < 0) {
58  fprintf(stderr, "Error while receiving a frame from the decoder: %s\n", av_err2str(ret));
59  return ret;
60  }
61 
62  if (ret >= 0) {
63  int i;
64  AVFrameSideData *sd;
65 
68  if (sd) {
69  const AVMotionVector *mvs = (const AVMotionVector *)sd->data;
70  for (i = 0; i < sd->size / sizeof(*mvs); i++) {
71  const AVMotionVector *mv = &mvs[i];
72  printf("%d,%2d,%2d,%2d,%4d,%4d,%4d,%4d,0x%"PRIx64",%4d,%4d,%4d\n",
73  video_frame_count, mv->source,
74  mv->w, mv->h, mv->src_x, mv->src_y,
75  mv->dst_x, mv->dst_y, mv->flags,
76  mv->motion_x, mv->motion_y, mv->motion_scale);
77  }
78  }
80  }
81  }
82 
83  return 0;
84 }
85 
87 {
88  int ret;
89  AVStream *st;
91  const AVCodec *dec = NULL;
93 
94  ret = av_find_best_stream(fmt_ctx, type, -1, -1, &dec, 0);
95  if (ret < 0) {
96  fprintf(stderr, "Could not find %s stream in input file '%s'\n",
98  return ret;
99  } else {
100  int stream_idx = ret;
101  st = fmt_ctx->streams[stream_idx];
102 
104  if (!dec_ctx) {
105  fprintf(stderr, "Failed to allocate codec\n");
106  return AVERROR(EINVAL);
107  }
108 
110  if (ret < 0) {
111  fprintf(stderr, "Failed to copy codec parameters to codec context\n");
112  return ret;
113  }
114 
115  /* Init the video decoder */
116  av_dict_set(&opts, "flags2", "+export_mvs", 0);
117  ret = avcodec_open2(dec_ctx, dec, &opts);
118  av_dict_free(&opts);
119  if (ret < 0) {
120  fprintf(stderr, "Failed to open %s codec\n",
122  return ret;
123  }
124 
125  video_stream_idx = stream_idx;
128  }
129 
130  return 0;
131 }
132 
133 int main(int argc, char **argv)
134 {
135  int ret = 0;
136  AVPacket *pkt = NULL;
137 
138  if (argc != 2) {
139  fprintf(stderr, "Usage: %s <video>\n", argv[0]);
140  exit(1);
141  }
142  src_filename = argv[1];
143 
145  fprintf(stderr, "Could not open source file %s\n", src_filename);
146  exit(1);
147  }
148 
150  fprintf(stderr, "Could not find stream information\n");
151  exit(1);
152  }
153 
155 
157 
158  if (!video_stream) {
159  fprintf(stderr, "Could not find video stream in the input, aborting\n");
160  ret = 1;
161  goto end;
162  }
163 
164  frame = av_frame_alloc();
165  if (!frame) {
166  fprintf(stderr, "Could not allocate frame\n");
167  ret = AVERROR(ENOMEM);
168  goto end;
169  }
170 
171  pkt = av_packet_alloc();
172  if (!pkt) {
173  fprintf(stderr, "Could not allocate AVPacket\n");
174  ret = AVERROR(ENOMEM);
175  goto end;
176  }
177 
178  printf("framenum,source,blockw,blockh,srcx,srcy,dstx,dsty,flags,motion_x,motion_y,motion_scale\n");
179 
180  /* read frames from the file */
181  while (av_read_frame(fmt_ctx, pkt) >= 0) {
183  ret = decode_packet(pkt);
185  if (ret < 0)
186  break;
187  }
188 
189  /* flush cached frames */
191 
192 end:
197  return ret < 0;
198 }
frame
static AVFrame * frame
Definition: extract_mvs.c:42
av_packet_unref
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:422
AVCodec
AVCodec.
Definition: codec.h:184
video_stream
static AVStream * video_stream
Definition: extract_mvs.c:38
dec_ctx
static AVCodecContext * dec_ctx
Definition: decode_filter_audio.c:46
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
av_frame_get_side_data
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
Definition: frame.c:682
AVMotionVector
Definition: motion_vector.h:24
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
mv
static const int8_t mv[256][2]
Definition: 4xm.c:80
av_frame_free
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:99
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:330
AVFormatContext::streams
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1172
AVDictionary
Definition: dict.c:32
av_read_frame
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: demux.c:1439
av_packet_free
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition: avpacket.c:73
av_find_best_stream
int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type, int wanted_stream_nb, int related_stream, const AVCodec **decoder_ret, int flags)
Find the "best" stream in the file.
Definition: avformat.c:414
avformat_close_input
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: demux.c:369
type
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf type
Definition: writing_filters.txt:86
av_frame_alloc
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:87
video_frame_count
static int video_frame_count
Definition: extract_mvs.c:43
pkt
AVPacket * pkt
Definition: movenc.c:59
AVFrameSideData::size
size_t size
Definition: frame.h:239
av_dump_format
void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output)
Print detailed information about the input or output format, such as duration, bitrate,...
Definition: dump.c:629
avformat_open_input
int avformat_open_input(AVFormatContext **ps, const char *url, const AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: demux.c:221
motion_vector.h
avcodec_alloc_context3
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:153
main
int main(int argc, char **argv)
Definition: extract_mvs.c:133
avcodec_receive_frame
int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
Return decoded output data from a decoder or encoder (when the AV_CODEC_FLAG_RECON_FRAME flag is used...
Definition: avcodec.c:709
fmt_ctx
static AVFormatContext * fmt_ctx
Definition: extract_mvs.c:36
AVFormatContext
Format I/O context.
Definition: avformat.h:1104
opts
AVDictionary * opts
Definition: movenc.c:50
AVStream::codecpar
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:861
NULL
#define NULL
Definition: coverity.c:32
avcodec_free_context
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
Definition: options.c:168
avcodec_open2
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: avcodec.c:115
video_dec_ctx
static AVCodecContext * video_dec_ctx
Definition: extract_mvs.c:37
open_codec_context
static int open_codec_context(AVFormatContext *fmt_ctx, enum AVMediaType type)
Definition: extract_mvs.c:86
avformat_find_stream_info
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: demux.c:2425
AVMediaType
AVMediaType
Definition: avutil.h:199
av_err2str
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:121
for
for(k=2;k<=8;++k)
Definition: h264pred_template.c:425
AVFrameSideData::data
uint8_t * data
Definition: frame.h:238
printf
printf("static const uint8_t my_array[100] = {\n")
av_packet_alloc
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: avpacket.c:62
av_dict_free
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition: dict.c:223
avcodec_send_packet
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
Supply raw packet data as input to a decoder.
Definition: decode.c:598
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:269
avcodec_parameters_to_context
int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par)
Fill the codec context based on the values from the supplied codec parameters.
Definition: codec_par.c:182
av_frame_unref
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition: frame.c:478
avcodec.h
ret
ret
Definition: filter_design.txt:187
AVStream
Stream structure.
Definition: avformat.h:838
avformat.h
av_get_media_type_string
const char * av_get_media_type_string(enum AVMediaType media_type)
Return a string describing the media_type enum, NULL if media_type is unknown.
Definition: utils.c:28
AVCodecContext
main external API structure.
Definition: avcodec.h:426
src_filename
static const char * src_filename
Definition: extract_mvs.c:39
AVPacket::stream_index
int stream_index
Definition: packet.h:376
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
decode_packet
static int decode_packet(const AVPacket *pkt)
Definition: extract_mvs.c:45
AVFrameSideData
Structure to hold side data for an AVFrame.
Definition: frame.h:236
video_stream_idx
static int video_stream_idx
Definition: extract_mvs.c:41
AVPacket
This structure stores compressed data.
Definition: packet.h:351
av_dict_set
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:86
AV_FRAME_DATA_MOTION_VECTORS
@ AV_FRAME_DATA_MOTION_VECTORS
Motion vectors exported by some codecs (on demand through the export_mvs flag set in the libavcodec A...
Definition: frame.h:97