2 * Copyright (C) 2010-2011 Kevin Stone
3 * Copyright (C) 2016 Paul B Mahol
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with FFmpeg; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "libavutil/common.h"
25 #include "libavutil/float_dsp.h"
26 #include "libavutil/imgutils.h"
27 #include "libavutil/mem_internal.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/pixdesc.h"
35 static const size_t NNEDI_WEIGHTS_SIZE = 13574928;
36 static const uint8_t NNEDI_XDIM[] = { 8, 16, 32, 48, 8, 16, 32 };
37 static const uint8_t NNEDI_YDIM[] = { 6, 6, 6, 6, 4, 4, 4 };
38 static const uint16_t NNEDI_NNS[] = { 16, 32, 64, 128, 256 };
40 typedef struct PrescreenerCoefficients {
41 DECLARE_ALIGNED(32, float, kernel_l0)[4][16 * 4];
42 DECLARE_ALIGNED(32, float, bias_l0)[4];
44 DECLARE_ALIGNED(32, float, kernel_l1)[4][4];
45 DECLARE_ALIGNED(32, float, bias_l1)[4];
47 DECLARE_ALIGNED(32, float, kernel_l2)[4][8];
48 DECLARE_ALIGNED(32, float, bias_l2)[4];
49 } PrescreenerCoefficients;
51 typedef struct PredictorCoefficients {
52 int xdim, ydim, nns, nsize;
56 float *softmax_bias_q1;
57 float *elliott_bias_q1;
60 float *softmax_bias_q2;
61 float *elliott_bias_q2;
62 } PredictorCoefficients;
64 typedef struct NNEDIContext {
75 AVFloatDSPContext *fdsp;
84 PrescreenerCoefficients prescreener[4];
85 PredictorCoefficients coeffs[2][5][7];
102 uint8_t **prescreen_buf;
106 void (*read)(const uint8_t *src, float *dst,
107 int src_stride, int dst_stride,
108 int width, int height, float scale);
109 void (*write)(const float *src, uint8_t *dst,
110 int src_stride, int dst_stride,
111 int width, int height, int depth, float scale);
112 void (*prescreen[2])(AVFilterContext *ctx,
113 const void *src, ptrdiff_t src_stride,
114 uint8_t *prescreen, int N,
115 const PrescreenerCoefficients *const coeffs);
118 #define OFFSET(x) offsetof(NNEDIContext, x)
119 #define RFLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_RUNTIME_PARAM
120 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
122 static const AVOption nnedi_options[] = {
123 {"weights", "set weights file", OFFSET(weights_file), AV_OPT_TYPE_STRING, {.str="nnedi3_weights.bin"}, 0, 0, FLAGS },
124 {"deint", "set which frames to deinterlace", OFFSET(deint), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, RFLAGS, "deint" },
125 {"all", "deinterlace all frames", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, RFLAGS, "deint" },
126 {"interlaced", "only deinterlace frames marked as interlaced", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, RFLAGS, "deint" },
127 {"field", "set mode of operation", OFFSET(field), AV_OPT_TYPE_INT, {.i64=-1}, -2, 3, RFLAGS, "field" },
128 {"af", "use frame flags, both fields", 0, AV_OPT_TYPE_CONST, {.i64=-2}, 0, 0, RFLAGS, "field" },
129 {"a", "use frame flags, single field", 0, AV_OPT_TYPE_CONST, {.i64=-1}, 0, 0, RFLAGS, "field" },
130 {"t", "use top field only", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, RFLAGS, "field" },
131 {"b", "use bottom field only", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, RFLAGS, "field" },
132 {"tf", "use both fields, top first", 0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, RFLAGS, "field" },
133 {"bf", "use both fields, bottom first", 0, AV_OPT_TYPE_CONST, {.i64=3}, 0, 0, RFLAGS, "field" },
134 {"planes", "set which planes to process", OFFSET(process_plane), AV_OPT_TYPE_INT, {.i64=7}, 0, 15, RFLAGS },
135 {"nsize", "set size of local neighborhood around each pixel, used by the predictor neural network", OFFSET(nsize), AV_OPT_TYPE_INT, {.i64=6}, 0, 6, RFLAGS, "nsize" },
136 {"s8x6", NULL, 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, RFLAGS, "nsize" },
137 {"s16x6", NULL, 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, RFLAGS, "nsize" },
138 {"s32x6", NULL, 0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, RFLAGS, "nsize" },
139 {"s48x6", NULL, 0, AV_OPT_TYPE_CONST, {.i64=3}, 0, 0, RFLAGS, "nsize" },
140 {"s8x4", NULL, 0, AV_OPT_TYPE_CONST, {.i64=4}, 0, 0, RFLAGS, "nsize" },
141 {"s16x4", NULL, 0, AV_OPT_TYPE_CONST, {.i64=5}, 0, 0, RFLAGS, "nsize" },
142 {"s32x4", NULL, 0, AV_OPT_TYPE_CONST, {.i64=6}, 0, 0, RFLAGS, "nsize" },
143 {"nns", "set number of neurons in predictor neural network", OFFSET(nnsparam), AV_OPT_TYPE_INT, {.i64=1}, 0, 4, RFLAGS, "nns" },
144 {"n16", NULL, 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, RFLAGS, "nns" },
145 {"n32", NULL, 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, RFLAGS, "nns" },
146 {"n64", NULL, 0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, RFLAGS, "nns" },
147 {"n128", NULL, 0, AV_OPT_TYPE_CONST, {.i64=3}, 0, 0, RFLAGS, "nns" },
148 {"n256", NULL, 0, AV_OPT_TYPE_CONST, {.i64=4}, 0, 0, RFLAGS, "nns" },
149 {"qual", "set quality", OFFSET(qual), AV_OPT_TYPE_INT, {.i64=1}, 1, 2, RFLAGS, "qual" },
150 {"fast", NULL, 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, RFLAGS, "qual" },
151 {"slow", NULL, 0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, RFLAGS, "qual" },
152 {"etype", "set which set of weights to use in the predictor", OFFSET(etype), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, RFLAGS, "etype" },
153 {"a", "weights trained to minimize absolute error", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, RFLAGS, "etype" },
154 {"abs","weights trained to minimize absolute error", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, RFLAGS, "etype" },
155 {"s", "weights trained to minimize squared error", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, RFLAGS, "etype" },
156 {"mse","weights trained to minimize squared error", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, RFLAGS, "etype" },
157 {"pscrn", "set prescreening", OFFSET(pscrn), AV_OPT_TYPE_INT, {.i64=2}, 0, 4, RFLAGS, "pscrn" },
158 {"none", NULL, 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, RFLAGS, "pscrn" },
159 {"original", NULL, 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, RFLAGS, "pscrn" },
160 {"new", NULL, 0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, RFLAGS, "pscrn" },
161 {"new2", NULL, 0, AV_OPT_TYPE_CONST, {.i64=3}, 0, 0, RFLAGS, "pscrn" },
162 {"new3", NULL, 0, AV_OPT_TYPE_CONST, {.i64=4}, 0, 0, RFLAGS, "pscrn" },
166 AVFILTER_DEFINE_CLASS(nnedi);
168 static int config_output(AVFilterLink *outlink)
170 AVFilterContext *ctx = outlink->src;
172 outlink->time_base.num = ctx->inputs[0]->time_base.num;
173 outlink->time_base.den = ctx->inputs[0]->time_base.den * 2;
174 outlink->w = ctx->inputs[0]->w;
175 outlink->h = ctx->inputs[0]->h;
177 outlink->frame_rate = av_mul_q(ctx->inputs[0]->frame_rate,
183 static int query_formats(AVFilterContext *ctx)
185 static const enum AVPixelFormat pix_fmts[] = {
187 AV_PIX_FMT_GRAY9, AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
188 AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
189 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
190 AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
191 AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P,
192 AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
194 AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVA422P, AV_PIX_FMT_YUVA444P,
195 AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP,
196 AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV444P9,
197 AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
198 AV_PIX_FMT_YUV440P10,
199 AV_PIX_FMT_YUV420P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV444P12,
200 AV_PIX_FMT_YUV440P12,
201 AV_PIX_FMT_YUV420P14, AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV444P14,
202 AV_PIX_FMT_YUV420P16, AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16,
203 AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
204 AV_PIX_FMT_YUVA444P9, AV_PIX_FMT_YUVA444P10, AV_PIX_FMT_YUVA444P12, AV_PIX_FMT_YUVA444P16,
205 AV_PIX_FMT_YUVA422P9, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA422P12, AV_PIX_FMT_YUVA422P16,
206 AV_PIX_FMT_YUVA420P9, AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA420P16,
207 AV_PIX_FMT_GBRAP10, AV_PIX_FMT_GBRAP12, AV_PIX_FMT_GBRAP16,
211 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
213 return AVERROR(ENOMEM);
214 return ff_set_common_formats(ctx, fmts_list);
217 static float dot_dsp(const NNEDIContext *const s, const float *kernel, const float *input,
218 int n, float scale, float bias)
222 sum = s->fdsp->scalarproduct_float(kernel, input, n);
224 return sum * scale + bias;
227 static float elliott(float x)
229 return x / (1.0f + fabsf(x));
232 static void transform_elliott(float *input, int size)
234 for (int i = 0; i < size; i++)
235 input[i] = elliott(input[i]);
238 static void process_old(AVFilterContext *ctx,
239 const void *src, ptrdiff_t src_stride,
240 uint8_t *prescreen, int N,
241 const PrescreenerCoefficients *const m_data)
243 NNEDIContext *s = ctx->priv;
244 const float *src_p = src;
246 // Adjust source pointer to point to top-left of filter window.
247 const float *window = src_p - 2 * src_stride - 5;
249 for (int j = 0; j < N; j++) {
250 LOCAL_ALIGNED_32(float, input, [48]);
253 for (int i = 0; i < 4; i++)
254 memcpy(input + i * 12, window + i * src_stride + j, 12 * sizeof(float));
257 for (int n = 0; n < 4; n++)
258 state[n] = dot_dsp(s, m_data->kernel_l0[n], input, 48, 1.0f, m_data->bias_l0[n]);
259 transform_elliott(state + 1, 3);
262 for (int n = 0; n < 4; n++)
263 state[n + 4] = dot_dsp(s, m_data->kernel_l1[n], state, 4, 1.0f, m_data->bias_l1[n]);
264 transform_elliott(state + 4, 3);
267 for (int n = 0; n < 4; n++)
268 state[n + 8] = dot_dsp(s, m_data->kernel_l2[n], state, 8, 1.0f, m_data->bias_l2[n]);
270 prescreen[j] = FFMAX(state[10], state[11]) <= FFMAX(state[8], state[9]) ? 255 : 0;
274 static void process_new(AVFilterContext *ctx,
275 const void *src, ptrdiff_t src_stride,
276 uint8_t *prescreen, int N,
277 const PrescreenerCoefficients *const m_data)
279 NNEDIContext *s = ctx->priv;
280 const float *src_p = src;
282 // Adjust source pointer to point to top-left of filter window.
283 const float *window = src_p - 2 * src_stride - 6;
285 for (int j = 0; j < N; j += 4) {
286 LOCAL_ALIGNED_32(float, input, [64]);
289 for (int i = 0; i < 4; i++)
290 memcpy(input + i * 16, window + i * src_stride + j, 16 * sizeof(float));
292 for (int n = 0; n < 4; n++)
293 state[n] = dot_dsp(s, m_data->kernel_l0[n], input, 64, 1.0f, m_data->bias_l0[n]);
294 transform_elliott(state, 4);
296 for (int n = 0; n < 4; n++)
297 state[n + 4] = dot_dsp(s, m_data->kernel_l1[n], state, 4, 1.0f, m_data->bias_l1[n]);
299 for (int n = 0; n < 4; n++)
300 prescreen[j + n] = state[n + 4] > 0.f;
304 static int filter_offset(int nn, const PredictorCoefficients *const model)
306 return nn * model->nsize;
309 static const float *softmax_q1_filter(int nn,
310 const PredictorCoefficients *const model)
312 return model->softmax_q1 + filter_offset(nn, model);
315 static const float *elliott_q1_filter(int nn,
316 const PredictorCoefficients *const model)
318 return model->elliott_q1 + filter_offset(nn, model);
321 static const float *softmax_q2_filter(int nn,
322 const PredictorCoefficients *const model)
324 return model->softmax_q2 + filter_offset(nn, model);
327 static const float *elliott_q2_filter(int nn,
328 const PredictorCoefficients *const model)
330 return model->elliott_q2 + filter_offset(nn, model);
333 static void gather_input(const float *src, ptrdiff_t src_stride,
334 float *buf, float mstd[4],
335 const PredictorCoefficients *const model)
341 for (int i = 0; i < model->ydim; i++) {
342 memcpy(buf, src, model->xdim * sizeof(float));
344 for (int j = 0; j < model->xdim; j++) {
345 const float val = src[j];
355 mstd[0] = sum / model->nsize;
358 tmp = sum_sq / model->nsize - mstd[0] * mstd[0];
359 if (tmp < FLT_EPSILON) {
363 mstd[1] = sqrtf(tmp);
364 mstd[2] = 1.0f / mstd[1];
368 static float softmax_exp(float x)
370 return expf(av_clipf(x, -80.f, 80.f));
373 static void transform_softmax_exp(float *input, int size)
375 for (int i = 0; i < size; i++)
376 input[i] = softmax_exp(input[i]);
379 static void wae5(const float *softmax, const float *el,
380 int n, float mstd[4])
382 float vsum = 0.0f, wsum = 0.0f;
384 for (int i = 0; i < n; i++) {
385 vsum += softmax[i] * elliott(el[i]);
390 mstd[3] += (5.0f * vsum) / wsum * mstd[1] + mstd[0];
395 static void predictor(AVFilterContext *ctx,
396 const void *src, ptrdiff_t src_stride, void *dst,
397 const uint8_t *prescreen, int N,
398 const PredictorCoefficients *const model, int use_q2)
400 const NNEDIContext *const s = ctx->priv;
401 const float *src_p = src;
404 // Adjust source pointer to point to top-left of filter window.
405 const float *window = src_p - (model->ydim / 2) * src_stride - (model->xdim / 2 - 1);
406 const int filter_size = model->nsize;
407 const int nns = model->nns;
409 for (int i = 0; i < N; i++) {
410 LOCAL_ALIGNED_32(float, input, [48 * 6]);
411 float activation[256 * 2];
418 gather_input(window + i, src_stride, input, mstd, model);
421 for (int nn = 0; nn < nns; nn++)
422 activation[nn] = dot_dsp(s, softmax_q1_filter(nn, model), input, filter_size, scale, model->softmax_bias_q1[nn]);
424 for (int nn = 0; nn < nns; nn++)
425 activation[nns + nn] = dot_dsp(s, elliott_q1_filter(nn, model), input, filter_size, scale, model->elliott_bias_q1[nn]);
427 transform_softmax_exp(activation, nns);
428 wae5(activation, activation + nns, nns, mstd);
431 for (int nn = 0; nn < nns; nn++)
432 activation[nn] = dot_dsp(s, softmax_q2_filter(nn, model), input, filter_size, scale, model->softmax_bias_q2[nn]);
434 for (int nn = 0; nn < nns; nn++)
435 activation[nns + nn] = dot_dsp(s, elliott_q2_filter(nn, model), input, filter_size, scale, model->elliott_bias_q2[nn]);
437 transform_softmax_exp(activation, nns);
438 wae5(activation, activation + nns, nns, mstd);
441 dst_p[i] = mstd[3] * (use_q2 ? 0.5f : 1.f);
445 static void read_bytes(const uint8_t *src, float *dst,
446 int src_stride, int dst_stride,
447 int width, int height, float scale)
449 for (int y = 0; y < height; y++) {
450 for (int x = 0; x < 32; x++)
451 dst[-x - 1] = src[x];
453 for (int x = 0; x < width; x++)
456 for (int x = 0; x < 32; x++)
457 dst[width + x] = src[width - x - 1];
464 static void read_words(const uint8_t *srcp, float *dst,
465 int src_stride, int dst_stride,
466 int width, int height, float scale)
468 const uint16_t *src = (const uint16_t *)srcp;
472 for (int y = 0; y < height; y++) {
473 for (int x = 0; x < 32; x++)
474 dst[-x - 1] = src[x] * scale;
476 for (int x = 0; x < width; x++)
477 dst[x] = src[x] * scale;
479 for (int x = 0; x < 32; x++)
480 dst[width + x] = src[width - x - 1] * scale;
487 static void write_bytes(const float *src, uint8_t *dst,
488 int src_stride, int dst_stride,
489 int width, int height, int depth,
492 for (int y = 0; y < height; y++) {
493 for (int x = 0; x < width; x++)
494 dst[x] = av_clip_uint8(src[x]);
501 static void write_words(const float *src, uint8_t *dstp,
502 int src_stride, int dst_stride,
503 int width, int height, int depth,
506 uint16_t *dst = (uint16_t *)dstp;
510 for (int y = 0; y < height; y++) {
511 for (int x = 0; x < width; x++)
512 dst[x] = av_clip_uintp2_c(src[x] * scale, depth);
519 static void interpolation(const void *src, ptrdiff_t src_stride,
520 void *dst, const uint8_t *prescreen, int n)
522 const float *src_p = src;
524 const float *window = src_p - 2 * src_stride;
526 for (int i = 0; i < n; i++) {
532 accum += (-3.0f / 32.0f) * window[0 * src_stride + i];
533 accum += (19.0f / 32.0f) * window[1 * src_stride + i];
534 accum += (19.0f / 32.0f) * window[2 * src_stride + i];
535 accum += (-3.0f / 32.0f) * window[3 * src_stride + i];
541 static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
543 const NNEDIContext *const s = ctx->priv;
544 AVFrame *out = s->dst;
545 AVFrame *in = s->src;
546 const float in_scale = s->in_scale;
547 const float out_scale = s->out_scale;
548 const int depth = s->depth;
549 const int interlaced = in->interlaced_frame;
550 const int tff = s->field_n == (s->field < 0 ? interlaced ? in->top_field_first : 1 :
554 for (int p = 0; p < s->nb_planes; p++) {
555 const int height = s->planeheight[p];
556 const int width = s->planewidth[p];
557 const int slice_start = 2 * ((height / 2 * jobnr) / nb_jobs);
558 const int slice_end = 2 * ((height / 2 * (jobnr+1)) / nb_jobs);
559 const uint8_t *src_data = in->data[p];
560 uint8_t *dst_data = out->data[p];
561 uint8_t *dst = out->data[p] + slice_start * out->linesize[p];
562 const int src_linesize = in->linesize[p];
563 const int dst_linesize = out->linesize[p];
564 uint8_t *prescreen_buf = s->prescreen_buf[jobnr];
565 float *srcbuf = s->input_buf[jobnr];
566 const int srcbuf_stride = width + 64;
567 float *dstbuf = s->output_buf[jobnr];
568 const int dstbuf_stride = width;
569 const int slice_height = (slice_end - slice_start) / 2;
570 const int last_slice = slice_end == height;
571 const uint8_t *in_line;
575 if (!(s->process_plane & (1 << p))) {
576 av_image_copy_plane(dst, out->linesize[p],
577 in->data[p] + slice_start * in->linesize[p],
579 s->linesize[p], slice_end - slice_start);
583 y_out = slice_start + (tff ^ (slice_start & 1));
584 in_line = src_data + (y_out * src_linesize);
585 out_line = dst_data + (y_out * dst_linesize);
587 while (y_out < slice_end) {
588 memcpy(out_line, in_line, s->linesize[p]);
590 in_line += src_linesize * 2;
591 out_line += dst_linesize * 2;
594 y_out = slice_start + ((!tff) ^ (slice_start & 1));
596 s->read(src_data + FFMAX(y_out - 5, tff) * src_linesize,
598 src_linesize * 2, srcbuf_stride,
600 srcbuf += srcbuf_stride;
602 s->read(src_data + FFMAX(y_out - 3, tff) * src_linesize,
604 src_linesize * 2, srcbuf_stride,
606 srcbuf += srcbuf_stride;
608 s->read(src_data + FFMAX(y_out - 1, tff) * src_linesize,
610 src_linesize * 2, srcbuf_stride,
612 srcbuf += srcbuf_stride;
614 in_line = src_data + FFMIN(y_out + 1, height - 1 - !tff) * src_linesize;
615 out_line = dst_data + (y_out * dst_linesize);
617 s->read(in_line, srcbuf + 32, src_linesize * 2, srcbuf_stride,
618 width, slice_height - last_slice, in_scale);
620 y_out += (slice_height - last_slice) * 2;
622 s->read(src_data + FFMIN(y_out + 1, height - 1 - !tff) * src_linesize,
623 srcbuf + 32 + srcbuf_stride * (slice_height - last_slice),
624 src_linesize * 2, srcbuf_stride,
627 s->read(src_data + FFMIN(y_out + 3, height - 1 - !tff) * src_linesize,
628 srcbuf + 32 + srcbuf_stride * (slice_height + 1 - last_slice),
629 src_linesize * 2, srcbuf_stride,
632 s->read(src_data + FFMIN(y_out + 5, height - 1 - !tff) * src_linesize,
633 srcbuf + 32 + srcbuf_stride * (slice_height + 2 - last_slice),
634 src_linesize * 2, srcbuf_stride,
637 for (int y = 0; y < slice_end - slice_start; y += 2) {
638 if (s->prescreen > 0)
639 s->prescreen[s->pscrn > 1](ctx, srcbuf + (y / 2) * srcbuf_stride + 32,
640 srcbuf_stride, prescreen_buf, width,
641 &s->prescreener[s->pscrn - 1]);
644 srcbuf + (y / 2) * srcbuf_stride + 32,
646 dstbuf + (y / 2) * dstbuf_stride,
647 prescreen_buf, width,
648 &s->coeffs[s->etype][s->nnsparam][s->nsize], s->qual == 2);
650 if (s->prescreen > 0)
651 interpolation(srcbuf + (y / 2) * srcbuf_stride + 32,
653 dstbuf + (y / 2) * dstbuf_stride,
654 prescreen_buf, width);
657 s->write(dstbuf, out_line, dstbuf_stride, dst_linesize * 2,
658 width, slice_height, depth, out_scale);
664 static int get_frame(AVFilterContext *ctx, int is_second)
666 NNEDIContext *s = ctx->priv;
667 AVFilterLink *outlink = ctx->outputs[0];
668 AVFrame *src = s->src;
670 s->dst = ff_get_video_buffer(outlink, outlink->w, outlink->h);
672 return AVERROR(ENOMEM);
673 av_frame_copy_props(s->dst, src);
674 s->dst->interlaced_frame = 0;
676 ctx->internal->execute(ctx, filter_slice, NULL, NULL, FFMIN(s->planeheight[1] / 2, s->nb_threads));
678 if (s->field == -2 || s->field > 1)
679 s->field_n = !s->field_n;
684 static int filter_frame(AVFilterLink *inlink, AVFrame *src)
686 AVFilterContext *ctx = inlink->dst;
687 AVFilterLink *outlink = ctx->outputs[0];
688 NNEDIContext *s = ctx->priv;
692 s->field == -2) && !s->second) {
694 } else if (s->field > 1 ||
699 ret = get_frame(ctx, 1);
701 av_frame_free(&s->dst);
702 av_frame_free(&s->second);
708 if (src->pts != AV_NOPTS_VALUE &&
709 dst->pts != AV_NOPTS_VALUE)
710 dst->pts += src->pts;
712 dst->pts = AV_NOPTS_VALUE;
714 ret = ff_filter_frame(outlink, dst);
719 s->cur_pts = s->second->pts;
720 av_frame_free(&s->second);
722 if ((s->deint && src->interlaced_frame &&
723 !ctx->is_disabled) ||
724 (!s->deint && !ctx->is_disabled)) {
729 if ((s->deint && !src->interlaced_frame) || ctx->is_disabled) {
730 AVFrame *dst = av_frame_clone(src);
733 av_frame_free(&s->second);
734 return AVERROR(ENOMEM);
737 if (s->field > 1 || s->field == -2) {
738 av_frame_free(&s->second);
739 if ((s->deint && src->interlaced_frame) ||
745 if (dst->pts != AV_NOPTS_VALUE)
747 return ff_filter_frame(outlink, dst);
751 ret = get_frame(ctx, 0);
753 av_frame_free(&s->dst);
754 av_frame_free(&s->src);
755 av_frame_free(&s->second);
759 if (src->pts != AV_NOPTS_VALUE)
760 s->dst->pts = src->pts * 2;
761 if (s->field <= 1 && s->field > -2) {
766 return ff_filter_frame(outlink, s->dst);
769 static int request_frame(AVFilterLink *link)
771 AVFilterContext *ctx = link->src;
772 NNEDIContext *s = ctx->priv;
778 ret = ff_request_frame(ctx->inputs[0]);
780 if (ret == AVERROR_EOF && s->second) {
781 AVFrame *next = av_frame_clone(s->second);
784 return AVERROR(ENOMEM);
786 next->pts = s->second->pts * 2 - s->cur_pts;
789 filter_frame(ctx->inputs[0], next);
790 } else if (ret < 0) {
797 static void copy_weights(float *dst, int n, const float **data)
799 memcpy(dst, *data, n * sizeof(float));
803 static float *allocate(float **ptr, int size)
812 static int allocate_model(PredictorCoefficients *coeffs, int xdim, int ydim, int nns)
814 int filter_size = nns * xdim * ydim;
818 data = av_calloc(filter_size + bias_size, 4 * sizeof(float));
820 return AVERROR(ENOMEM);
825 coeffs->nsize = xdim * ydim;
828 coeffs->softmax_q1 = allocate(&data, filter_size);
829 coeffs->elliott_q1 = allocate(&data, filter_size);
830 coeffs->softmax_bias_q1 = allocate(&data, bias_size);
831 coeffs->elliott_bias_q1 = allocate(&data, bias_size);
833 coeffs->softmax_q2 = allocate(&data, filter_size);
834 coeffs->elliott_q2 = allocate(&data, filter_size);
835 coeffs->softmax_bias_q2 = allocate(&data, bias_size);
836 coeffs->elliott_bias_q2 = allocate(&data, bias_size);
841 static int read_weights(AVFilterContext *ctx, const float *bdata)
843 NNEDIContext *s = ctx->priv;
846 copy_weights(&s->prescreener[0].kernel_l0[0][0], 4 * 48, &bdata);
847 copy_weights(s->prescreener[0].bias_l0, 4, &bdata);
849 copy_weights(&s->prescreener[0].kernel_l1[0][0], 4 * 4, &bdata);
850 copy_weights(s->prescreener[0].bias_l1, 4, &bdata);
852 copy_weights(&s->prescreener[0].kernel_l2[0][0], 4 * 8, &bdata);
853 copy_weights(s->prescreener[0].bias_l2, 4, &bdata);
855 for (int i = 0; i < 3; i++) {
856 PrescreenerCoefficients *data = &s->prescreener[i + 1];
857 float kernel_l0_shuffled[4 * 64];
858 float kernel_l1_shuffled[4 * 4];
860 copy_weights(kernel_l0_shuffled, 4 * 64, &bdata);
861 copy_weights(data->bias_l0, 4, &bdata);
863 copy_weights(kernel_l1_shuffled, 4 * 4, &bdata);
864 copy_weights(data->bias_l1, 4, &bdata);
866 for (int n = 0; n < 4; n++) {
867 for (int k = 0; k < 64; k++)
868 data->kernel_l0[n][k] = kernel_l0_shuffled[(k / 8) * 32 + n * 8 + k % 8];
869 for (int k = 0; k < 4; k++)
870 data->kernel_l1[n][k] = kernel_l1_shuffled[k * 4 + n];
874 for (int m = 0; m < 2; m++) {
875 // Grouping by neuron count.
876 for (int i = 0; i < 5; i++) {
877 const int nns = NNEDI_NNS[i];
879 // Grouping by window size.
880 for (int j = 0; j < 7; j++) {
881 PredictorCoefficients *model = &s->coeffs[m][i][j];
882 const int xdim = NNEDI_XDIM[j];
883 const int ydim = NNEDI_YDIM[j];
884 const int filter_size = xdim * ydim;
886 ret = allocate_model(model, xdim, ydim, nns);
890 // Quality 1 model. NNS[i] * (XDIM[j] * YDIM[j]) * 2 coefficients.
891 copy_weights(model->softmax_q1, nns * filter_size, &bdata);
892 copy_weights(model->elliott_q1, nns * filter_size, &bdata);
894 // Quality 1 model bias. NNS[i] * 2 coefficients.
895 copy_weights(model->softmax_bias_q1, nns, &bdata);
896 copy_weights(model->elliott_bias_q1, nns, &bdata);
898 // Quality 2 model. NNS[i] * (XDIM[j] * YDIM[j]) * 2 coefficients.
899 copy_weights(model->softmax_q2, nns * filter_size, &bdata);
900 copy_weights(model->elliott_q2, nns * filter_size, &bdata);
902 // Quality 2 model bias. NNS[i] * 2 coefficients.
903 copy_weights(model->softmax_bias_q2, nns, &bdata);
904 copy_weights(model->elliott_bias_q2, nns, &bdata);
912 static float mean(const float *input, int size)
916 for (int i = 0; i < size; i++)
922 static void transform(float *input, int size, float mean, float half)
924 for (int i = 0; i < size; i++)
925 input[i] = (input[i] - mean) / half;
928 static void subtract_mean_old(PrescreenerCoefficients *coeffs, float half)
930 for (int n = 0; n < 4; n++) {
931 float m = mean(coeffs->kernel_l0[n], 48);
933 transform(coeffs->kernel_l0[n], 48, m, half);
937 static void subtract_mean_new(PrescreenerCoefficients *coeffs, float half)
939 for (int n = 0; n < 4; n++) {
940 float m = mean(coeffs->kernel_l0[n], 64);
942 transform(coeffs->kernel_l0[n], 64, m, half);
946 static void subtract_mean_predictor(PredictorCoefficients *model)
948 int filter_size = model->nsize;
949 int nns = model->nns;
951 float softmax_means[256]; // Average of individual softmax filters.
952 float elliott_means[256]; // Average of individual elliott filters.
953 float mean_filter[48 * 6]; // Pointwise average of all softmax filters.
957 for (int nn = 0; nn < nns; nn++) {
958 softmax_means[nn] = mean(model->softmax_q1 + nn * filter_size, filter_size);
959 elliott_means[nn] = mean(model->elliott_q1 + nn * filter_size, filter_size);
961 for (int k = 0; k < filter_size; k++)
962 mean_filter[k] += model->softmax_q1[nn * filter_size + k] - softmax_means[nn];
965 for (int k = 0; k < filter_size; k++)
966 mean_filter[k] /= nns;
968 mean_bias = mean(model->softmax_bias_q1, nns);
970 for (int nn = 0; nn < nns; nn++) {
971 for (int k = 0; k < filter_size; k++) {
972 model->softmax_q1[nn * filter_size + k] -= softmax_means[nn] + mean_filter[k];
973 model->elliott_q1[nn * filter_size + k] -= elliott_means[nn];
975 model->softmax_bias_q1[nn] -= mean_bias;
979 memset(mean_filter, 0, 48 * 6 * sizeof(float));
981 for (int nn = 0; nn < nns; nn++) {
982 softmax_means[nn] = mean(model->softmax_q2 + nn * filter_size, filter_size);
983 elliott_means[nn] = mean(model->elliott_q2 + nn * filter_size, filter_size);
985 for (int k = 0; k < filter_size; k++) {
986 mean_filter[k] += model->softmax_q2[nn * filter_size + k] - softmax_means[nn];
990 for (int k = 0; k < filter_size; k++)
991 mean_filter[k] /= nns;
993 mean_bias = mean(model->softmax_bias_q2, nns);
995 for (int nn = 0; nn < nns; nn++) {
996 for (int k = 0; k < filter_size; k++) {
997 model->softmax_q2[nn * filter_size + k] -= softmax_means[nn] + mean_filter[k];
998 model->elliott_q2[nn * filter_size + k] -= elliott_means[nn];
1001 model->softmax_bias_q2[nn] -= mean_bias;
1005 static av_cold int init(AVFilterContext *ctx)
1007 NNEDIContext *s = ctx->priv;
1008 FILE *weights_file = NULL;
1009 int64_t weights_size;
1014 weights_file = av_fopen_utf8(s->weights_file, "rb");
1015 if (!weights_file) {
1016 av_log(ctx, AV_LOG_ERROR, "No weights file provided, aborting!\n");
1017 return AVERROR(EINVAL);
1020 if (fseek(weights_file, 0, SEEK_END)) {
1021 av_log(ctx, AV_LOG_ERROR, "Couldn't seek to the end of weights file.\n");
1022 fclose(weights_file);
1023 return AVERROR(EINVAL);
1026 weights_size = ftell(weights_file);
1028 if (weights_size == -1) {
1029 fclose(weights_file);
1030 av_log(ctx, AV_LOG_ERROR, "Couldn't get size of weights file.\n");
1031 return AVERROR(EINVAL);
1032 } else if (weights_size != NNEDI_WEIGHTS_SIZE) {
1033 fclose(weights_file);
1034 av_log(ctx, AV_LOG_ERROR, "Unexpected weights file size.\n");
1035 return AVERROR(EINVAL);
1038 if (fseek(weights_file, 0, SEEK_SET)) {
1039 fclose(weights_file);
1040 av_log(ctx, AV_LOG_ERROR, "Couldn't seek to the start of weights file.\n");
1041 return AVERROR(EINVAL);
1044 bdata = av_malloc(NNEDI_WEIGHTS_SIZE);
1046 fclose(weights_file);
1047 return AVERROR(ENOMEM);
1050 bytes_read = fread(bdata, 1, NNEDI_WEIGHTS_SIZE, weights_file);
1051 if (bytes_read != NNEDI_WEIGHTS_SIZE) {
1052 fclose(weights_file);
1053 ret = AVERROR_INVALIDDATA;
1054 av_log(ctx, AV_LOG_ERROR, "Couldn't read weights file.\n");
1058 fclose(weights_file);
1060 s->fdsp = avpriv_float_dsp_alloc(0);
1062 ret = AVERROR(ENOMEM);
1066 ret = read_weights(ctx, bdata);
1075 static int config_input(AVFilterLink *inlink)
1077 AVFilterContext *ctx = inlink->dst;
1078 NNEDIContext *s = ctx->priv;
1079 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
1082 s->depth = desc->comp[0].depth;
1083 s->nb_threads = ff_filter_get_nb_threads(ctx);
1084 s->nb_planes = av_pix_fmt_count_planes(inlink->format);
1085 if ((ret = av_image_fill_linesizes(s->linesize, inlink->format, inlink->w)) < 0)
1088 s->planewidth[1] = s->planewidth[2] = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
1089 s->planewidth[0] = s->planewidth[3] = inlink->w;
1090 s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
1091 s->planeheight[0] = s->planeheight[3] = inlink->h;
1093 s->half = ((1 << 8) - 1) / 2.f;
1094 s->out_scale = 1 << (s->depth - 8);
1095 s->in_scale = 1.f / s->out_scale;
1099 s->read = read_bytes;
1100 s->write = write_bytes;
1103 s->read = read_words;
1104 s->write = write_words;
1108 subtract_mean_old(&s->prescreener[0], s->half);
1109 subtract_mean_new(&s->prescreener[1], s->half);
1110 subtract_mean_new(&s->prescreener[2], s->half);
1111 subtract_mean_new(&s->prescreener[3], s->half);
1113 s->prescreen[0] = process_old;
1114 s->prescreen[1] = process_new;
1116 for (int i = 0; i < 2; i++) {
1117 for (int j = 0; j < 5; j++) {
1118 for (int k = 0; k < 7; k++)
1119 subtract_mean_predictor(&s->coeffs[i][j][k]);
1123 s->input_size = (s->planewidth[0] + 64) * (s->planeheight[0] + 6);
1124 s->input_buf = av_calloc(s->nb_threads, sizeof(*s->input_buf));
1126 return AVERROR(ENOMEM);
1128 for (int i = 0; i < s->nb_threads; i++) {
1129 s->input_buf[i] = av_calloc(s->input_size, sizeof(**s->input_buf));
1130 if (!s->input_buf[i])
1131 return AVERROR(ENOMEM);
1134 s->output_buf = av_calloc(s->nb_threads, sizeof(*s->output_buf));
1136 return AVERROR(ENOMEM);
1138 for (int i = 0; i < s->nb_threads; i++) {
1139 s->output_buf[i] = av_calloc(s->input_size, sizeof(**s->output_buf));
1140 if (!s->output_buf[i])
1141 return AVERROR(ENOMEM);
1144 s->prescreen_buf = av_calloc(s->nb_threads, sizeof(*s->prescreen_buf));
1145 if (!s->prescreen_buf)
1146 return AVERROR(ENOMEM);
1148 for (int i = 0; i < s->nb_threads; i++) {
1149 s->prescreen_buf[i] = av_calloc(s->planewidth[0], sizeof(**s->prescreen_buf));
1150 if (!s->prescreen_buf[i])
1151 return AVERROR(ENOMEM);
1157 static av_cold void uninit(AVFilterContext *ctx)
1159 NNEDIContext *s = ctx->priv;
1161 for (int i = 0; i < s->nb_threads && s->prescreen_buf; i++)
1162 av_freep(&s->prescreen_buf[i]);
1164 av_freep(&s->prescreen_buf);
1166 for (int i = 0; i < s->nb_threads && s->input_buf; i++)
1167 av_freep(&s->input_buf[i]);
1169 av_freep(&s->input_buf);
1171 for (int i = 0; i < s->nb_threads && s->output_buf; i++)
1172 av_freep(&s->output_buf[i]);
1174 av_freep(&s->output_buf);
1177 for (int i = 0; i < 2; i++) {
1178 for (int j = 0; j < 5; j++) {
1179 for (int k = 0; k < 7; k++) {
1180 av_freep(&s->coeffs[i][j][k].data);
1185 av_frame_free(&s->second);
1188 static const AVFilterPad inputs[] = {
1191 .type = AVMEDIA_TYPE_VIDEO,
1192 .filter_frame = filter_frame,
1193 .config_props = config_input,
1198 static const AVFilterPad outputs[] = {
1201 .type = AVMEDIA_TYPE_VIDEO,
1202 .config_props = config_output,
1203 .request_frame = request_frame,
1208 AVFilter ff_vf_nnedi = {
1210 .description = NULL_IF_CONFIG_SMALL("Apply neural network edge directed interpolation intra-only deinterlacer."),
1211 .priv_size = sizeof(NNEDIContext),
1212 .priv_class = &nnedi_class,
1215 .query_formats = query_formats,
1218 .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL | AVFILTER_FLAG_SLICE_THREADS,
1219 .process_command = ff_filter_process_command,