9f570526ec4fe4f6cef91035ad7746fe13d414c7
[goodguy/history.git] / cinelerra-5.1 / cinelerra / pluginfclient.C
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include <ctype.h>
7
8 #include "bcwindowbase.h"
9 #include "bctitle.h"
10 #include "cstrdup.h"
11 #include "language.h"
12 #include "mwindow.h"
13 #include "pluginfclient.h"
14 #include "pluginserver.h"
15 #include "samples.h"
16 #include "vframe.h"
17 #include "filexml.h"
18
19
20 static void ff_err(int ret, const char *fmt, ...)
21 {
22         char msg[BCTEXTLEN];
23         va_list ap;
24         va_start(ap, fmt);
25         vsnprintf(msg, sizeof(msg), fmt, ap);
26         va_end(ap);
27         char errmsg[BCSTRLEN];
28         av_strerror(ret, errmsg, sizeof(errmsg));
29         fprintf(stderr,_("%s  err: %s\n"),msg, errmsg);
30 }
31
32 PluginFClientConfig::PluginFClientConfig()
33 {
34         ffilt = 0;
35 }
36
37 PluginFClientConfig::~PluginFClientConfig()
38 {
39         delete ffilt;
40         remove_all_objects();
41 }
42
43 int PluginFClientConfig::equivalent(PluginFClientConfig &that)
44 {
45         PluginFClientConfig &conf = *this;
46         for( int i=0; i<that.size(); ++i ) {
47                 PluginFClient_Opt *topt = conf[i], *vopt = that[i];
48                 char tval[BCTEXTLEN], *tp = topt->get(tval, sizeof(tval));
49                 char vval[BCTEXTLEN], *vp = vopt->get(vval, sizeof(vval));
50                 int ret = tp && vp ? strcmp(tp, vp) : tp || vp ? 1 : 0;
51                 if( ret ) return 0;
52         }
53         return 1;
54 }
55
56 void PluginFClientConfig::copy_from(PluginFClientConfig &that)
57 {
58         PluginFClientConfig &conf = *this;
59         for( int i=0; i<that.size(); ++i ) {
60                 PluginFClient_Opt *vp = that[i];
61                 const char *nm = vp->opt->name;
62                 int k = size();
63                 while( --k >= 0 && strcmp(nm, conf[k]->opt->name) );
64                 if( k < 0 ) continue;
65                 PluginFClient_Opt *fopt = conf[k];
66                 char str[BCTEXTLEN], *sp = vp->get(str, sizeof(str));
67                 if( sp ) fopt->set(sp);
68         }
69 }
70
71 void PluginFClientConfig::interpolate(PluginFClientConfig &prev, PluginFClientConfig &next,
72         int64_t prev_frame, int64_t next_frame, int64_t current_frame)
73 {
74         copy_from(prev);
75 }
76
77 void PluginFClientConfig::initialize(const char *name)
78 {
79         delete ffilt;
80         ffilt = PluginFFilter::new_ffilter(name);
81         const AVOption *opt = 0;
82         void *obj = ffilt->filter_config();
83
84         const AVClass *filt_class = ffilt->filter_class();
85         if( filt_class && filt_class->option ) {
86                 PluginFClientConfig &conf = *this;
87                 while( (opt=av_opt_next(obj, opt)) != 0 ) {
88                         if( opt->type == AV_OPT_TYPE_CONST ) continue;
89                         int dupl = 0;
90                         for( int i=0; !dupl && i<size(); ++i ) {
91                                 PluginFClient_Opt *fp = conf[i];
92                                 const AVOption *op = fp->opt;
93                                 if( op->offset != opt->offset ) continue;
94                                 if( op->type != opt->type ) continue;
95                                 dupl = 1;
96                                 if( strlen(op->name) < strlen(opt->name) )
97                                         fp->opt = opt;
98                         }
99                         if( dupl ) continue;
100                         PluginFClient_Opt *fopt = new PluginFClient_Opt(this, opt);
101                         append(fopt);
102                 }
103         }
104         if( (ffilt->filter->flags & AVFILTER_FLAG_SLICE_THREADS) != 0 ) {
105                 opt = av_opt_find(ffilt->fctx, "threads", NULL, 0, 0);
106                 if( opt ) {
107                         PluginFClient_Opt *fopt = new PluginFClient_Opt(this, opt);
108                         append(fopt);
109                 }
110         }
111 }
112
113 int PluginFClientConfig::update()
114 {
115         int ret = 0;
116         PluginFClientConfig &conf = *this;
117
118         for( int i=0; i<size(); ++i ) {
119                 PluginFClient_Opt *fopt = conf[i];
120                 char val[BCTEXTLEN], *vp = fopt->get(val, sizeof(val));
121                 if( !vp || !strcmp(val, fopt->item_value->get_text()) ) continue;
122                 fopt->item_value->update();
123                 ++ret;
124         }
125         return ret;
126 }
127
128 void PluginFClientConfig::dump(FILE *fp)
129 {
130         const AVOption *opt = 0;
131         const AVClass *obj = filter_class();
132         PluginFClientConfig &conf = *this;
133
134         while( (opt=av_opt_next(&obj, opt)) != 0 ) {
135                 if( opt->type == AV_OPT_TYPE_CONST ) continue;
136                 int k = size();
137                 while( --k >= 0 && strcmp(opt->name, conf[k]->opt->name) );
138                 if( k < 0 ) continue;
139                 PluginFClient_Opt *fopt = conf[k];
140                 char val[BCTEXTLEN], *vp = fopt->get(val,sizeof(val));
141                 fprintf(fp, "  %s:=%s", opt->name, vp);
142                 if( opt->unit ) {
143                         char unt[BCTEXTLEN], *up = unt;
144                         fopt->units(up);
145                         fprintf(fp, "%s", unt);
146                 }
147                 fprintf(fp, "\n");
148         }
149 }
150
151 PluginFClientReset::
152 PluginFClientReset(PluginFClientWindow *fwin, int x, int y)
153  : BC_GenericButton(x, y, _("Reset"))
154 {
155         this->fwin = fwin;
156 }
157
158 PluginFClientReset::
159 ~PluginFClientReset()
160 {
161 }
162
163 int PluginFClientReset::handle_event()
164 {
165         fwin->ffmpeg->config.initialize(fwin->ffmpeg->name);
166         if( fwin->ffmpeg->config.update() > 0 )
167                 fwin->draw();
168         fwin->ffmpeg->plugin->send_configure_change();
169         return 1;
170 }
171
172 PluginFClientText::
173 PluginFClientText(PluginFClientWindow *fwin, int x, int y, int w)
174  : BC_TextBox(x, y, w, 1, (char *)"")
175 {
176         this->fwin = fwin;
177 }
178
179 PluginFClientText::
180 ~PluginFClientText()
181 {
182 }
183
184 int PluginFClientText::handle_event()
185 {
186         return 0;
187 }
188
189 PluginFClientUnits::
190 PluginFClientUnits(PluginFClientWindow *fwin, int x, int y, int w)
191  : BC_PopupMenu(x, y, w, "")
192 {
193         this->fwin = fwin;
194 }
195
196 PluginFClientUnits::
197 ~PluginFClientUnits()
198 {
199 }
200
201 int PluginFClientUnits::handle_event()
202 {
203         const char *text = get_text();
204         if( text && fwin->selected ) {
205                 if( text ) fwin->selected->set(text);
206                 fwin->selected->item_value->update();
207                 fwin->draw();
208                 fwin->ffmpeg->plugin->send_configure_change();
209         }
210         return 1;
211 }
212
213 PluginFClientApply::
214 PluginFClientApply(PluginFClientWindow *fwin, int x, int y)
215  : BC_GenericButton(x, y, _("Apply"))
216 {
217         this->fwin = fwin;
218 }
219
220 PluginFClientApply::
221 ~PluginFClientApply()
222 {
223 }
224
225 int PluginFClientApply::handle_event()
226 {
227         const char *text = fwin->text->get_text();
228         if( text && fwin->selected ) {
229                 fwin->selected->set(text);
230                 fwin->selected->item_value->update();
231                 fwin->draw();
232                 fwin->ffmpeg->plugin->send_configure_change();
233         }
234         return 1;
235 }
236
237
238 PluginFClient_OptPanel::
239 PluginFClient_OptPanel(PluginFClientWindow *fwin, int x, int y, int w, int h)
240  : BC_ListBox(x, y, w, h, LISTBOX_TEXT), opts(items[0]), vals(items[1])
241 {
242         this->fwin = fwin;
243         update();  // init col/wid/columns
244 }
245
246 PluginFClient_OptPanel::
247 ~PluginFClient_OptPanel()
248 {
249 }
250
251 void PluginFClient_OptPanel::create_objects()
252 {
253         PluginFClientConfig &fconfig = fwin->ffmpeg->config;
254         for( int i=0; i<fconfig.size(); ++i ) {
255                 PluginFClient_Opt *opt = fconfig[i];
256                 opts.append(opt->item_name);
257                 vals.append(opt->item_value);
258         }
259 }
260
261 int PluginFClient_OptPanel::cursor_leave_event()
262 {
263         hide_tooltip();
264         return 0;
265 }
266
267 void PluginFClientWindow::update(PluginFClient_Opt *opt)
268 {
269         if( selected != opt ) {
270                 if( selected ) selected->item_name->set_selected(0);
271                 selected = opt;
272                 if( selected ) selected->item_name->set_selected(1);
273         }
274         clear_box(0,0, 0,panel->get_y());
275         char str[BCTEXTLEN], *sp;
276         *(sp=str) = 0;
277         if( opt ) opt->types(sp);
278         type->update(str);
279         *(sp=str) = 0;
280         if( opt ) opt->ranges(sp);
281         range->update(str);
282         while( units->total_items() ) units->del_item(0);
283         ArrayList<const AVOption *> opts;
284         int n = !opt ? 0 : opt->units(opts);
285         for( int i=0; i<n; ++i )
286                 units->add_item(new BC_MenuItem(opts[i]->name, 0));
287         char unit[BCSTRLEN];  strcpy(unit, "()");
288         if( units->total_items() && opt && opt->opt->unit )
289                 strcpy(unit, opt->opt->unit);
290         units->set_text(unit);
291         char val[BCTEXTLEN];  val[0] = 0;
292         if( opt ) opt->get(val, sizeof(val));
293         text->update(val);
294
295         panel->update();
296 }
297
298 int PluginFClient_OptPanel::selection_changed()
299 {
300         PluginFClient_Opt *opt = 0;
301         BC_ListBoxItem *item = get_selection(0, 0);
302         if( item ) {
303                 PluginFClient_OptName *opt_name = (PluginFClient_OptName *)item;
304                 opt = opt_name->opt;
305         }
306         fwin->update(opt);
307         fwin->panel->set_tooltip(!opt ? 0 : opt->tip());
308         fwin->panel->show_tooltip();
309         return 1;
310 }
311
312 void *PluginFClient_Opt::filter_config()
313 {
314         return conf->filter_config();
315 }
316 const AVClass *PluginFClient_Opt::filter_class()
317 {
318         return conf->filter_class();
319 }
320
321 int PluginFClient_Opt::types(char *rp)
322 {
323         const char *cp;
324         switch (opt->type) {
325         case AV_OPT_TYPE_FLAGS: cp = "<flags>";  break;
326         case AV_OPT_TYPE_INT: cp = "<int>"; break;
327         case AV_OPT_TYPE_INT64: cp = "<int64>"; break;
328         case AV_OPT_TYPE_DOUBLE: cp = "<double>"; break;
329         case AV_OPT_TYPE_FLOAT: cp = "<float>"; break;
330         case AV_OPT_TYPE_STRING: cp = "<string>"; break;
331         case AV_OPT_TYPE_RATIONAL: cp = "<rational>"; break;
332         case AV_OPT_TYPE_BINARY: cp = "<binary>"; break;
333         case AV_OPT_TYPE_IMAGE_SIZE: cp = "<image_size>"; break;
334         case AV_OPT_TYPE_VIDEO_RATE: cp = "<video_rate>"; break;
335         case AV_OPT_TYPE_PIXEL_FMT: cp = "<pix_fmt>"; break;
336         case AV_OPT_TYPE_SAMPLE_FMT: cp = "<sample_fmt>"; break;
337         case AV_OPT_TYPE_DURATION: cp = "<duration>"; break;
338         case AV_OPT_TYPE_COLOR: cp = "<color>"; break;
339         case AV_OPT_TYPE_CHANNEL_LAYOUT: cp = "<channel_layout>";  break;
340         default: cp = "<undef>";  break;
341         }
342         return sprintf(rp, "%s", cp);
343 }
344 int PluginFClient_Opt::scalar(double d, char *rp)
345 {
346         const char *cp = 0;
347              if( d == INT_MAX ) cp = "INT_MAX";
348         else if( d == INT_MIN ) cp = "INT_MIN";
349         else if( d == UINT32_MAX ) cp = "UINT32_MAX";
350         else if( d == (double)INT64_MAX ) cp = "I64_MAX";
351         else if( d == INT64_MIN ) cp = "I64_MIN";
352         else if( d == FLT_MAX ) cp = "FLT_MAX";
353         else if( d == FLT_MIN ) cp = "FLT_MIN";
354         else if( d == -FLT_MAX ) cp = "-FLT_MAX";
355         else if( d == -FLT_MIN ) cp = "-FLT_MIN";
356         else if( d == DBL_MAX ) cp = "DBL_MAX";
357         else if( d == DBL_MIN ) cp = "DBL_MIN";
358         else if( d == -DBL_MAX ) cp = "-DBL_MAX";
359         else if( d == -DBL_MIN ) cp = "-DBL_MIN";
360         else if( d == 0 ) cp = signbit(d) ? "-0" : "0";
361         else if( isnan(d) ) cp = signbit(d) ? "-NAN" : "NAN";
362         else if( isinf(d) ) cp = signbit(d) ? "-INF" : "INF";
363         else return sprintf(rp, "%g", d);
364         return sprintf(rp, "%s", cp);
365 }
366
367 int PluginFClient_Opt::ranges(char *rp)
368 {
369         const AVClass *filt_class = filter_class();
370         if( !filt_class || !filt_class->option ) return 0;
371         switch (opt->type) {
372         case AV_OPT_TYPE_INT:
373         case AV_OPT_TYPE_INT64:
374         case AV_OPT_TYPE_DOUBLE:
375         case AV_OPT_TYPE_FLOAT: break;
376         default: return 0;;
377         }
378         AVOptionRanges *r = 0;
379         void *obj = &filt_class;
380         char *cp = rp;
381         if( av_opt_query_ranges(&r, obj, opt->name, AV_OPT_SEARCH_FAKE_OBJ) < 0 ) return 0;
382         for( int i=0; i<r->nb_ranges; ++i ) {
383                 cp += sprintf(cp, " (");  cp += scalar(r->range[i]->value_min, cp);
384                 cp += sprintf(cp, "..");  cp += scalar(r->range[i]->value_max, cp);
385                 cp += sprintf(cp, ")");
386         }
387         av_opt_freep_ranges(&r);
388         return cp - rp;
389 }
390
391 int PluginFClient_Opt::units(ArrayList<const AVOption *> &opts)
392 {
393         if( !this->opt->unit ) return 0;
394         const AVClass *filt_class = filter_class();
395         if( !filt_class || !filt_class->option ) return 0;
396         void *obj = &filt_class;
397         const AVOption *opt = NULL;
398         while( (opt=av_opt_next(obj, opt)) != 0 ) {
399                 if( !opt->unit ) continue;
400                 if( opt->type != AV_OPT_TYPE_CONST ) continue;
401                 if( strcmp(this->opt->unit, opt->unit) ) continue;
402                 int i = opts.size();
403                 while( --i >= 0 ) {
404                         if( opts[i]->default_val.i64 != opt->default_val.i64 ) continue;
405                         if( strlen(opts[i]->name) < strlen(opt->name) ) opts[i] = opt;
406                         break;
407                 }
408                 if( i < 0 )
409                         opts.append(opt);
410         }
411         return opts.size();
412 }
413
414 int PluginFClient_Opt::units(char *rp)
415 {
416         ArrayList<const AVOption *> opts;
417         int n = units(opts);
418         if( !n ) return 0;
419         char *cp = rp;
420         cp += sprintf(cp, " [%s:", this->opt->unit);
421         for( int i=0; i<n; ++i )
422                 cp += sprintf(cp, " %s", opts[i]->name);
423         cp += sprintf(cp, "]:");
424         return cp - rp;
425 }
426
427 const char *PluginFClient_Opt::tip()
428 {
429         return opt->help;
430 }
431
432 int PluginFClient_OptPanel::update()
433 {
434         const char *cols[] = { "option", "value", };
435         const int col1_w = 150;
436         int wids[] = { col1_w, get_w()-col1_w };
437         BC_ListBox::update(&items[0], &cols[0], &wids[0], sizeof(items)/sizeof(items[0]));
438         return 0;
439 }
440
441
442 PluginFClientWindow::PluginFClientWindow(PluginFClient *ffmpeg)
443  : PluginClientWindow(ffmpeg->plugin, 600, 300, 600, 300, 1)
444 {
445         this->ffmpeg = ffmpeg;
446         this->selected = 0;
447 }
448
449 PluginFClientWindow::~PluginFClientWindow()
450 {
451 }
452
453 void PluginFClientWindow::create_objects()
454 {
455         char string[BCTEXTLEN];
456         BC_Title *title;
457         int x = 10, y = 10;
458         const char *descr = ffmpeg->config.ffilt->description();
459         if( !descr ) descr = ffmpeg->config.ffilt->filter_name();
460         add_subwindow(title = new BC_Title(x, y, descr));
461         y += title->get_h() + 10;
462         int x0 = x;
463         sprintf(string, _("Type: "));
464         add_subwindow(title = new BC_Title(x0, y, string));
465         x0 += title->get_w() + 8;
466         add_subwindow(type = new BC_Title(x0, y, (char *)""));
467         x0 = x + 150;
468         sprintf(string, _("Range: "));
469         add_subwindow(title = new BC_Title(x0, y, string));
470         x0 += title->get_w() + 8;
471         add_subwindow(range = new BC_Title(x0, y, (char *)""));
472         int x1 = get_w() - BC_GenericButton::calculate_w(this, _("Reset")) - 8;
473         add_subwindow(reset = new PluginFClientReset(this, x1, y));
474         y += title->get_h() + 10;
475         x0 = x;
476         add_subwindow(units = new PluginFClientUnits(this, x0, y, 120));
477         x0 += units->get_w() + 8;
478         x1 = get_w() - BC_GenericButton::calculate_w(this, _("Apply")) - 8;
479         add_subwindow(apply = new PluginFClientApply(this, x1, y));
480         add_subwindow(text = new PluginFClientText(this, x0, y, x1-x0 - 8));
481         y += title->get_h() + 10;
482
483         panel_x = x;  panel_y = y;
484         panel_w = get_w()-10 - panel_x;
485         panel_h = get_h()-10 - panel_y;
486         panel = new PluginFClient_OptPanel(this, panel_x, panel_y, panel_w, panel_h);
487         add_subwindow(panel);
488         panel->create_objects();
489         ffmpeg->config.update();
490         draw();
491         show_window(1);
492 }
493
494 void PluginFClientWindow::draw()
495 {
496         update(selected);
497 }
498
499 int PluginFClientWindow::resize_event(int w, int h)
500 {
501         int x = get_w() - BC_GenericButton::calculate_w(this, _("Reset")) - 8;
502         int y = reset->get_y();
503         reset->reposition_window(x, y);
504         int x1 = get_w() - BC_GenericButton::calculate_w(this, _("Apply")) - 8;
505         int y1 = units->get_y();
506         apply->reposition_window(x1, y1);
507         int x0 = units->get_x() + units->get_w() + 8;
508         int y0 = units->get_y();
509         text->reposition_window(x0,y0, x1-x0-8);
510         panel_w = get_w()-10 - panel_x;
511         panel_h = get_h()-10 - panel_y;
512         panel->reposition_window(panel_x,panel_y, panel_w, panel_h);
513         return 1;
514 }
515
516 PluginFClient::PluginFClient(PluginClient *plugin, const char *name)
517 {
518         this->plugin = plugin;
519         this->name = name;
520         ffilt = 0;
521         fsrc = fsink = 0;
522         plugin_position = -1;
523         filter_position = -1;
524         activated = 0;
525         sprintf(title, "F_%s", name);
526         config.initialize(name);
527         curr_config.initialize(name);
528 }
529
530 PluginFClient::~PluginFClient()
531 {
532         delete ffilt;
533 }
534
535 bool PluginFClient::is_audio(const AVFilter *fp)
536 {
537         if( !fp->outputs ) return 0;
538         if( avfilter_pad_count(fp->outputs) > 1 ) return 0;
539         if( !avfilter_pad_get_name(fp->outputs, 0) ) return 0;
540         if( avfilter_pad_get_type(fp->outputs, 0) != AVMEDIA_TYPE_AUDIO ) return 0;
541         if( !fp->inputs ) return 1;
542         if( avfilter_pad_count(fp->inputs) > 1 ) return 0;
543         if( !avfilter_pad_get_name(fp->inputs, 0) ) return 0;
544         if( avfilter_pad_get_type(fp->inputs, 0) != AVMEDIA_TYPE_AUDIO ) return 0;
545         return 1;
546 }
547 bool PluginFClient::is_video(const AVFilter *fp)
548 {
549         if( !fp->outputs ) return 0;
550         if( avfilter_pad_count(fp->outputs) > 1 ) return 0;
551         if( !avfilter_pad_get_name(fp->outputs, 0) ) return 0;
552         if( avfilter_pad_get_type(fp->outputs, 0) != AVMEDIA_TYPE_VIDEO ) return 0;
553         if( !fp->inputs ) return 1;
554         if( avfilter_pad_count(fp->inputs) > 1 ) return 0;
555         if( !avfilter_pad_get_name(fp->inputs, 0) ) return 0;
556         if( avfilter_pad_get_type(fp->inputs, 0) != AVMEDIA_TYPE_VIDEO ) return 0;
557         return 1;
558 }
559
560 NEW_WINDOW_MACRO(PluginFClient, PluginFClientWindow)
561
562 int PluginFClient::load_configuration()
563 {
564         int64_t src_position =  get_source_position();
565         KeyFrame *prev_keyframe = get_prev_keyframe(src_position);
566         config.copy_from(curr_config);
567         read_data(prev_keyframe);
568         int ret = !config.equivalent(curr_config) ? 1 : 0;
569         return ret;
570 }
571
572
573 void PluginFClient::render_gui(void *data, int size)
574 {
575         PluginFClientConfig *conf = (PluginFClientConfig *)data;
576         config.copy_from(*conf);
577         KeyFrame *keyframe = plugin->server->get_keyframe();
578         save_data(keyframe);
579         update_gui();
580 }
581
582 void PluginFClient::update_gui()
583 {
584         PluginClientThread *thread = plugin->get_thread();
585         if( !thread ) return;
586         PluginFClientWindow *window = (PluginFClientWindow*)thread->get_window();
587         window->lock_window("PluginFClient::update_gui");
588         load_configuration();
589         if( config.update() > 0 )
590                 window->draw();
591         window->unlock_window();
592 }
593
594 const char *PluginFClient::plugin_title()
595 {
596         return title;
597 }
598
599 char *PluginFClient::to_upper(char *cp, const char *sp)
600 {
601         char *bp = cp;
602         while( *sp != 0 ) *bp++ = toupper(*sp++);
603         *bp = 0;
604         return cp;
605 }
606
607 void PluginFClient::save_data(KeyFrame *keyframe)
608 {
609         FileXML output;
610         char string[BCTEXTLEN];
611
612 // cause data to be stored directly in text
613         output.set_shared_output(keyframe->get_data(), MESSAGESIZE);
614         output.tag.set_title(to_upper(string, plugin_title()));
615         const AVClass *filt_class = config.filter_class();
616         if( filt_class && filt_class->option ) {
617                 void *obj = config.filter_config();
618                 const AVOption *opt = NULL;
619                 while( (opt=av_opt_next(obj, opt)) != 0 ) {
620                         uint8_t *buf = 0;
621                         if( av_opt_get(obj, opt->name, 0, &buf) < 0 ) continue;
622                         output.tag.set_property(opt->name, (const char *)buf);
623                         av_freep(&buf);
624                 }
625         }
626         if( (config.ffilt->filter->flags & AVFILTER_FLAG_SLICE_THREADS) != 0 ) {
627                 uint8_t *buf = 0;
628                 if( av_opt_get(config.ffilt->fctx, "threads", 0, &buf) >= 0 && buf ) {
629                         output.tag.set_property("threads", (const char *)buf);
630                         av_freep(&buf);
631                 }
632         }
633
634         output.append_tag();
635         output.terminate_string();
636 }
637
638 void PluginFClient::read_data(KeyFrame *keyframe)
639 {
640         FileXML input;
641         char string[BCTEXTLEN];
642         input.set_shared_input(keyframe->get_data(), strlen(keyframe->get_data()));
643
644         while( !input.read_tag() ) {
645                 to_upper(string, plugin_title());
646                 if( !input.tag.title_is(string) ) continue;
647                 const AVClass *filt_class = config.filter_class();
648                 if( filt_class && filt_class->option ) {
649                         void *obj = config.filter_config();
650                         const AVOption *opt = NULL;
651                         while( (opt=av_opt_next(obj, opt)) != 0 ) {
652                                 const char *v = input.tag.get_property(opt->name);
653                                 if( v ) av_opt_set(obj, opt->name, v, 0);
654                         }
655                         if( (config.ffilt->filter->flags & AVFILTER_FLAG_SLICE_THREADS) != 0 ) {
656                                 const char *v = input.tag.get_property("threads");
657                                 if( v ) av_opt_set(config.ffilt->fctx, "threads", v, 0);
658                         }
659                 }
660         }
661 }
662
663 int PluginFClient::activate()
664 {
665         if( fsrc )
666                 avfilter_link(fsrc, 0, ffilt->fctx, 0);
667         avfilter_link(ffilt->fctx, 0, fsink, 0);
668         int ret = avfilter_graph_config(ffilt->graph, NULL);
669         if( ret >= 0 ) {
670                 curr_config.copy_from(config);
671                 activated = 1;
672         }
673         return ret;
674 }
675
676 void PluginFClient::reactivate()
677 {
678         delete ffilt;  ffilt = 0;
679         activated = 0;
680 }
681
682 PluginFAClient::PluginFAClient(PluginServer *server, const char *name)
683  : PluginAClient(server), PluginFClient(this, name)
684 {
685 }
686
687 PluginFAClient::~PluginFAClient()
688 {
689 }
690
691 int PluginFAClient::activate()
692 {
693         if( activated ) return activated;
694         ffilt = PluginFFilter::new_ffilter(name, &config);
695         if( !ffilt ) {
696                 config.copy_from(curr_config);
697                 send_configure_change();
698                 send_render_gui(&config, sizeof(config));
699                 ffilt = PluginFFilter::new_ffilter(name, &config);
700         }
701         AVSampleFormat sample_fmt = AV_SAMPLE_FMT_FLTP;
702         int channels = PluginClient::total_in_buffers;
703         uint64_t layout = (((uint64_t)1)<<channels) - 1;
704         AVFilterGraph *graph = !ffilt ? 0 : ffilt->graph;
705         int ret = !graph ? -1 : 0;
706         if( ret >= 0 && ffilt->filter->inputs ) {
707                 char args[BCTEXTLEN];
708                 snprintf(args, sizeof(args),
709                         "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
710                         1, sample_rate, sample_rate, av_get_sample_fmt_name(sample_fmt), layout);
711                 ret = avfilter_graph_create_filter(&fsrc, avfilter_get_by_name("abuffer"),
712                         "in", args, NULL, graph);
713         }
714         if( ret >= 0 )
715                 ret = avfilter_graph_create_filter(&fsink, avfilter_get_by_name("abuffersink"),
716                         "out", NULL, NULL, graph);
717         if( ret >= 0 )
718                 ret = av_opt_set_bin(fsink, "sample_fmts",
719                         (uint8_t*)&sample_fmt, sizeof(sample_fmt), AV_OPT_SEARCH_CHILDREN);
720         if( ret >= 0 )
721                 ret = av_opt_set_bin(fsink, "channel_layouts",
722                         (uint8_t*)&layout, sizeof(layout), AV_OPT_SEARCH_CHILDREN);
723         if( ret >= 0 )
724                 ret = av_opt_set_bin(fsink, "sample_rates",
725                         (uint8_t*)&sample_rate, sizeof(sample_rate), AV_OPT_SEARCH_CHILDREN);
726         if( ret >= 0 )
727                 ret = PluginFClient::activate();
728         if( ret < 0 && activated >= 0 ) {
729                 ff_err(ret, "PluginFAClient::activate: %s failed\n", plugin_title());
730                 activated = -1;
731         }
732         return activated;
733 }
734
735
736 static AVRational best_frame_rate(double frame_rate)
737 {
738         static const int m1 = 1001*12, m2 = 1000*12;
739         static const int freqs[] = {
740                 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
741                 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
742         };
743         double max_err = 1.;
744         int freq, best_freq = 0;
745         for( int i=0; (freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12]); ++i ) {
746                 double framerate = (double)freq / m1;
747                 double err = fabs(frame_rate/framerate - 1.);
748                 if( err >= max_err ) continue;
749                 max_err = err;
750                 best_freq = freq;
751         }
752         return max_err < 0.0001 ?
753                 (AVRational) { best_freq, m1 } :
754                 (AVRational) { 0, 0 };
755 }
756
757 int PluginFVClient::activate(int width, int height, int color_model)
758 {
759         if( activated ) return activated;
760         ffilt = PluginFFilter::new_ffilter(name, &config);
761         if( !ffilt ) {
762                 config.copy_from(curr_config);
763                 send_configure_change();
764                 send_render_gui(&config, sizeof(config));
765                 ffilt = PluginFFilter::new_ffilter(name, &config);
766         }
767         AVPixelFormat pix_fmt = color_model_to_pix_fmt(color_model);
768         AVFilterGraph *graph = !ffilt ? 0 : ffilt->graph;
769         int ret = !graph ? -1 : 0;
770         if( ret >= 0 && ffilt->filter->inputs ) {
771                 curr_config.copy_from(config);
772                 if( pix_fmt == AV_PIX_FMT_NB ) {
773                         int bpp = BC_CModels::calculate_pixelsize(color_model) * 8;
774                         int bits_per_comp = bpp / BC_CModels::components(color_model);
775                         int alpha =  BC_CModels::has_alpha(color_model);
776                         pix_fmt = bits_per_comp > 8 ?
777                                 !alpha ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGBA64LE :
778                                 !alpha ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_RGBA ;
779                 }
780                 int aspect_w = 1, aspect_h = 1; // XXX
781                 AVRational best_rate = best_frame_rate(frame_rate);
782                 char args[BCTEXTLEN];
783                 snprintf(args, sizeof(args),
784                         "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
785                         width, height, pix_fmt, best_rate.num, best_rate.den, aspect_w, aspect_h);
786                 ret = avfilter_graph_create_filter(&fsrc, avfilter_get_by_name("buffer"),
787                         "in", args, NULL, graph);
788         }
789         if( ret >= 0 )
790                 ret = avfilter_graph_create_filter(&fsink, avfilter_get_by_name("buffersink"),
791                         "out", NULL, NULL, graph);
792         if( ret >= 0 )
793                 ret = av_opt_set_bin(fsink, "pix_fmts",
794                         (uint8_t*)&pix_fmt, sizeof(pix_fmt), AV_OPT_SEARCH_CHILDREN);
795         if( ret >= 0 )
796                 ret = PluginFClient::activate();
797         if( ret < 0 && activated >= 0 ) {
798                 ff_err(ret, "PluginFVClient::activate() %s\n", plugin_title());
799                 activated = -1;
800         }
801         return activated;
802 }
803
804 int PluginFAClient::get_inchannels()
805 {
806         AVFilterContext *fctx = ffilt->fctx;
807         AVFilterLink **links = !fctx->nb_inputs ? 0 : fctx->inputs;
808         return !links ? 0 : links[0]->channels;
809 }
810
811 int PluginFAClient::get_outchannels()
812 {
813         AVFilterContext *fctx = ffilt->fctx;
814         AVFilterLink **links = !fctx->nb_outputs ? 0 : fctx->outputs;
815         return !links ? 0 : links[0]->channels;
816 }
817
818 int PluginFAClient::process_buffer(int64_t size, Samples **buffer, int64_t start_position, int sample_rate)
819 {
820         int total_in = PluginClient::total_in_buffers;
821         int total_out = PluginClient::total_out_buffers;
822         int in_channels = 0, out_channels = 0;
823
824         if( load_configuration() )
825                 reactivate();
826
827         if( plugin_position != start_position )
828                 filter_position = plugin_position = start_position;
829
830         AVFrame *frame = 0;
831         int ret = activate();
832         if( ret >= 0 && !(frame = av_frame_alloc()) ) {
833                 fprintf(stderr, "PluginFAClient::process_buffer: av_frame_alloc failed\n");
834                 ret = AVERROR(ENOMEM);
835         }
836         if( ret >= 0 ) {
837                 in_channels = get_inchannels();
838                 out_channels = get_outchannels();
839                 frame->nb_samples = size;
840                 frame->format = AV_SAMPLE_FMT_FLTP;
841                 frame->channel_layout = (1<<in_channels)-1;
842                 frame->sample_rate = sample_rate;
843                 frame->pts = local_to_edl(filter_position);
844         }
845
846         int retry = 10;
847         while( ret >= 0 && --retry >= 0 ) {
848                 ret = av_buffersink_get_frame(fsink, frame);
849                 if( ret >= 0 || ret != AVERROR(EAGAIN) ) break;
850                 if( !fsrc ) { ret = AVERROR(EIO);  break; }
851                 for( int i=0; i<total_in; ++i )
852                         read_samples(buffer[i], i, sample_rate, filter_position, size);
853                 filter_position += size;
854                 ret = av_frame_get_buffer(frame, 0);
855                 if( ret < 0 ) break;
856                 float **in_buffers = (float **)&frame->extended_data[0];
857                 for(int i = 0; i < in_channels; i++) {
858                         float *in_buffer = in_buffers[i];
859                         int k = i < total_in ? i : 0;
860                         double *in_ptr = buffer[k]->get_data();
861                         for(int j = 0; j < size; j++) in_buffer[j] = in_ptr[j];
862                 }
863                 ret = av_buffersrc_add_frame_flags(fsrc, frame, 0);
864         }
865         if( ret >= 0 && retry < 0 )
866                 ret = AVERROR(EAGAIN);
867
868         if( ret >= 0 ) {
869                 int nbfrs = total_out;
870                 if( out_channels < nbfrs ) nbfrs = out_channels;
871                 float **out_buffers = (float **)&frame->extended_data[0];
872                 int i = 0;
873                 while( i < nbfrs ) {
874                         float *out_buffer = out_buffers[i];
875                         double *out_ptr = buffer[i++]->get_data();
876                         for(int j = 0; j < size; j++) out_ptr[j] = out_buffer[j];
877                 }
878                 while( i < total_out ) {
879                         double *out_ptr = buffer[i++]->get_data();
880                         bzero(out_ptr, sizeof(double) * size);
881                 }
882         }
883         if( ret < 0 ) {
884                 int64_t position = PluginFClient::get_source_position();
885                 double t0 = (double)position/sample_rate, dt = 1./sample_rate;
886                 for( int i=0; i<total_out; ++i ) {
887                         double t = t0, *out = buffer[i]->get_data();
888                         for( int k=size; --k>=0; t+=dt ) {
889                                 double w = int(2*t) & 1 ? 2*M_PI*440 : 2*M_PI*697;
890                                 *out++ = sin(t * w);
891                         }
892                 }
893                 ff_err(ret, "PluginFAClient::process_buffer() %s\n", plugin_title());
894         }
895
896         av_frame_free(&frame);
897         plugin_position += size;
898         return size;
899 }
900
901
902 PluginFVClient::PluginFVClient(PluginServer *server, const char *name)
903  : PluginVClient(server), PluginFClient(this, name)
904 {
905 }
906
907 PluginFVClient::~PluginFVClient()
908 {
909 }
910
911 int PluginFVClient::process_buffer(VFrame **frames, int64_t position, double frame_rate)
912 {
913         VFrame *vframe = *frames;
914         int width = vframe->get_w();
915         int height = vframe->get_h();
916
917         if( load_configuration() )
918                 reactivate();
919
920         if( plugin_position != position )
921                 filter_position = plugin_position = position;
922
923         int colormodel = vframe->get_color_model();
924         int ret = activate(width, height, colormodel);
925         AVPixelFormat pix_fmt = fsrc ?
926                 (AVPixelFormat) fsrc->outputs[0]->format :
927                 color_model_to_pix_fmt(colormodel);
928         if( pix_fmt <= AV_PIX_FMT_NONE || pix_fmt >= AV_PIX_FMT_NB )
929                 pix_fmt = AV_PIX_FMT_RGBA;
930
931         AVFrame *frame = 0;
932         if( ret >= 0 && !(frame = av_frame_alloc()) ) {
933                 fprintf(stderr, "PluginFVClient::process_buffer: av_frame_alloc failed\n");
934                 ret = AVERROR(ENOMEM);
935         }
936
937         int retry = 10;
938         while( ret >= 0 && --retry >= 0 ) {
939                 ret = av_buffersink_get_frame(fsink, frame);
940                 if( ret >= 0 || ret != AVERROR(EAGAIN) ) break;
941                 if( !fsrc ) { ret = AVERROR(EIO);  break; }
942                 read_frame(vframe, 0, filter_position++, frame_rate, 0);
943                 frame->format = pix_fmt;
944                 frame->width  = width;
945                 frame->height = height;
946                 frame->pts = local_to_edl(position);
947                 ret = av_frame_get_buffer(frame, 32);
948                 if( ret < 0 ) break;
949                 ret = transfer_pixfmt(vframe, frame);
950                 if( ret < 0 ) break;
951                 ret = av_buffersrc_add_frame_flags(fsrc, frame, 0);
952         }
953         if( ret >= 0 && retry < 0 )
954                 ret = AVERROR(EAGAIN);
955
956         if( ret >= 0 ) {
957                 pix_fmt = (AVPixelFormat) frame->format;
958                 ret = transfer_cmodel(vframe, frame);
959         }
960         if( ret < 0 ) {
961                 ff_err(ret, "PluginFVClient::process_buffer() %s\n", plugin_title());
962                 if( position & 1 ) vframe->clear_frame();
963         }
964
965         ++plugin_position;
966         av_frame_free(&frame);
967         return ret >= 0 ? 0 : 1;
968 }
969
970
971 PluginFClient_OptName:: PluginFClient_OptName(PluginFClient_Opt *opt)
972 {
973         this->opt = opt;
974         set_text(opt->opt->name);
975 }
976
977 PluginFClient_OptValue::PluginFClient_OptValue(PluginFClient_Opt *opt)
978 {
979         this->opt = opt;
980         update();
981 }
982
983 void PluginFClient_OptValue::update()
984 {
985         char val[BCTEXTLEN];  val[0] = 0;
986         opt->get(val, sizeof(val));
987         set_text(val);
988 }
989
990
991 PluginFClient_Opt::PluginFClient_Opt(PluginFClientConfig *conf, const AVOption *opt)
992 {
993         this->conf = conf;
994         this->opt = opt;
995         item_name = new PluginFClient_OptName(this);
996         item_value = new PluginFClient_OptValue(this);
997 }
998
999 PluginFClient_Opt::~PluginFClient_Opt()
1000 {
1001         delete item_name;
1002         delete item_value;
1003 }
1004
1005 const char *PluginFClientConfig::get(const char *name)
1006 {
1007         uint8_t *bp = 0;
1008         if( av_opt_get(filter_config(), name, 0, &bp) >= 0 ||
1009             av_opt_get(ffilt->fctx, name, 0, &bp) >= 0 )
1010                 return (const char *)bp;
1011         return 0;
1012 }
1013 char *PluginFClient_Opt::get(char *vp, int sz)
1014 {
1015         const char *val = conf->get(opt->name);
1016         if( val ) {
1017                 strncpy(vp, val, sz);
1018                 vp[sz-1] = 0;
1019         }
1020         else
1021                 vp = 0;
1022         av_freep(&val);
1023         return vp;
1024 }
1025
1026 void PluginFClientConfig::set(const char *name, const char *val)
1027 {
1028         if( av_opt_set(filter_config(), name, val, 0) < 0 )
1029                 av_opt_set(ffilt->fctx, name, val, 0);
1030 }
1031 void PluginFClient_Opt::set(const char *val)
1032 {
1033         conf->set(opt->name, val);
1034 }
1035
1036 void PluginFFilter::uninit()
1037 {
1038 }
1039
1040 static int get_defaults(const char *name, char *args)
1041 {
1042         *args = 0;
1043         char defaults_path[BCTEXTLEN];
1044         FFMPEG::set_option_path(defaults_path, "plugin.opts");
1045         FILE *fp = fopen(defaults_path,"r");
1046         if( !fp ) return 0;
1047         char ff_plugin[BCSTRLEN], ff_args[BCTEXTLEN], *ap = 0;
1048         while( fgets(ff_args, sizeof(ff_args), fp) ) {
1049                 char *cp = ff_args;
1050                 if( *cp == ';' ) continue;
1051                 if( *cp == '#' ) ++cp;
1052                 char *bp = ff_plugin, *ep = bp + sizeof(ff_plugin)-1;
1053                 while( bp < ep && *cp && *cp != '\n' && *cp != ' ' ) *bp++ = *cp++;
1054                 *bp = 0;
1055                 if( !strcmp(ff_plugin, name) ) { ap = cp;  break; }
1056         }
1057         fclose(fp);
1058         if( !ap ) return 0;
1059         if( ff_args[0] == '#' ) return -1;
1060         while( *ap == ' ' ) ++ap;
1061         while( *ap && *ap != '\n' ) *args++ = *ap++;
1062         *args = 0;
1063         return 1;
1064 }
1065
1066 bool PluginFFilter::is_audio()
1067 {
1068         return PluginFClient::is_audio(filter);
1069 }
1070
1071 bool PluginFFilter::is_video()
1072 {
1073         return PluginFClient::is_video(filter);
1074 }
1075
1076 int PluginFFilter::init(const char *name, PluginFClientConfig *conf)
1077 {
1078         char args[BCTEXTLEN];
1079         int ret = get_defaults(name, args);
1080         if( ret < 0 ) return 0;
1081         PluginFLogLevel errs(AV_LOG_ERROR);
1082         this->filter = avfilter_get_by_name(name);
1083         if( !this->filter ) return AVERROR(ENOENT);
1084         int flag_mask = AVFILTER_FLAG_DYNAMIC_INPUTS | AVFILTER_FLAG_DYNAMIC_OUTPUTS;
1085         if( filter->flags & flag_mask ) return AVERROR(EPERM);
1086         if( !this->is_audio() && !this->is_video() ) return AVERROR(EIO);
1087         this->graph = avfilter_graph_alloc();
1088         if( !this->graph ) return AVERROR(ENOMEM);
1089         static int inst = 0;
1090         char inst_name[BCSTRLEN];
1091         sprintf(inst_name,"%s_%d", name, ++inst);
1092         if( conf && (filter->flags & AVFILTER_FLAG_SLICE_THREADS) != 0 ) {
1093                 graph->thread_type = AVFILTER_THREAD_SLICE;
1094                 graph->nb_threads  = atoi(conf->get("threads"));
1095         }
1096         else {
1097                 graph->thread_type = 0;
1098                 graph->nb_threads  = 0;
1099         }
1100         fctx = avfilter_graph_alloc_filter(graph, filter, inst_name);
1101         if( !fctx ) return AVERROR(ENOMEM);
1102         fctx->thread_type = graph->thread_type; // bug in avfilter
1103         if( conf ) {
1104                 AVDictionary *opts = 0;
1105                 for( int i=0; i<conf->size(); ++i ) {
1106                         PluginFClient_Opt *op = conf->get(i);
1107                         const char *name = op->opt->name;
1108                         char val[BCTEXTLEN], *vp = op->get(val, sizeof(val));
1109                         if( !vp ) continue;
1110                         uint8_t *bp = 0;
1111 // unspecified opts cause a special behavior in some filters (lut3d)
1112 // so... if opt value is the default, skip it or no special behavior
1113                         if( av_opt_get(filter_config(), name, 0, &bp) >= 0 ) {
1114                                 int result = strcmp((const char *)bp, vp);
1115                                 av_freep(&bp);
1116                                 if( !result ) continue;
1117                         }
1118                         av_dict_set(&opts, name, vp, 0);
1119                 }
1120                 ret = avfilter_init_dict(fctx, &opts);
1121                 av_dict_free(&opts);
1122         }
1123         else
1124                 ret = avfilter_init_str(fctx, args);
1125         return ret < 0 ? ret : 1;
1126 }
1127
1128
1129 PluginFFilter::PluginFFilter()
1130 {
1131         filter = 0;
1132         graph = 0;
1133         fctx = 0;
1134 }
1135
1136 PluginFFilter::~PluginFFilter()
1137 {
1138         PluginFLogLevel errs(AV_LOG_ERROR);
1139         avfilter_graph_free(&graph);
1140         filter = 0;  fctx = 0;
1141 }
1142
1143 PluginFFilter *PluginFFilter::new_ffilter(const char *name, PluginFClientConfig *conf)
1144 {
1145         PluginFFilter *ffilt = new PluginFFilter;
1146         int ret = ffilt->init(name, conf);
1147         if( ret < 0 ) ff_err(ret, "PluginFFilter::new_ffilter(%s)\n", name);
1148         if( ret <= 0 ) { delete ffilt;  ffilt = 0; }
1149         return ffilt;
1150 }
1151
1152 PluginClient *PluginServer::new_ffmpeg_plugin()
1153 {
1154         const AVFilter *filter = avfilter_get_by_name(ff_name);
1155         if( !filter ) return 0;
1156         PluginFClient *ffmpeg =
1157                 PluginFClient::is_audio(filter) ?
1158                         (PluginFClient *)new PluginFAClient(this, ff_name) :
1159                 PluginFClient::is_video(filter) ?
1160                         (PluginFClient *)new PluginFVClient(this, ff_name) :
1161                 0;
1162         if( !ffmpeg ) return 0;
1163         return ffmpeg->plugin;
1164 }
1165
1166
1167 PluginServer* MWindow::new_ffmpeg_server(MWindow *mwindow, const char *name)
1168 {
1169         PluginFFilter *ffilt = PluginFFilter::new_ffilter(name);
1170         if( !ffilt ) return 0;
1171         delete ffilt;
1172         return new PluginServer(mwindow, (char*)name, PLUGIN_TYPE_FFMPEG);
1173 }
1174
1175 void MWindow::init_ffmpeg_index(MWindow *mwindow, Preferences *preferences, FILE *fp)
1176 {
1177         PluginFLogLevel errs(AV_LOG_ERROR);
1178         const AVFilter *filter = 0;  void *idx = 0;
1179         while( (filter=av_filter_iterate(&idx)) != 0 ) {
1180 //printf("%s\n",filter->name);
1181                 PluginServer *server = new_ffmpeg_server(mwindow, filter->name);
1182                 if( server ) {
1183                         int result = server->open_plugin(1, preferences, 0, 0);
1184                         if( !result ) {
1185                                 server->write_table(fp, filter->name, PLUGIN_FFMPEG_ID, 0);
1186                                 server->close_plugin();
1187                         }
1188                         delete server;
1189                         if( result ) fprintf(fp, "#%s\n", filter->name);
1190                 }
1191         }
1192 }
1193
1194 void MWindow::init_ffmpeg()
1195 {
1196 }
1197