FFmpeg
vf_blockdetect.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2021 Thilo Borgmann <thilo.borgmann _at_ mail.de>
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 
21 /**
22  * @file
23  * No-reference blockdetect filter
24  *
25  * Implementing:
26  * Remco Muijs and Ihor Kirenko: "A no-reference blocking artifact measure for adaptive video processing." 2005 13th European signal processing conference. IEEE, 2005.
27  * http://www.eurasip.org/Proceedings/Eusipco/Eusipco2005/defevent/papers/cr1042.pdf
28  *
29  * @author Thilo Borgmann <thilo.borgmann _at_ mail.de>
30  */
31 
32 #include "libavutil/mem.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/pixdesc.h"
35 #include "internal.h"
36 #include "video.h"
37 
38 typedef struct BLKContext {
39  const AVClass *class;
40 
41  int hsub, vsub;
42  int nb_planes;
43 
44  int period_min; // minimum period to search for
45  int period_max; // maximum period to search for
46  int planes; // number of planes to filter
47 
48  double block_total;
49  uint64_t nb_frames;
50 
51  float *gradients;
52 } BLKContext;
53 
54 #define OFFSET(x) offsetof(BLKContext, x)
55 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
56 static const AVOption blockdetect_options[] = {
57  { "period_min", "Minimum period to search for", OFFSET(period_min), AV_OPT_TYPE_INT, {.i64=3}, 2, 32, FLAGS},
58  { "period_max", "Maximum period to search for", OFFSET(period_max), AV_OPT_TYPE_INT, {.i64=24}, 2, 64, FLAGS},
59  { "planes", "set planes to filter", OFFSET(planes), AV_OPT_TYPE_INT, {.i64=1}, 0, 15, FLAGS },
60  { NULL }
61 };
62 
63 AVFILTER_DEFINE_CLASS(blockdetect);
64 
66 {
67  AVFilterContext *ctx = inlink->dst;
68  BLKContext *s = ctx->priv;
69  const int bufsize = inlink->w * inlink->h;
70  const AVPixFmtDescriptor *pix_desc;
71 
72  pix_desc = av_pix_fmt_desc_get(inlink->format);
73  s->hsub = pix_desc->log2_chroma_w;
74  s->vsub = pix_desc->log2_chroma_h;
75  s->nb_planes = av_pix_fmt_count_planes(inlink->format);
76 
77  s->gradients = av_calloc(bufsize, sizeof(*s->gradients));
78 
79  if (!s->gradients)
80  return AVERROR(ENOMEM);
81 
82  return 0;
83 }
84 
85 static float calculate_blockiness(BLKContext *s, int w, int h,
86  float *grad, int grad_linesize,
87  uint8_t* src, int src_linesize)
88 {
89  float block = 0.0f;
90  float nonblock = 0.0f;
91  int block_count = 0;
92  int nonblock_count = 0;
93  float ret = 0;
94 
95  // Calculate BS in horizontal and vertical directions according to (1)(2)(3).
96  // Also try to find integer pixel periods (grids) even for scaled images.
97  // In case of fractional periods, FFMAX of current and neighbor pixels
98  // can help improve the correlation with MQS.
99  // Skip linear correction term (4)(5), as it appears only valid for their own test samples.
100 
101  // horizontal blockiness (fixed width)
102  for (int j = 1; j < h; j++) {
103  for (int i = 3; i < w - 4; i++) {
104  float temp = 0.0f;
105  grad[j * grad_linesize + i] =
106  abs(src[j * src_linesize + i + 0] - src[j * src_linesize + i + 1]);
107  temp += abs(src[j * src_linesize + i + 1] - src[j * src_linesize + i + 2]);
108  temp += abs(src[j * src_linesize + i + 2] - src[j * src_linesize + i + 3]);
109  temp += abs(src[j * src_linesize + i + 3] - src[j * src_linesize + i + 4]);
110  temp += abs(src[j * src_linesize + i - 0] - src[j * src_linesize + i - 1]);
111  temp += abs(src[j * src_linesize + i - 1] - src[j * src_linesize + i - 2]);
112  temp += abs(src[j * src_linesize + i - 2] - src[j * src_linesize + i - 3]);
113  temp = FFMAX(1, temp);
114  grad[j * grad_linesize + i] /= temp;
115 
116  // use first row to store acculated results
117  grad[i] += grad[j * grad_linesize + i];
118  }
119  }
120 
121  // find horizontal period
122  for (int period = s->period_min; period < s->period_max + 1; period++) {
123  float temp;
124  block = 0;
125  nonblock = 0;
126  block_count = 0;
127  nonblock_count = 0;
128  for (int i = 3; i < w - 4; i++) {
129  if ((i % period) == (period - 1)) {
130  block += FFMAX(FFMAX(grad[i + 0], grad[i + 1]), grad[i - 1]);
131  block_count++;
132  } else {
133  nonblock += grad[i];
134  nonblock_count++;
135  }
136  }
137  if (block_count && nonblock_count) {
138  temp = (block / block_count) / (nonblock / nonblock_count);
139  ret = FFMAX(ret, temp);
140  }
141  }
142 
143  // vertical blockiness (fixed height)
144  block_count = 0;
145  for (int j = 3; j < h - 4; j++) {
146  for (int i = 1; i < w; i++) {
147  float temp = 0.0f;
148  grad[j * grad_linesize + i] =
149  abs(src[(j + 0) * src_linesize + i] - src[(j + 1) * src_linesize + i]);
150  temp += abs(src[(j + 1) * src_linesize + i] - src[(j + 2) * src_linesize + i]);
151  temp += abs(src[(j + 2) * src_linesize + i] - src[(j + 3) * src_linesize + i]);
152  temp += abs(src[(j + 3) * src_linesize + i] - src[(j + 4) * src_linesize + i]);
153  temp += abs(src[(j - 0) * src_linesize + i] - src[(j - 1) * src_linesize + i]);
154  temp += abs(src[(j - 1) * src_linesize + i] - src[(j - 2) * src_linesize + i]);
155  temp += abs(src[(j - 2) * src_linesize + i] - src[(j - 3) * src_linesize + i]);
156  temp = FFMAX(1, temp);
157  grad[j * grad_linesize + i] /= temp;
158 
159  // use first column to store accumulated results
160  grad[j * grad_linesize] += grad[j * grad_linesize + i];
161  }
162  }
163 
164  // find vertical period
165  for (int period = s->period_min; period < s->period_max + 1; period++) {
166  float temp;
167  block = 0;
168  nonblock = 0;
169  block_count = 0;
170  nonblock_count = 0;
171  for (int j = 3; j < h - 4; j++) {
172  if ((j % period) == (period - 1)) {
173  block += FFMAX(FFMAX(grad[(j + 0) * grad_linesize],
174  grad[(j + 1) * grad_linesize]),
175  grad[(j - 1) * grad_linesize]);
176  block_count++;
177  } else {
178  nonblock += grad[j * grad_linesize];
179  nonblock_count++;
180  }
181  }
182  if (block_count && nonblock_count) {
183  temp = (block / block_count) / (nonblock / nonblock_count);
184  ret = FFMAX(ret, temp);
185  }
186  }
187 
188  // return highest value of horz||vert
189  return ret;
190 }
191 
192 static void set_meta(AVDictionary **metadata, const char *key, float d)
193 {
194  char value[128];
195  snprintf(value, sizeof(value), "%f", d);
196  av_dict_set(metadata, key, value, 0);
197 }
198 
200 {
201  AVFilterContext *ctx = inlink->dst;
202  BLKContext *s = ctx->priv;
203  AVFilterLink *outlink = ctx->outputs[0];
204 
205  const int inw = inlink->w;
206  const int inh = inlink->h;
207 
208  float *gradients = s->gradients;
209 
210  float block = 0.0f;
211  int nplanes = 0;
212  AVDictionary **metadata;
213  metadata = &in->metadata;
214 
215  for (int plane = 0; plane < s->nb_planes; plane++) {
216  int hsub = plane == 1 || plane == 2 ? s->hsub : 0;
217  int vsub = plane == 1 || plane == 2 ? s->vsub : 0;
218  int w = AV_CEIL_RSHIFT(inw, hsub);
219  int h = AV_CEIL_RSHIFT(inh, vsub);
220 
221  if (!((1 << plane) & s->planes))
222  continue;
223 
224  nplanes++;
225 
226  block += calculate_blockiness(s, w, h, gradients, w, in->data[plane], in->linesize[plane]);
227  }
228 
229  if (nplanes)
230  block /= nplanes;
231 
232  s->block_total += block;
233 
234  // write stats
235  av_log(ctx, AV_LOG_VERBOSE, "block: %.7f\n", block);
236 
237  set_meta(metadata, "lavfi.block", block);
238 
239  s->nb_frames = inlink->frame_count_in;
240 
241  return ff_filter_frame(outlink, in);
242 }
243 
245 {
246  BLKContext *s = ctx->priv;
247 
248  if (s->nb_frames > 0) {
249  av_log(ctx, AV_LOG_INFO, "block mean: %.7f\n",
250  s->block_total / s->nb_frames);
251  }
252 
253  av_freep(&s->gradients);
254 }
255 
256 static const enum AVPixelFormat pix_fmts[] = {
266 };
267 
268 static const AVFilterPad blockdetect_inputs[] = {
269  {
270  .name = "default",
271  .type = AVMEDIA_TYPE_VIDEO,
272  .config_props = blockdetect_config_input,
273  .filter_frame = blockdetect_filter_frame,
274  },
275 };
276 
278  .name = "blockdetect",
279  .description = NULL_IF_CONFIG_SMALL("Blockdetect filter."),
280  .priv_size = sizeof(BLKContext),
285  .priv_class = &blockdetect_class,
287 };
BLKContext::gradients
float * gradients
Definition: vf_blockdetect.c:51
AVPixelFormat
AVPixelFormat
Pixel format.
Definition: pixfmt.h:71
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
opt.h
ff_filter_frame
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1015
av_pix_fmt_desc_get
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:2965
BLKContext::period_max
int period_max
Definition: vf_blockdetect.c:45
FILTER_PIXFMTS_ARRAY
#define FILTER_PIXFMTS_ARRAY(array)
Definition: internal.h:162
inlink
The exact code depends on how similar the blocks are and how related they are to the and needs to apply these operations to the correct inlink or outlink if there are several Macros are available to factor that when no extra processing is inlink
Definition: filter_design.txt:212
BLKContext::period_min
int period_min
Definition: vf_blockdetect.c:44
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:374
pixdesc.h
w
uint8_t w
Definition: llviddspenc.c:38
pix_fmts
static enum AVPixelFormat pix_fmts[]
Definition: vf_blockdetect.c:256
AVOption
AVOption.
Definition: opt.h:357
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:196
blockdetect_inputs
static const AVFilterPad blockdetect_inputs[]
Definition: vf_blockdetect.c:268
AV_PIX_FMT_YUV440P
@ AV_PIX_FMT_YUV440P
planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
Definition: pixfmt.h:106
AVDictionary
Definition: dict.c:34
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
AVFilter::name
const char * name
Filter name.
Definition: avfilter.h:170
blockdetect_uninit
static av_cold void blockdetect_uninit(AVFilterContext *ctx)
Definition: vf_blockdetect.c:244
video.h
BLKContext::planes
int planes
Definition: vf_blockdetect.c:46
AVFrame::data
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:395
hsub
static void hsub(htype *dst, const htype *src, int bins)
Definition: vf_median.c:74
av_pix_fmt_count_planes
int av_pix_fmt_count_planes(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:3005
ff_vf_blockdetect
const AVFilter ff_vf_blockdetect
Definition: vf_blockdetect.c:277
AV_PIX_FMT_GBRAP
@ AV_PIX_FMT_GBRAP
planar GBRA 4:4:4:4 32bpp
Definition: pixfmt.h:212
BLKContext
Definition: vf_blockdetect.c:38
set_meta
static void set_meta(AVDictionary **metadata, const char *key, float d)
Definition: vf_blockdetect.c:192
AVFilterPad
A filter pad used for either input or output.
Definition: internal.h:33
AV_PIX_FMT_YUVJ411P
@ AV_PIX_FMT_YUVJ411P
planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) full scale (JPEG), deprecated in favor ...
Definition: pixfmt.h:283
av_cold
#define av_cold
Definition: attributes.h:90
ff_video_default_filterpad
const AVFilterPad ff_video_default_filterpad[1]
An AVFilterPad array whose only entry has name "default" and is of type AVMEDIA_TYPE_VIDEO.
Definition: video.c:37
AV_PIX_FMT_YUVJ422P
@ AV_PIX_FMT_YUVJ422P
planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV422P and setting col...
Definition: pixfmt.h:86
planes
static const struct @417 planes[]
s
#define s(width, name)
Definition: cbs_vp9.c:198
AV_PIX_FMT_YUVA420P
@ AV_PIX_FMT_YUVA420P
planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
Definition: pixfmt.h:108
AV_CEIL_RSHIFT
#define AV_CEIL_RSHIFT(a, b)
Definition: common.h:59
ctx
AVFormatContext * ctx
Definition: movenc.c:49
AVPixFmtDescriptor::log2_chroma_w
uint8_t log2_chroma_w
Amount to shift the luma width right to find the chroma width.
Definition: pixdesc.h:80
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
key
const char * key
Definition: hwcontext_opencl.c:189
FILTER_INPUTS
#define FILTER_INPUTS(array)
Definition: internal.h:182
AV_PIX_FMT_YUVJ444P
@ AV_PIX_FMT_YUVJ444P
planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV444P and setting col...
Definition: pixfmt.h:87
OFFSET
#define OFFSET(x)
Definition: vf_blockdetect.c:54
BLKContext::nb_planes
int nb_planes
Definition: vf_blockdetect.c:42
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:66
NULL
#define NULL
Definition: coverity.c:32
FLAGS
#define FLAGS
Definition: vf_blockdetect.c:55
period
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 default minimum maximum flags name is the option keep it simple and lowercase description are in without period
Definition: writing_filters.txt:89
AV_PIX_FMT_YUVJ420P
@ AV_PIX_FMT_YUVJ420P
planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV420P and setting col...
Definition: pixfmt.h:85
abs
#define abs(x)
Definition: cuda_runtime.h:35
AV_PIX_FMT_GRAY8
@ AV_PIX_FMT_GRAY8
Y , 8bpp.
Definition: pixfmt.h:81
calculate_blockiness
static float calculate_blockiness(BLKContext *s, int w, int h, float *grad, int grad_linesize, uint8_t *src, int src_linesize)
Definition: vf_blockdetect.c:85
BLKContext::hsub
int hsub
Definition: vf_blockdetect.c:41
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:94
AV_PIX_FMT_YUVA444P
@ AV_PIX_FMT_YUVA444P
planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples)
Definition: pixfmt.h:174
AV_LOG_INFO
#define AV_LOG_INFO
Standard information.
Definition: log.h:191
internal.h
uninit
static void uninit(AVBSFContext *ctx)
Definition: pcm_rechunk.c:68
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:256
BLKContext::block_total
double block_total
Definition: vf_blockdetect.c:48
value
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 default value
Definition: writing_filters.txt:86
AV_PIX_FMT_YUVJ440P
@ AV_PIX_FMT_YUVJ440P
planar YUV 4:4:0 full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV440P and setting color_range
Definition: pixfmt.h:107
blockdetect_filter_frame
static int blockdetect_filter_frame(AVFilterLink *inlink, AVFrame *in)
Definition: vf_blockdetect.c:199
AVFilterPad::name
const char * name
Pad name.
Definition: internal.h:39
BLKContext::vsub
int vsub
Definition: vf_blockdetect.c:41
av_calloc
void * av_calloc(size_t nmemb, size_t size)
Definition: mem.c:264
AVFilter
Filter definition.
Definition: avfilter.h:166
ret
ret
Definition: filter_design.txt:187
AV_PIX_FMT_NONE
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:72
AV_OPT_TYPE_INT
@ AV_OPT_TYPE_INT
Definition: opt.h:245
AVFrame::metadata
AVDictionary * metadata
metadata.
Definition: frame.h:692
AVFILTER_FLAG_METADATA_ONLY
#define AVFILTER_FLAG_METADATA_ONLY
The filter is a "metadata" filter - it does not modify the frame data in any way.
Definition: avfilter.h:133
temp
else temp
Definition: vf_mcdeint.c:263
AV_PIX_FMT_YUV444P
@ AV_PIX_FMT_YUV444P
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
Definition: pixfmt.h:78
AVFilterContext
An instance of a filter.
Definition: avfilter.h:407
AV_PIX_FMT_GBRP
@ AV_PIX_FMT_GBRP
planar GBR 4:4:4 24bpp
Definition: pixfmt.h:165
blockdetect_options
static const AVOption blockdetect_options[]
Definition: vf_blockdetect.c:56
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
AV_PIX_FMT_YUV422P
@ AV_PIX_FMT_YUV422P
planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
Definition: pixfmt.h:77
mem.h
AVFILTER_DEFINE_CLASS
AVFILTER_DEFINE_CLASS(blockdetect)
AVPixFmtDescriptor
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition: pixdesc.h:69
FILTER_OUTPUTS
#define FILTER_OUTPUTS(array)
Definition: internal.h:183
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:34
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:88
src
INIT_CLIP pixel * src
Definition: h264pred_template.c:418
AV_PIX_FMT_YUV411P
@ AV_PIX_FMT_YUV411P
planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
Definition: pixfmt.h:80
d
d
Definition: ffmpeg_filter.c:424
AVFrame::linesize
int linesize[AV_NUM_DATA_POINTERS]
For video, a positive or negative value, which is typically indicating the size in bytes of each pict...
Definition: frame.h:419
AV_PIX_FMT_YUV410P
@ AV_PIX_FMT_YUV410P
planar YUV 4:1:0, 9bpp, (1 Cr & Cb sample per 4x4 Y samples)
Definition: pixfmt.h:79
block
The exact code depends on how similar the blocks are and how related they are to the block
Definition: filter_design.txt:207
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
h
h
Definition: vp9dsp_template.c:2038
BLKContext::nb_frames
uint64_t nb_frames
Definition: vf_blockdetect.c:49
snprintf
#define snprintf
Definition: snprintf.h:34
AVPixFmtDescriptor::log2_chroma_h
uint8_t log2_chroma_h
Amount to shift the luma height right to find the chroma height.
Definition: pixdesc.h:89
AV_PIX_FMT_YUVA422P
@ AV_PIX_FMT_YUVA422P
planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples)
Definition: pixfmt.h:173
blockdetect_config_input
static int blockdetect_config_input(AVFilterLink *inlink)
Definition: vf_blockdetect.c:65