FFmpeg
target_enc_fuzzer.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2024 Michael Niedermayer <michael-ffmpeg@niedermayer.cc>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  *
20  * Based on target_dec_fuzzer
21  */
22 
23 #include "config.h"
24 #include "libavutil/avassert.h"
25 #include "libavutil/avstring.h"
26 #include "libavutil/cpu.h"
27 #include "libavutil/imgutils.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/mem.h"
30 
31 #include "libavcodec/avcodec.h"
32 #include "libavcodec/bytestream.h"
34 #include "libavformat/avformat.h"
35 
36 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);
37 
38 extern const FFCodec * codec_list[];
39 
40 static void error(const char *err)
41 {
42  fprintf(stderr, "%s", err);
43  exit(1);
44 }
45 
46 static const FFCodec *c = NULL;
47 
48 // Ensure we don't loop forever
49 const uint32_t maxiteration = 8096;
50 
51 
52 static int encode(AVCodecContext *enc_ctx, AVFrame *frame, AVPacket *pkt)
53 {
54  int ret;
55 
56  ret = avcodec_send_frame(enc_ctx, frame);
57  if (ret < 0)
58  return ret;
59 
60  while (ret >= 0) {
61  ret = avcodec_receive_packet(enc_ctx, pkt);
62  if (ret == AVERROR(EAGAIN)) {
63  return 0;
64  } else if (ret < 0) {
65  return ret;
66  }
67 
69  }
70  av_assert0(0);
71 }
72 
73 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
74  uint64_t maxpixels_per_frame = 512 * 512;
75  uint64_t maxpixels;
76 
77  const uint8_t *end = data + size;
78  uint32_t it = 0;
79  uint64_t nb_samples = 0;
81  uint64_t ec_pixels = 0;
82 
83  if (!c) {
84 #define ENCODER_SYMBOL0(CODEC) ff_##CODEC##_encoder
85 #define ENCODER_SYMBOL(CODEC) ENCODER_SYMBOL0(CODEC)
86  extern FFCodec ENCODER_SYMBOL(FFMPEG_ENCODER);
87  codec_list[0] = &ENCODER_SYMBOL(FFMPEG_ENCODER);
88 
89  c = &ENCODER_SYMBOL(FFMPEG_ENCODER);
91  }
92 
93  if (c->p.type != AVMEDIA_TYPE_VIDEO)
94  return 0;
95 
96  maxpixels = maxpixels_per_frame * maxiteration;
97  switch (c->p.id) {
98  case AV_CODEC_ID_A64_MULTI: maxpixels /= 65536; break;
99  case AV_CODEC_ID_A64_MULTI5: maxpixels /= 65536; break;
100  }
101 
102  maxpixels_per_frame = FFMIN(maxpixels_per_frame , maxpixels);
103 
105  if (!ctx)
106  error("Failed memory allocation");
107 
108  if (ctx->max_pixels == 0 || ctx->max_pixels > maxpixels_per_frame)
109  ctx->max_pixels = maxpixels_per_frame; //To reduce false positive OOM and hangs
110 
111  ctx->pix_fmt = AV_PIX_FMT_YUV420P;
112  if (size > 1024) {
113  GetByteContext gbc;
114  int flags;
115  int64_t flags64;
116 
117  size -= 1024;
118  bytestream2_init(&gbc, data + size, 1024);
119  ctx->width = bytestream2_get_le32(&gbc) & 0xFFFF;
120  ctx->height = bytestream2_get_le32(&gbc) & 0xFFFF;
121  ctx->bit_rate = bytestream2_get_le64(&gbc);
122  ctx->gop_size = bytestream2_get_le32(&gbc) & 0x7FFFFFFF;
123  ctx->max_b_frames = bytestream2_get_le32(&gbc) & 0x7FFFFFFF;
124  ctx->time_base.num = bytestream2_get_le32(&gbc) & 0x7FFFFFFF;
125  ctx->time_base.den = bytestream2_get_le32(&gbc) & 0x7FFFFFFF;
126  ctx->framerate.num = bytestream2_get_le32(&gbc) & 0x7FFFFFFF;
127  ctx->framerate.den = bytestream2_get_le32(&gbc) & 0x7FFFFFFF;
128 
129  flags = bytestream2_get_byte(&gbc);
130  if (flags & 2)
132 
133  if (flags & 0x40)
135 
136  flags64 = bytestream2_get_le64(&gbc);
137 
138  if (c->p.pix_fmts) {
139  int npixfmts = 0;
140  while (c->p.pix_fmts[npixfmts++] != AV_PIX_FMT_NONE)
141  ;
142  ctx->pix_fmt = c->p.pix_fmts[bytestream2_get_byte(&gbc) % npixfmts];
143  }
144 
145  switch (c->p.id) {
146  case AV_CODEC_ID_FFV1:{
147  int coder = bytestream2_get_byte(&gbc)&3;
148  if (coder == 3) coder = -2;
149  av_dict_set_int(&opts, "coder", coder, 0);
150  av_dict_set_int(&opts, "context", bytestream2_get_byte(&gbc)&1, 0);
151  av_dict_set_int(&opts, "slicecrc", bytestream2_get_byte(&gbc)&1, 0);
152  break;}
153  }
154  }
155  if (ctx->width == 0 || av_image_check_size(ctx->width, ctx->height, 0, ctx))
156  ctx->width = ctx->height = 64;
157 
158  int res = avcodec_open2(ctx, &c->p, &opts);
159  if (res < 0) {
161  av_dict_free(&opts);
162  return 0; // Failure of avcodec_open2() does not imply that a issue was found
163  }
164 
165 
167  AVPacket *avpkt = av_packet_alloc();
168  if (!frame || !avpkt)
169  error("Failed memory allocation");
170 
171  frame->format = ctx->pix_fmt;
172  frame->width = ctx->width;
173  frame->height = ctx->height;
174 
175  while (data < end && it < maxiteration) {
176  ec_pixels += (ctx->width + 32LL) * (ctx->height + 32LL);
177  if (ec_pixels > maxpixels)
178  goto maximums_reached;
179 
180  res = av_frame_get_buffer(frame, 0);
181  if (res < 0)
182  error("Failed av_frame_get_buffer");
183 
184  for (int i=0; i<FF_ARRAY_ELEMS(frame->buf); i++) {
185  if (frame->buf[i]) {
186  int buf_size = FFMIN(end-data, frame->buf[i]->size);
187  memcpy(frame->buf[i]->data, data, buf_size);
188  memset(frame->buf[i]->data + buf_size, 0, frame->buf[i]->size - buf_size);
189  data += buf_size;
190  }
191  }
192 
193  frame->pts = nb_samples;
194 
195  res = encode(ctx, frame, avpkt);
196  if (res < 0)
197  break;
198  it++;
199  for (int i=0; i<FF_ARRAY_ELEMS(frame->buf); i++)
200  av_buffer_unref(&frame->buf[i]);
201 
202  av_packet_unref(avpkt);
203  }
204 maximums_reached:
205  encode(ctx, NULL, avpkt);
206  av_packet_unref(avpkt);
207 
208 // fprintf(stderr, "frames encoded: %"PRId64", iterations: %d\n", nb_samples , it);
209 
212  av_packet_free(&avpkt);
213  av_dict_free(&opts);
214  return 0;
215 }
av_packet_unref
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: packet.c:429
av_force_cpu_flags
void av_force_cpu_flags(int arg)
Disables cpu detection and forces the specified flags.
Definition: cpu.c:79
avcodec_receive_packet
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
Read encoded data from the encoder.
Definition: encode.c:541
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_buffer
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
Definition: frame.c:292
GetByteContext
Definition: bytestream.h:33
AV_LOG_PANIC
#define AV_LOG_PANIC
Something went really wrong and we will crash now.
Definition: log.h:196
int64_t
long long int64_t
Definition: coverity.c:34
av_frame_free
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:162
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:389
AVFormatContext::strict_std_compliance
int strict_std_compliance
Allow non-standard and experimental extension.
Definition: avformat.h:1657
AV_CODEC_ID_A64_MULTI
@ AV_CODEC_ID_A64_MULTI
Definition: codec_id.h:195
data
const char data[16]
Definition: mxf.c:148
FFCodec
Definition: codec_internal.h:127
FF_COMPLIANCE_EXPERIMENTAL
#define FF_COMPLIANCE_EXPERIMENTAL
Allow nonstandardized experimental things.
Definition: defs.h:62
AVDictionary
Definition: dict.c:34
av_packet_free
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition: packet.c:74
error
static void error(const char *err)
Definition: target_enc_fuzzer.c:40
FFCodec::p
AVCodec p
The public AVCodec.
Definition: codec_internal.h:131
codec_list
const FFCodec * codec_list[]
av_frame_alloc
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:150
AVFormatContext::bit_rate
int64_t bit_rate
Total stream bitrate in bit/s, 0 if not available.
Definition: avformat.h:1442
avassert.h
pkt
AVPacket * pkt
Definition: movenc.c:60
FF_ARRAY_ELEMS
#define FF_ARRAY_ELEMS(a)
Definition: sinewin_tablegen.c:29
avcodec_alloc_context3
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:149
intreadwrite.h
av_assert0
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:40
ctx
AVFormatContext * ctx
Definition: movenc.c:49
AV_PIX_FMT_YUV420P
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:73
opts
AVDictionary * opts
Definition: movenc.c:51
NULL
#define NULL
Definition: coverity.c:32
maxiteration
const uint32_t maxiteration
Definition: target_enc_fuzzer.c:49
av_buffer_unref
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
Definition: buffer.c:139
AVCodec::type
enum AVMediaType type
Definition: codec.h:200
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:164
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:143
ENCODER_SYMBOL
#define ENCODER_SYMBOL(CODEC)
AV_CODEC_ID_FFV1
@ AV_CODEC_ID_FFV1
Definition: codec_id.h:85
codec_internal.h
cpu.h
AVCodec::pix_fmts
attribute_deprecated enum AVPixelFormat * pix_fmts
Definition: codec.h:215
size
int size
Definition: twinvq_data.h:10344
LLVMFuzzerTestOneInput
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
Definition: target_enc_fuzzer.c:73
av_packet_alloc
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: packet.c:63
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::id
enum AVCodecID id
Definition: codec.h:201
av_log_set_level
void av_log_set_level(int level)
Set the log level.
Definition: log.c:447
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:256
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
AV_CODEC_ID_A64_MULTI5
@ AV_CODEC_ID_A64_MULTI5
Definition: codec_id.h:196
avcodec_send_frame
int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Supply a raw video or audio frame to the encoder.
Definition: encode.c:508
avcodec.h
ret
ret
Definition: filter_design.txt:187
frame
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
Definition: filter_design.txt:264
avformat.h
AVCodecContext
main external API structure.
Definition: avcodec.h:451
AV_PIX_FMT_NONE
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:72
c
static const FFCodec * c
Definition: target_enc_fuzzer.c:46
av_dict_set_int
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set() that converts the value to a string and stores it.
Definition: dict.c:167
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
mem.h
it
s EdgeDetect Foobar g libavfilter vf_edgedetect c libavfilter vf_foobar c edit libavfilter and add an entry for foobar following the pattern of the other filters edit libavfilter allfilters and add an entry for foobar following the pattern of the other filters configure make j< whatever > ffmpeg ffmpeg i you should get a foobar png with Lena edge detected That s it
Definition: writing_filters.txt:31
AVPacket
This structure stores compressed data.
Definition: packet.h:516
encode
static int encode(AVCodecContext *enc_ctx, AVFrame *frame, AVPacket *pkt)
Definition: target_enc_fuzzer.c:52
bytestream.h
imgutils.h
bytestream2_init
static av_always_inline void bytestream2_init(GetByteContext *g, const uint8_t *buf, int buf_size)
Definition: bytestream.h:137
flags
#define flags(name, subs,...)
Definition: cbs_av1.c:482
avstring.h
av_image_check_size
int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx)
Check if the given dimension of an image is valid, meaning that all bytes of the image can be address...
Definition: imgutils.c:318