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