1 /*
2  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
3  * Copyright (c) 2014 Clément Bœsch <u pkh me>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
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 GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 /**
23  * @file
24  * Codec debug viewer filter.
25  *
26  * All the MV drawing code from Michael Niedermayer is extracted from
27  * libavcodec/mpegvideo.c.
28  *
29  * TODO: segmentation
30  */
31 
32 #include "libavutil/imgutils.h"
33 #include "libavutil/motion_vector.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/video_enc_params.h"
36 #include "avfilter.h"
37 #include "qp_table.h"
38 #include "internal.h"
39 
40 #define MV_P_FOR  (1<<0)
41 #define MV_B_FOR  (1<<1)
42 #define MV_B_BACK (1<<2)
43 #define MV_TYPE_FOR  (1<<0)
44 #define MV_TYPE_BACK (1<<1)
45 #define FRAME_TYPE_I (1<<0)
46 #define FRAME_TYPE_P (1<<1)
47 #define FRAME_TYPE_B (1<<2)
48 
49 typedef struct CodecViewContext {
50     const AVClass *class;
51     unsigned mv;
52     unsigned frame_type;
53     unsigned mv_type;
54     int hsub, vsub;
55     int qp;
56     int block;
57 } CodecViewContext;
58 
59 #define OFFSET(x) offsetof(CodecViewContext, x)
60 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
61 #define CONST(name, help, val, unit) { name, help, 0, AV_OPT_TYPE_CONST, {.i64=val}, 0, 0, FLAGS, unit }
62 
63 static const AVOption codecview_options[] = {
64     { "mv", "set motion vectors to visualize", OFFSET(mv), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, INT_MAX, FLAGS, "mv" },
65         CONST("pf", "forward predicted MVs of P-frames",  MV_P_FOR,  "mv"),
66         CONST("bf", "forward predicted MVs of B-frames",  MV_B_FOR,  "mv"),
67         CONST("bb", "backward predicted MVs of B-frames", MV_B_BACK, "mv"),
68     { "qp", NULL, OFFSET(qp), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, .flags = FLAGS },
69     { "mv_type", "set motion vectors type", OFFSET(mv_type), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, INT_MAX, FLAGS, "mv_type" },
70     { "mvt",     "set motion vectors type", OFFSET(mv_type), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, INT_MAX, FLAGS, "mv_type" },
71         CONST("fp", "forward predicted MVs",  MV_TYPE_FOR,  "mv_type"),
72         CONST("bp", "backward predicted MVs", MV_TYPE_BACK, "mv_type"),
73     { "frame_type", "set frame types to visualize motion vectors of", OFFSET(frame_type), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, INT_MAX, FLAGS, "frame_type" },
74     { "ft",         "set frame types to visualize motion vectors of", OFFSET(frame_type), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, INT_MAX, FLAGS, "frame_type" },
75         CONST("if", "I-frames", FRAME_TYPE_I, "frame_type"),
76         CONST("pf", "P-frames", FRAME_TYPE_P, "frame_type"),
77         CONST("bf", "B-frames", FRAME_TYPE_B, "frame_type"),
78     { "block",      "set block partitioning structure to visualize", OFFSET(block), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
79     { NULL }
80 };
81 
82 AVFILTER_DEFINE_CLASS(codecview);
83 
clip_line(int *sx, int *sy, int *ex, int *ey, int maxx)84 static int clip_line(int *sx, int *sy, int *ex, int *ey, int maxx)
85 {
86     if(*sx > *ex)
87         return clip_line(ex, ey, sx, sy, maxx);
88 
89     if (*sx < 0) {
90         if (*ex < 0)
91             return 1;
92         *sy = *ey + (*sy - *ey) * (int64_t)*ex / (*ex - *sx);
93         *sx = 0;
94     }
95 
96     if (*ex > maxx) {
97         if (*sx > maxx)
98             return 1;
99         *ey = *sy + (*ey - *sy) * (int64_t)(maxx - *sx) / (*ex - *sx);
100         *ex = maxx;
101     }
102     return 0;
103 }
104 
105 /**
106  * Draw a line from (ex, ey) -> (sx, sy).
107  * @param w width of the image
108  * @param h height of the image
109  * @param stride stride/linesize of the image
110  * @param color color of the arrow
111  */
draw_line(uint8_t *buf, int sx, int sy, int ex, int ey, int w, int h, int stride, int color)112 static void draw_line(uint8_t *buf, int sx, int sy, int ex, int ey,
113                       int w, int h, int stride, int color)
114 {
115     int x, y, fr, f;
116 
117     if (clip_line(&sx, &sy, &ex, &ey, w - 1))
118         return;
119     if (clip_line(&sy, &sx, &ey, &ex, h - 1))
120         return;
121 
122     sx = av_clip(sx, 0, w - 1);
123     sy = av_clip(sy, 0, h - 1);
124     ex = av_clip(ex, 0, w - 1);
125     ey = av_clip(ey, 0, h - 1);
126 
127     buf[sy * stride + sx] += color;
128 
129     if (FFABS(ex - sx) > FFABS(ey - sy)) {
130         if (sx > ex) {
131             FFSWAP(int, sx, ex);
132             FFSWAP(int, sy, ey);
133         }
134         buf += sx + sy * stride;
135         ex  -= sx;
136         f    = ((ey - sy) * (1 << 16)) / ex;
137         for (x = 0; x <= ex; x++) {
138             y  = (x * f) >> 16;
139             fr = (x * f) & 0xFFFF;
140                    buf[ y      * stride + x] += (color * (0x10000 - fr)) >> 16;
141             if(fr) buf[(y + 1) * stride + x] += (color *            fr ) >> 16;
142         }
143     } else {
144         if (sy > ey) {
145             FFSWAP(int, sx, ex);
146             FFSWAP(int, sy, ey);
147         }
148         buf += sx + sy * stride;
149         ey  -= sy;
150         if (ey)
151             f = ((ex - sx) * (1 << 16)) / ey;
152         else
153             f = 0;
154         for(y= 0; y <= ey; y++){
155             x  = (y*f) >> 16;
156             fr = (y*f) & 0xFFFF;
157                    buf[y * stride + x    ] += (color * (0x10000 - fr)) >> 16;
158             if(fr) buf[y * stride + x + 1] += (color *            fr ) >> 16;
159         }
160     }
161 }
162 
163 /**
164  * Draw an arrow from (ex, ey) -> (sx, sy).
165  * @param w width of the image
166  * @param h height of the image
167  * @param stride stride/linesize of the image
168  * @param color color of the arrow
169  */
draw_arrow(uint8_t *buf, int sx, int sy, int ex, int ey, int w, int h, int stride, int color, int tail, int direction)170 static void draw_arrow(uint8_t *buf, int sx, int sy, int ex,
171                        int ey, int w, int h, int stride, int color, int tail, int direction)
172 {
173     int dx,dy;
174 
175     if (direction) {
176         FFSWAP(int, sx, ex);
177         FFSWAP(int, sy, ey);
178     }
179 
180     sx = av_clip(sx, -100, w + 100);
181     sy = av_clip(sy, -100, h + 100);
182     ex = av_clip(ex, -100, w + 100);
183     ey = av_clip(ey, -100, h + 100);
184 
185     dx = ex - sx;
186     dy = ey - sy;
187 
188     if (dx * dx + dy * dy > 3 * 3) {
189         int rx =  dx + dy;
190         int ry = -dx + dy;
191         int length = sqrt((rx * rx + ry * ry) << 8);
192 
193         // FIXME subpixel accuracy
194         rx = ROUNDED_DIV(rx * (3 << 4), length);
195         ry = ROUNDED_DIV(ry * (3 << 4), length);
196 
197         if (tail) {
198             rx = -rx;
199             ry = -ry;
200         }
201 
202         draw_line(buf, sx, sy, sx + rx, sy + ry, w, h, stride, color);
203         draw_line(buf, sx, sy, sx - ry, sy + rx, w, h, stride, color);
204     }
205     draw_line(buf, sx, sy, ex, ey, w, h, stride, color);
206 }
207 
draw_block_rectangle(uint8_t *buf, int sx, int sy, int w, int h, int stride, int color)208 static void draw_block_rectangle(uint8_t *buf, int sx, int sy, int w, int h, int stride, int color)
209 {
210     for (int x = sx; x < sx + w; x++)
211         buf[x] = color;
212 
213     for (int y = sy; y < sy + h; y++) {
214         buf[sx] = color;
215         buf[sx + w - 1] = color;
216         buf += stride;
217     }
218 
219     for (int x = sx; x < sx + w; x++)
220         buf[x] = color;
221 }
222 
filter_frame(AVFilterLink *inlink, AVFrame *frame)223 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
224 {
225     AVFilterContext *ctx = inlink->dst;
226     CodecViewContext *s = ctx->priv;
227     AVFilterLink *outlink = ctx->outputs[0];
228 
229     if (s->qp) {
230         enum AVVideoEncParamsType qp_type;
231         int qstride, ret;
232         int8_t *qp_table;
233 
234         ret = ff_qp_table_extract(frame, &qp_table, &qstride, NULL, &qp_type);
235         if (ret < 0) {
236             av_frame_free(&frame);
237             return ret;
238         }
239 
240         if (qp_table) {
241             int x, y;
242             const int w = AV_CEIL_RSHIFT(frame->width,  s->hsub);
243             const int h = AV_CEIL_RSHIFT(frame->height, s->vsub);
244             uint8_t *pu = frame->data[1];
245             uint8_t *pv = frame->data[2];
246             const int lzu = frame->linesize[1];
247             const int lzv = frame->linesize[2];
248 
249             for (y = 0; y < h; y++) {
250                 for (x = 0; x < w; x++) {
251                     const int qp = ff_norm_qscale(qp_table[(y >> 3) * qstride + (x >> 3)], qp_type) * 128/31;
252                     pu[x] = pv[x] = qp;
253                 }
254                 pu += lzu;
255                 pv += lzv;
256             }
257         }
258         av_freep(&qp_table);
259     }
260 
261     if (s->block) {
262         AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_VIDEO_ENC_PARAMS);
263         if (sd) {
264             AVVideoEncParams *par = (AVVideoEncParams*)sd->data;
265             const int stride = frame->linesize[0];
266 
267             if (par->nb_blocks) {
268                 for (int block_idx = 0; block_idx < par->nb_blocks; block_idx++) {
269                     AVVideoBlockParams *b = av_video_enc_params_block(par, block_idx);
270                     uint8_t *buf = frame->data[0] + b->src_y * stride;
271 
272                     draw_block_rectangle(buf, b->src_x, b->src_y, b->w, b->h, stride, 100);
273                 }
274             }
275         }
276     }
277 
278     if (s->mv || s->mv_type) {
279         AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_MOTION_VECTORS);
280         if (sd) {
281             int i;
282             const AVMotionVector *mvs = (const AVMotionVector *)sd->data;
283             const int is_iframe = (s->frame_type & FRAME_TYPE_I) && frame->pict_type == AV_PICTURE_TYPE_I;
284             const int is_pframe = (s->frame_type & FRAME_TYPE_P) && frame->pict_type == AV_PICTURE_TYPE_P;
285             const int is_bframe = (s->frame_type & FRAME_TYPE_B) && frame->pict_type == AV_PICTURE_TYPE_B;
286 
287             for (i = 0; i < sd->size / sizeof(*mvs); i++) {
288                 const AVMotionVector *mv = &mvs[i];
289                 const int direction = mv->source > 0;
290 
291                 if (s->mv_type) {
292                     const int is_fp = direction == 0 && (s->mv_type & MV_TYPE_FOR);
293                     const int is_bp = direction == 1 && (s->mv_type & MV_TYPE_BACK);
294 
295                     if ((!s->frame_type && (is_fp || is_bp)) ||
296                         is_iframe && is_fp || is_iframe && is_bp ||
297                         is_pframe && is_fp ||
298                         is_bframe && is_fp || is_bframe && is_bp)
299                         draw_arrow(frame->data[0], mv->dst_x, mv->dst_y, mv->src_x, mv->src_y,
300                                    frame->width, frame->height, frame->linesize[0],
301                                    100, 0, direction);
302                 } else if (s->mv)
303                     if ((direction == 0 && (s->mv & MV_P_FOR)  && frame->pict_type == AV_PICTURE_TYPE_P) ||
304                         (direction == 0 && (s->mv & MV_B_FOR)  && frame->pict_type == AV_PICTURE_TYPE_B) ||
305                         (direction == 1 && (s->mv & MV_B_BACK) && frame->pict_type == AV_PICTURE_TYPE_B))
306                         draw_arrow(frame->data[0], mv->dst_x, mv->dst_y, mv->src_x, mv->src_y,
307                                    frame->width, frame->height, frame->linesize[0],
308                                    100, 0, direction);
309             }
310         }
311     }
312 
313     return ff_filter_frame(outlink, frame);
314 }
315 
config_input(AVFilterLink *inlink)316 static int config_input(AVFilterLink *inlink)
317 {
318     AVFilterContext *ctx = inlink->dst;
319     CodecViewContext *s = ctx->priv;
320     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
321 
322     s->hsub = desc->log2_chroma_w;
323     s->vsub = desc->log2_chroma_h;
324     return 0;
325 }
326 
327 static const AVFilterPad codecview_inputs[] = {
328     {
329         .name           = "default",
330         .type           = AVMEDIA_TYPE_VIDEO,
331         .flags          = AVFILTERPAD_FLAG_NEEDS_WRITABLE,
332         .filter_frame   = filter_frame,
333         .config_props   = config_input,
334     },
335 };
336 
337 static const AVFilterPad codecview_outputs[] = {
338     {
339         .name = "default",
340         .type = AVMEDIA_TYPE_VIDEO,
341     },
342 };
343 
344 const AVFilter ff_vf_codecview = {
345     .name          = "codecview",
346     .description   = NULL_IF_CONFIG_SMALL("Visualize information about some codecs."),
347     .priv_size     = sizeof(CodecViewContext),
348     FILTER_INPUTS(codecview_inputs),
349     FILTER_OUTPUTS(codecview_outputs),
350     // TODO: we can probably add way more pixel formats without any other
351     // changes; anything with 8-bit luma in first plane should be working
352     FILTER_SINGLE_PIXFMT(AV_PIX_FMT_YUV420P),
353     .priv_class    = &codecview_class,
354     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
355 };
356