• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 Michael Niedermayer <michaelni@gmx.at>
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 #include <float.h> /* FLT_MAX */
22 
23 #include "libavutil/common.h"
24 #include "libavutil/opt.h"
25 #include "internal.h"
26 #include "vf_idet.h"
27 
28 #define OFFSET(x) offsetof(IDETContext, x)
29 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
30 
31 static const AVOption idet_options[] = {
32     { "intl_thres", "set interlacing threshold", OFFSET(interlace_threshold),   AV_OPT_TYPE_FLOAT, {.dbl = 1.04}, -1, FLT_MAX, FLAGS },
33     { "prog_thres", "set progressive threshold", OFFSET(progressive_threshold), AV_OPT_TYPE_FLOAT, {.dbl = 1.5},  -1, FLT_MAX, FLAGS },
34     { "rep_thres",  "set repeat threshold",      OFFSET(repeat_threshold),      AV_OPT_TYPE_FLOAT, {.dbl = 3.0},  -1, FLT_MAX, FLAGS },
35     { "half_life", "half life of cumulative statistics", OFFSET(half_life),     AV_OPT_TYPE_FLOAT, {.dbl = 0.0},  -1, INT_MAX, FLAGS },
36     { "analyze_interlaced_flag", "set number of frames to use to determine if the interlace flag is accurate", OFFSET(analyze_interlaced_flag), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, FLAGS },
37     { NULL }
38 };
39 
40 AVFILTER_DEFINE_CLASS(idet);
41 
type2str(Type type)42 static const char *type2str(Type type)
43 {
44     switch(type) {
45         case TFF          : return "tff";
46         case BFF          : return "bff";
47         case PROGRESSIVE  : return "progressive";
48         case UNDETERMINED : return "undetermined";
49     }
50     return NULL;
51 }
52 
53 #define PRECISION 1048576
54 
uintpow(uint64_t b,unsigned int e)55 static uint64_t uintpow(uint64_t b,unsigned int e)
56 {
57     uint64_t r=1;
58     while(e--) r*=b;
59     return r;
60 }
61 
av_dict_set_fxp(AVDictionary ** pm,const char * key,uint64_t value,unsigned int digits,int flags)62 static int av_dict_set_fxp(AVDictionary **pm, const char *key, uint64_t value, unsigned int digits,
63                 int flags)
64 {
65     char valuestr[44];
66     uint64_t print_precision = uintpow(10, digits);
67 
68     value = av_rescale(value, print_precision, PRECISION);
69 
70     snprintf(valuestr, sizeof(valuestr), "%"PRId64".%0*"PRId64,
71              value / print_precision, digits, value % print_precision);
72 
73     return av_dict_set(pm, key, valuestr, flags);
74 }
75 
rep2str(RepeatedField repeated_field)76 static const char *rep2str(RepeatedField repeated_field)
77 {
78     switch(repeated_field) {
79         case REPEAT_NONE    : return "neither";
80         case REPEAT_TOP     : return "top";
81         case REPEAT_BOTTOM  : return "bottom";
82     }
83     return NULL;
84 }
85 
ff_idet_filter_line_c(const uint8_t * a,const uint8_t * b,const uint8_t * c,int w)86 int ff_idet_filter_line_c(const uint8_t *a, const uint8_t *b, const uint8_t *c, int w)
87 {
88     int x;
89     int ret=0;
90 
91     for(x=0; x<w; x++){
92         int v = (*a++ + *c++) - 2 * *b++;
93         ret += FFABS(v);
94     }
95 
96     return ret;
97 }
98 
ff_idet_filter_line_c_16bit(const uint16_t * a,const uint16_t * b,const uint16_t * c,int w)99 int ff_idet_filter_line_c_16bit(const uint16_t *a, const uint16_t *b, const uint16_t *c, int w)
100 {
101     int x;
102     int ret=0;
103 
104     for(x=0; x<w; x++){
105         int v = (*a++ + *c++) - 2 * *b++;
106         ret += FFABS(v);
107     }
108 
109     return ret;
110 }
111 
filter(AVFilterContext * ctx)112 static void filter(AVFilterContext *ctx)
113 {
114     IDETContext *idet = ctx->priv;
115     int y, i;
116     int64_t alpha[2]={0};
117     int64_t delta=0;
118     int64_t gamma[2]={0};
119     Type type, best_type;
120     RepeatedField repeat;
121     int match = 0;
122     AVDictionary **metadata = &idet->cur->metadata;
123 
124     for (i = 0; i < idet->csp->nb_components; i++) {
125         int w = idet->cur->width;
126         int h = idet->cur->height;
127         int refs = idet->cur->linesize[i];
128 
129         if (i && i<3) {
130             w = AV_CEIL_RSHIFT(w, idet->csp->log2_chroma_w);
131             h = AV_CEIL_RSHIFT(h, idet->csp->log2_chroma_h);
132         }
133 
134         for (y = 2; y < h - 2; y++) {
135             uint8_t *prev = &idet->prev->data[i][y*refs];
136             uint8_t *cur  = &idet->cur ->data[i][y*refs];
137             uint8_t *next = &idet->next->data[i][y*refs];
138             alpha[ y   &1] += idet->filter_line(cur-refs, prev, cur+refs, w);
139             alpha[(y^1)&1] += idet->filter_line(cur-refs, next, cur+refs, w);
140             delta          += idet->filter_line(cur-refs,  cur, cur+refs, w);
141             gamma[(y^1)&1] += idet->filter_line(cur     , prev, cur     , w);
142         }
143     }
144 
145     if      (alpha[0] > idet->interlace_threshold * alpha[1]){
146         type = TFF;
147     }else if(alpha[1] > idet->interlace_threshold * alpha[0]){
148         type = BFF;
149     }else if(alpha[1] > idet->progressive_threshold * delta){
150         type = PROGRESSIVE;
151     }else{
152         type = UNDETERMINED;
153     }
154 
155     if ( gamma[0] > idet->repeat_threshold * gamma[1] ){
156         repeat = REPEAT_TOP;
157     } else if ( gamma[1] > idet->repeat_threshold * gamma[0] ){
158         repeat = REPEAT_BOTTOM;
159     } else {
160         repeat = REPEAT_NONE;
161     }
162 
163     memmove(idet->history+1, idet->history, HIST_SIZE-1);
164     idet->history[0] = type;
165     best_type = UNDETERMINED;
166     for(i=0; i<HIST_SIZE; i++){
167         if(idet->history[i] != UNDETERMINED){
168             if(best_type == UNDETERMINED)
169                 best_type = idet->history[i];
170 
171             if(idet->history[i] == best_type) {
172                 match++;
173             }else{
174                 match=0;
175                 break;
176             }
177         }
178     }
179     if(idet->last_type == UNDETERMINED){
180         if(match  ) idet->last_type = best_type;
181     }else{
182         if(match>2) idet->last_type = best_type;
183     }
184 
185     if      (idet->last_type == TFF){
186         idet->cur->top_field_first = 1;
187         idet->cur->interlaced_frame = 1;
188     }else if(idet->last_type == BFF){
189         idet->cur->top_field_first = 0;
190         idet->cur->interlaced_frame = 1;
191     }else if(idet->last_type == PROGRESSIVE){
192         idet->cur->interlaced_frame = 0;
193     }
194 
195     for(i=0; i<3; i++)
196         idet->repeats[i]  = av_rescale(idet->repeats [i], idet->decay_coefficient, PRECISION);
197 
198     for(i=0; i<4; i++){
199         idet->prestat [i] = av_rescale(idet->prestat [i], idet->decay_coefficient, PRECISION);
200         idet->poststat[i] = av_rescale(idet->poststat[i], idet->decay_coefficient, PRECISION);
201     }
202 
203     idet->total_repeats [         repeat] ++;
204     idet->repeats       [         repeat] += PRECISION;
205 
206     idet->total_prestat [           type] ++;
207     idet->prestat       [           type] += PRECISION;
208 
209     idet->total_poststat[idet->last_type] ++;
210     idet->poststat      [idet->last_type] += PRECISION;
211 
212     av_log(ctx, AV_LOG_DEBUG, "Repeated Field:%12s, Single frame:%12s, Multi frame:%12s\n",
213            rep2str(repeat), type2str(type), type2str(idet->last_type));
214 
215     av_dict_set    (metadata, "lavfi.idet.repeated.current_frame", rep2str(repeat), 0);
216     av_dict_set_fxp(metadata, "lavfi.idet.repeated.neither",       idet->repeats[REPEAT_NONE], 2, 0);
217     av_dict_set_fxp(metadata, "lavfi.idet.repeated.top",           idet->repeats[REPEAT_TOP], 2, 0);
218     av_dict_set_fxp(metadata, "lavfi.idet.repeated.bottom",        idet->repeats[REPEAT_BOTTOM], 2, 0);
219 
220     av_dict_set    (metadata, "lavfi.idet.single.current_frame",   type2str(type), 0);
221     av_dict_set_fxp(metadata, "lavfi.idet.single.tff",             idet->prestat[TFF], 2 , 0);
222     av_dict_set_fxp(metadata, "lavfi.idet.single.bff",             idet->prestat[BFF], 2, 0);
223     av_dict_set_fxp(metadata, "lavfi.idet.single.progressive",     idet->prestat[PROGRESSIVE], 2, 0);
224     av_dict_set_fxp(metadata, "lavfi.idet.single.undetermined",    idet->prestat[UNDETERMINED], 2, 0);
225 
226     av_dict_set    (metadata, "lavfi.idet.multiple.current_frame", type2str(idet->last_type), 0);
227     av_dict_set_fxp(metadata, "lavfi.idet.multiple.tff",           idet->poststat[TFF], 2, 0);
228     av_dict_set_fxp(metadata, "lavfi.idet.multiple.bff",           idet->poststat[BFF], 2, 0);
229     av_dict_set_fxp(metadata, "lavfi.idet.multiple.progressive",   idet->poststat[PROGRESSIVE], 2, 0);
230     av_dict_set_fxp(metadata, "lavfi.idet.multiple.undetermined",  idet->poststat[UNDETERMINED], 2, 0);
231 }
232 
filter_frame(AVFilterLink * link,AVFrame * picref)233 static int filter_frame(AVFilterLink *link, AVFrame *picref)
234 {
235     AVFilterContext *ctx = link->dst;
236     IDETContext *idet = ctx->priv;
237 
238     // initial frame(s) and not interlaced, just pass through for
239     // the analyze_interlaced_flag mode
240     if (idet->analyze_interlaced_flag &&
241         !picref->interlaced_frame &&
242         !idet->next) {
243         return ff_filter_frame(ctx->outputs[0], picref);
244     }
245     if (idet->analyze_interlaced_flag_done) {
246         if (picref->interlaced_frame && idet->interlaced_flag_accuracy < 0)
247             picref->interlaced_frame = 0;
248         return ff_filter_frame(ctx->outputs[0], picref);
249     }
250 
251     av_frame_free(&idet->prev);
252 
253     if(   picref->width  != link->w
254        || picref->height != link->h
255        || picref->format != link->format) {
256         link->dst->inputs[0]->format = picref->format;
257         link->dst->inputs[0]->w      = picref->width;
258         link->dst->inputs[0]->h      = picref->height;
259 
260         av_frame_free(&idet->cur );
261         av_frame_free(&idet->next);
262     }
263 
264     idet->prev = idet->cur;
265     idet->cur  = idet->next;
266     idet->next = picref;
267 
268     if (!idet->cur &&
269         !(idet->cur = av_frame_clone(idet->next)))
270         return AVERROR(ENOMEM);
271 
272     if (!idet->prev)
273         return 0;
274 
275     if (!idet->csp)
276         idet->csp = av_pix_fmt_desc_get(link->format);
277     if (idet->csp->comp[0].depth > 8){
278         idet->filter_line = (ff_idet_filter_func)ff_idet_filter_line_c_16bit;
279 #if ARCH_X86
280         ff_idet_init_x86(idet, 1);
281 #endif
282     }
283 
284     if (idet->analyze_interlaced_flag) {
285         if (idet->cur->interlaced_frame) {
286             idet->cur->interlaced_frame = 0;
287             filter(ctx);
288             if (idet->last_type == PROGRESSIVE) {
289                 idet->interlaced_flag_accuracy --;
290                 idet->analyze_interlaced_flag --;
291             } else if (idet->last_type != UNDETERMINED) {
292                 idet->interlaced_flag_accuracy ++;
293                 idet->analyze_interlaced_flag --;
294             }
295             if (idet->analyze_interlaced_flag == 1) {
296                 ff_filter_frame(ctx->outputs[0], av_frame_clone(idet->cur));
297 
298                 if (idet->next->interlaced_frame && idet->interlaced_flag_accuracy < 0)
299                     idet->next->interlaced_frame = 0;
300                 idet->analyze_interlaced_flag_done = 1;
301                 av_log(ctx, AV_LOG_INFO, "Final flag accuracy %d\n", idet->interlaced_flag_accuracy);
302                 return ff_filter_frame(ctx->outputs[0], av_frame_clone(idet->next));
303             }
304         }
305     } else {
306         filter(ctx);
307     }
308 
309     return ff_filter_frame(ctx->outputs[0], av_frame_clone(idet->cur));
310 }
311 
request_frame(AVFilterLink * link)312 static int request_frame(AVFilterLink *link)
313 {
314     AVFilterContext *ctx = link->src;
315     IDETContext *idet = ctx->priv;
316     int ret;
317 
318     if (idet->eof)
319         return AVERROR_EOF;
320 
321     ret = ff_request_frame(link->src->inputs[0]);
322 
323     if (ret == AVERROR_EOF && idet->cur && !idet->analyze_interlaced_flag_done) {
324         AVFrame *next = av_frame_clone(idet->next);
325 
326         if (!next)
327             return AVERROR(ENOMEM);
328 
329         ret = filter_frame(link->src->inputs[0], next);
330         idet->eof = 1;
331     }
332 
333     return ret;
334 }
335 
uninit(AVFilterContext * ctx)336 static av_cold void uninit(AVFilterContext *ctx)
337 {
338     IDETContext *idet = ctx->priv;
339 
340     av_log(ctx, AV_LOG_INFO, "Repeated Fields: Neither:%6"PRId64" Top:%6"PRId64" Bottom:%6"PRId64"\n",
341            idet->total_repeats[REPEAT_NONE],
342            idet->total_repeats[REPEAT_TOP],
343            idet->total_repeats[REPEAT_BOTTOM]
344         );
345     av_log(ctx, AV_LOG_INFO, "Single frame detection: TFF:%6"PRId64" BFF:%6"PRId64" Progressive:%6"PRId64" Undetermined:%6"PRId64"\n",
346            idet->total_prestat[TFF],
347            idet->total_prestat[BFF],
348            idet->total_prestat[PROGRESSIVE],
349            idet->total_prestat[UNDETERMINED]
350         );
351     av_log(ctx, AV_LOG_INFO, "Multi frame detection: TFF:%6"PRId64" BFF:%6"PRId64" Progressive:%6"PRId64" Undetermined:%6"PRId64"\n",
352            idet->total_poststat[TFF],
353            idet->total_poststat[BFF],
354            idet->total_poststat[PROGRESSIVE],
355            idet->total_poststat[UNDETERMINED]
356         );
357 
358     av_frame_free(&idet->prev);
359     av_frame_free(&idet->cur );
360     av_frame_free(&idet->next);
361 }
362 
363 static const enum AVPixelFormat pix_fmts[] = {
364     AV_PIX_FMT_YUV420P,
365     AV_PIX_FMT_YUV422P,
366     AV_PIX_FMT_YUV444P,
367     AV_PIX_FMT_YUV410P,
368     AV_PIX_FMT_YUV411P,
369     AV_PIX_FMT_GRAY8,
370     AV_PIX_FMT_YUVJ420P,
371     AV_PIX_FMT_YUVJ422P,
372     AV_PIX_FMT_YUVJ444P,
373     AV_PIX_FMT_GRAY16,
374     AV_PIX_FMT_YUV440P,
375     AV_PIX_FMT_YUVJ440P,
376     AV_PIX_FMT_YUV420P9,
377     AV_PIX_FMT_YUV422P9,
378     AV_PIX_FMT_YUV444P9,
379     AV_PIX_FMT_YUV420P10,
380     AV_PIX_FMT_YUV422P10,
381     AV_PIX_FMT_YUV444P10,
382     AV_PIX_FMT_YUV420P12,
383     AV_PIX_FMT_YUV422P12,
384     AV_PIX_FMT_YUV444P12,
385     AV_PIX_FMT_YUV420P14,
386     AV_PIX_FMT_YUV422P14,
387     AV_PIX_FMT_YUV444P14,
388     AV_PIX_FMT_YUV420P16,
389     AV_PIX_FMT_YUV422P16,
390     AV_PIX_FMT_YUV444P16,
391     AV_PIX_FMT_YUVA420P,
392     AV_PIX_FMT_YUVA422P,
393     AV_PIX_FMT_YUVA444P,
394     AV_PIX_FMT_NONE
395 };
396 
init(AVFilterContext * ctx)397 static av_cold int init(AVFilterContext *ctx)
398 {
399     IDETContext *idet = ctx->priv;
400 
401     idet->eof = 0;
402     idet->last_type = UNDETERMINED;
403     memset(idet->history, UNDETERMINED, HIST_SIZE);
404 
405     if( idet->half_life > 0 )
406         idet->decay_coefficient = lrint( PRECISION * exp2(-1.0 / idet->half_life) );
407     else
408         idet->decay_coefficient = PRECISION;
409 
410     idet->filter_line = ff_idet_filter_line_c;
411 
412 #if ARCH_X86
413     ff_idet_init_x86(idet, 0);
414 #endif
415 
416     return 0;
417 }
418 
419 static const AVFilterPad idet_inputs[] = {
420     {
421         .name         = "default",
422         .type         = AVMEDIA_TYPE_VIDEO,
423         .filter_frame = filter_frame,
424     },
425 };
426 
427 static const AVFilterPad idet_outputs[] = {
428     {
429         .name         = "default",
430         .type         = AVMEDIA_TYPE_VIDEO,
431         .request_frame = request_frame
432     },
433 };
434 
435 const AVFilter ff_vf_idet = {
436     .name          = "idet",
437     .description   = NULL_IF_CONFIG_SMALL("Interlace detect Filter."),
438     .priv_size     = sizeof(IDETContext),
439     .init          = init,
440     .uninit        = uninit,
441     .flags         = AVFILTER_FLAG_METADATA_ONLY,
442     FILTER_INPUTS(idet_inputs),
443     FILTER_OUTPUTS(idet_outputs),
444     FILTER_PIXFMTS_ARRAY(pix_fmts),
445     .priv_class    = &idet_class,
446 };
447