78bc2bec395e56c3147ad3758565025fee45fa90
[goodguy/cinelerra.git] / cinelerra-5.1 / cinelerra / mwindow.C
1 /*
2  * CINELERRA
3  * Copyright (C) 1997-2014 Adam Williams <broadcast at earthling dot net>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  */
20
21 #include "aboutprefs.h"
22 #include "asset.h"
23 #include "assets.h"
24 #include "atrack.h"
25 #include "audioalsa.h"
26 #include "autos.h"
27 #include "awindowgui.h"
28 #include "awindow.h"
29 #include "batchrender.h"
30 #include "bccmodels.h"
31 #include "bcdisplayinfo.h"
32 #include "bcprogressbox.h"
33 #include "bcsignals.h"
34 #include "bctimer.h"
35 #include "bctrace.h"
36 #include "bdcreate.h"
37 #include "brender.h"
38 #include "cache.h"
39 #include "channel.h"
40 #include "channeldb.h"
41 #include "channelinfo.h"
42 #include "clip.h"
43 #include "clipedls.h"
44 #include "commercials.h"
45 #include "confirmsave.h"
46 #include "convert.h"
47 #include "cplayback.h"
48 #include "ctimebar.h"
49 #include "cwindowgui.h"
50 #include "cwindow.h"
51 #include "cwindowtool.h"
52 #include "bchash.h"
53 #include "devicedvbinput.inc"
54 #include "dvdcreate.h"
55 #include "editpanel.h"
56 #include "edl.h"
57 #include "edlsession.h"
58 #include "errorbox.h"
59 #include "fileformat.h"
60 #include "file.h"
61 #include "filesystem.h"
62 #include "filexml.h"
63 #include "floatautos.h"
64 #include "framecache.h"
65 #include "gwindow.h"
66 #include "gwindowgui.h"
67 #include "keyframegui.h"
68 #include "indexfile.h"
69 #include "intautos.h"
70 #include "interlacemodes.h"
71 #include "language.h"
72 #include "levelwindowgui.h"
73 #include "levelwindow.h"
74 #include "loadfile.inc"
75 #include "localsession.h"
76 #include "maincursor.h"
77 #include "mainerror.h"
78 #include "mainindexes.h"
79 #include "mainmenu.h"
80 #include "mainprogress.h"
81 #include "mainsession.h"
82 #include "mainundo.h"
83 #include "mbuttons.h"
84 #include "mixersalign.h"
85 #include "mutex.h"
86 #include "mwindowgui.h"
87 #include "mwindow.h"
88 #include "new.h"
89 #include "panautos.h"
90 #include "patchbay.h"
91 #include "playback3d.h"
92 #include "playbackengine.h"
93 #include "plugin.h"
94 #include "pluginserver.h"
95 #include "pluginset.h"
96 #include "preferences.h"
97 #include "proxy.h"
98 #include "record.h"
99 #include "recordmonitor.h"
100 #include "recordlabel.h"
101 #include "removefile.h"
102 #include "render.h"
103 #include "resourcethread.h"
104 #include "savefile.inc"
105 #include "samplescroll.h"
106 #include "sha1.h"
107 #include "shuttle.h"
108 #include "sighandler.h"
109 #include "splashgui.h"
110 #include "statusbar.h"
111 #include "theme.h"
112 #include "threadloader.h"
113 #include "timebar.h"
114 #include "timelinepane.h"
115 #include "tipwindow.h"
116 #include "trackcanvas.h"
117 #include "track.h"
118 #include "tracking.h"
119 #include "trackscroll.h"
120 #include "tracks.h"
121 #include "transition.h"
122 #include "transportque.h"
123 #include "vframe.h"
124 #include "vtrack.h"
125 #include "versioninfo.h"
126 #include "vicon.h"
127 #include "videodevice.inc"
128 #include "videowindow.h"
129 #include "vplayback.h"
130 #include "vwindowgui.h"
131 #include "vwindow.h"
132 #include "wavecache.h"
133 #include "wintv.h"
134 #include "wwindow.h"
135 #include "zoombar.h"
136 #include "zwindow.h"
137 #include "zwindowgui.h"
138 #include "exportedl.h"
139
140 #include "defaultformats.h"
141 #include "ntsczones.h"
142
143 #include <stdint.h>
144 #include <stdlib.h>
145 #include <unistd.h>
146 #include <fcntl.h>
147 #include <string.h>
148 #include <sys/types.h>
149 #include <sys/stat.h>
150 #include <sys/time.h>
151 #include <sys/mman.h>
152 #include <sys/file.h>
153 #include <limits.h>
154 #include <errno.h>
155
156
157 extern "C"
158 {
159
160
161
162
163 // Hack for libdv to remove glib dependancy
164
165 // void
166 // g_log (const char    *log_domain,
167 //        int  log_level,
168 //        const char    *format,
169 //        ...)
170 // {
171 // }
172 //
173 // void
174 // g_logv (const char    *log_domain,
175 //        int  log_level,
176 //        const char    *format,
177 //        ...)
178 // {
179 // }
180 //
181
182 }
183
184 extern long cin_timezone;
185
186 ArrayList<PluginServer*>* MWindow::plugindb = 0;
187 Commercials* MWindow::commercials = 0;
188
189
190 MWindow::MWindow()
191  : Thread(1, 0, 0)
192 {
193         run_lock = new Mutex("MWindow::run_lock");
194         plugin_gui_lock = new Mutex("MWindow::plugin_gui_lock");
195         dead_plugin_lock = new Mutex("MWindow::dead_plugin_lock");
196         vwindows_lock = new Mutex("MWindow::vwindows_lock");
197         zwindows_lock = new Mutex("MWindow::zwindows_lock");
198         brender_lock = new Mutex("MWindow::brender_lock");
199         keyframe_gui_lock = new Mutex("MWindow::keyframe_gui_lock");
200
201         playback_3d = 0;
202         splash_window = 0;
203         undo = 0;
204         undo_command = COMMAND_NONE;
205         defaults = 0;
206         assets = 0;
207         //commercials = 0;
208         commercial_active = 0;
209         audio_cache = 0;
210         video_cache = 0;
211         frame_cache = 0;
212         wave_cache = 0;
213         preferences = 0;
214         session = 0;
215         theme = 0;
216         mainindexes = 0;
217         mainprogress = 0;
218         brender = 0;
219         brender_active = 0;
220         strcpy(cin_lang,"en");
221         channeldb_buz =  new ChannelDB;
222         channeldb_v4l2jpeg =  new ChannelDB;
223         plugin_guis = 0;
224         dead_plugins = 0;
225         keyframe_threads = 0;
226         create_bd = 0;
227         create_dvd = 0;
228         batch_render = 0;
229         convert_render = 0;
230         render = 0;
231         edl = 0;
232         gui = 0;
233         cwindow = 0;
234         awindow = 0;
235         gwindow = 0;
236         twindow = 0;
237         wwindow = 0;
238         lwindow = 0;
239         sighandler = 0;
240         restart_status = 0;
241         screens = 1;
242         in_destructor = 0;
243         speed_edl = 0;
244         beeper = 0;
245         shuttle = 0;
246         wintv = 0;
247         mixers_align = 0;
248 }
249
250
251 // Need to delete brender temporary here.
252 MWindow::~MWindow()
253 {
254         run_lock->lock("MWindow::~MWindow");
255         in_destructor = 1;
256 //printf("MWindow::~MWindow %d\n", __LINE__);
257         if( wwindow && wwindow->is_running() )
258                 wwindow->close_window();
259         if( twindow && twindow->is_running() )
260                 twindow->close_window();
261         gui->remote_control->deactivate();
262         gui->record->stop();
263 #ifdef HAVE_DVB
264         gui->channel_info->stop();
265 #endif
266         delete beeper;
267         delete create_bd;       create_bd = 0;
268         delete create_dvd;      create_dvd = 0;
269         delete shuttle;         shuttle = 0;
270 #ifdef HAVE_WINTV
271         delete wintv;           wintv = 0;
272 #endif
273         delete batch_render;    batch_render = 0;
274         delete convert_render;  convert_render = 0;
275         delete render;          render = 0;
276         delete mixers_align;    mixers_align = 0;
277         commit_commercial();
278         if( commercials && !commercials->remove_user() ) commercials = 0;
279         close_mixers();
280         if( speed_edl ) { speed_edl->remove_user();  speed_edl = 0; }
281 // Save defaults for open plugins
282         plugin_gui_lock->lock("MWindow::~MWindow");
283         for(int i = 0; i < plugin_guis->size(); i++) {
284                 plugin_guis->get(i)->hide_gui();
285                 delete_plugin(plugin_guis->get(i));
286         }
287         plugin_gui_lock->unlock();
288         hide_keyframe_guis();
289         clean_indexes();
290         save_defaults();
291 // Give up and go to a movie
292 //  cant run valgrind if this is used
293
294         gui->del_keyboard_listener(
295                 (int (BC_WindowBase::*)(BC_WindowBase *))
296                 &MWindowGUI::keyboard_listener);
297 #if 0
298 // release the hounds
299         if( awindow && awindow->gui ) awindow->gui->close(0);
300         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
301         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
302         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
303         vwindows.remove_all_objects();
304         zwindows.remove_all_objects();
305         gui->close(0);
306         if( awindow ) awindow->join();
307         if( cwindow ) cwindow->join();
308         if( lwindow ) lwindow->join();
309         if( gwindow ) gwindow->join();
310         join();
311 #else
312 // one at a time, or nouveau chokes
313 #define close_gui(win) if( win ) { \
314   if( win->gui ) win->gui->close(0); \
315   win->join(); }
316         close_gui(awindow);
317         close_gui(cwindow);
318         close_gui(lwindow);
319         close_gui(gwindow);
320         vwindows.remove_all_objects();
321         zwindows.remove_all_objects();
322         gui->close(0);
323         join();
324 #endif
325         reset_caches();
326         dead_plugins->remove_all_objects();
327 // must delete theme before destroying plugindb
328 //  theme destructor will be deleted by delete_plugins
329         delete theme;           theme = 0;
330         delete_plugins();
331         finit_error();
332         keyframe_threads->remove_all_objects();
333         colormodels.remove_all_objects();
334         delete awindow;         awindow = 0;
335         delete lwindow;         lwindow = 0;
336         delete twindow;         twindow = 0;
337         delete wwindow;         wwindow = 0;
338         delete gwindow;         gwindow = 0;
339         delete cwindow;         cwindow = 0;
340         delete gui;             gui = 0;
341         delete mainindexes;     mainindexes = 0;
342         delete mainprogress;    mainprogress = 0;
343         delete audio_cache;     audio_cache = 0;  // delete the cache after the assets
344         delete video_cache;     video_cache = 0;  // delete the cache after the assets
345         delete frame_cache;     frame_cache = 0;
346         delete wave_cache;      wave_cache = 0;
347         delete plugin_guis;     plugin_guis = 0;
348         delete dead_plugins;    dead_plugins = 0;
349         delete keyframe_threads;  keyframe_threads = 0;
350         delete undo;            undo = 0;
351         delete preferences;     preferences = 0;
352         delete exportedl;       exportedl = 0;
353         delete session;         session = 0;
354         delete defaults;        defaults = 0;
355         delete assets;          assets = 0;
356         delete splash_window;   splash_window = 0;
357         if( !edl->Garbage::remove_user() ) edl = 0;
358         delete channeldb_buz;
359         delete channeldb_v4l2jpeg;
360 // This must be last thread to exit
361         delete playback_3d;     playback_3d = 0;
362         delete dead_plugin_lock;
363         delete plugin_gui_lock;
364         delete vwindows_lock;
365         delete zwindows_lock;
366         delete brender_lock;
367         delete keyframe_gui_lock;
368         colormodels.remove_all_objects();
369         interlace_project_modes.remove_all_objects();
370         interlace_asset_modes.remove_all_objects();
371         sighandler->terminate();
372         delete sighandler;
373         delete run_lock;
374 }
375
376
377 void MWindow::quit()
378 {
379         gui->set_done(0);
380 }
381
382 void MWindow::init_error()
383 {
384         MainError::init_error(this);
385 }
386
387 void MWindow::finit_error()
388 {
389         MainError::finit_error();
390 }
391
392 void MWindow::create_defaults_path(char *string, const char *config_file)
393 {
394 // set the .bcast path
395         FileSystem fs;
396
397         sprintf(string, "%s/", File::get_config_path());
398         fs.complete_path(string);
399         if(!fs.is_dir(string))
400                 fs.create_dir(string);
401
402 // load the defaults
403         strcat(string, config_file);
404 }
405 const char *MWindow::default_std()
406 {
407         char buf[BCTEXTLEN], *p = 0;
408
409         int fd = open(TIMEZONE_NAME, O_RDONLY);
410         if( fd >= 0 ) {
411                 int l = read(fd, buf, sizeof(buf)-1);
412                 close(fd);
413                 if( l > 0 ) {
414                         if( buf[l-1] == '\n' ) --l;
415                         buf[l] = 0;
416                         p = buf;
417                 }
418         }
419         if( !p ) {
420                 int l = readlink(LOCALTIME_LINK, buf, sizeof(buf)-1);
421                 if( l > 0 ) {
422                         buf[l] = 0;
423                         if( !(p=strstr(buf, ZONEINFO_STR)) != 0 ) return "PAL";
424                         p += strlen(ZONEINFO_STR);
425                 }
426         }
427
428         if( p ) {
429                 for( int i=0; ntsc_zones[i]; ++i ) {
430                         if( !strcmp(ntsc_zones[i], p) )
431                                 return "NTSC";
432                 }
433         }
434
435         p = getenv("TZ");
436         if( p ) {
437                 for( int i=0; ntsc_zones[i]; ++i ) {
438                         if( !strcmp(ntsc_zones[i], p) )
439                                 return "NTSC";
440                 }
441         }
442
443 // cin_timezone: Seconds west of UTC.  240sec/deg
444         double tz_deg =  -cin_timezone / 240.;
445 // from Honolulu = -10, to New York = -5, 15deg/hr   lat -150..-75
446         return tz_deg >= -10*15 && tz_deg <= -5*15 ? "NTSC" : "PAL";
447 }
448
449 void MWindow::fill_preset_defaults(const char *preset, EDLSession *session)
450 {
451         struct formatpresets *fpr;
452
453         for(fpr = &format_presets[0]; fpr->name; fpr++)
454         {
455                 if(strcmp(_(fpr->name), preset) == 0)
456                 {
457                         session->audio_channels = fpr->audio_channels;
458                         session->audio_tracks = fpr->audio_tracks;
459                         session->sample_rate = fpr->sample_rate;
460                         session->video_channels = fpr->video_channels;
461                         session->video_tracks = fpr->video_tracks;
462                         session->frame_rate = fpr->frame_rate;
463                         session->output_w = fpr->output_w;
464                         session->output_h = fpr->output_h;
465                         session->aspect_w = fpr->aspect_w;
466                         session->aspect_h = fpr->aspect_h;
467                         session->interlace_mode = fpr->interlace_mode;
468                         session->color_model = fpr->color_model;
469                         return;
470                 }
471         }
472 }
473
474 const char *MWindow::get_preset_name(int index)
475 {
476         if(index < 0 || index >= (int)MAX_NUM_PRESETS)
477                 return "Error";
478         return _(format_presets[index].name);
479 }
480
481
482 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
483 {
484         char path[BCTEXTLEN];
485 // Use user supplied path
486         if(config_path[0])
487                 strcpy(path, config_path);
488         else
489                 create_defaults_path(path, CONFIG_FILE);
490
491         delete defaults;
492         defaults = new BC_Hash(path);
493         defaults->load();
494 }
495
496
497 void MWindow::check_language()
498 {
499         char curr_lang[BCTEXTLEN]; curr_lang[0] = 0;
500         const char *env_lang = getenv("LANGUAGE");
501         if( !env_lang ) env_lang = getenv("LC_ALL");
502         if( !env_lang ) env_lang = getenv("LANG");
503         if( !env_lang ) {
504                 snprintf(curr_lang, sizeof(curr_lang), "%s_%s-%s",
505                         BC_Resources::language, BC_Resources::region, BC_Resources::encoding);
506                 env_lang = curr_lang;
507         }
508         char last_lang[BCTEXTLEN]; last_lang[0] = 0;
509         defaults->get("LAST_LANG",last_lang);
510         if( strcmp(env_lang,last_lang)) {
511                 printf("lang changed from '%s' to '%s'\n", last_lang, env_lang);
512                 defaults->update("LAST_LANG",env_lang);
513                 char plugin_path[BCTEXTLEN];
514                 create_defaults_path(plugin_path, PLUGIN_FILE);
515                 ::remove(plugin_path);
516                 char ladspa_path[BCTEXTLEN];
517                 create_defaults_path(ladspa_path, LADSPA_FILE);
518                 ::remove(ladspa_path);
519                 defaults->save();
520         }
521         if( strlen(env_lang) > 1 &&
522             ( env_lang[2] == 0 || env_lang[2] == '_'  || env_lang[2] == '.' ) ) {
523                 cin_lang[0] = env_lang[0];  cin_lang[1] = env_lang[1];  cin_lang[2] = 0;
524         }
525         else
526                 strcpy(cin_lang, "en");
527 }
528
529 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
530 {
531         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
532         if( plug_dir ) {
533                 const char *dp = plug_dir;
534                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
535                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
536         }
537         strcpy(path, bp);
538         delete [] base_path;
539 }
540
541 int MWindow::load_plugin_index(MWindow *mwindow, FILE *fp, const char *plugin_dir)
542 {
543         if( !fp ) return -1;
544 // load index
545         fseek(fp, 0, SEEK_SET);
546         int ret = 0;
547         char index_line[BCTEXTLEN];
548         int index_version = -1, len = strlen(plugin_dir);
549         if( !fgets(index_line, BCTEXTLEN, fp) ||
550             sscanf(index_line, "%d", &index_version) != 1 ||
551             index_version != PLUGIN_FILE_VERSION ||
552             !fgets(index_line, BCTEXTLEN, fp) ||
553             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
554             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
555
556         ArrayList<PluginServer*> plugins;
557         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
558                 if( index_line[0] == ';' ) continue;
559                 if( index_line[0] == '#' ) continue;
560                 int type = PLUGIN_TYPE_UNKNOWN;
561                 char path[BCTEXTLEN], title[BCTEXTLEN];
562                 int64_t mtime = 0;
563                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
564                         ret = 1; continue;
565                 }
566                 PluginServer *server = 0;
567                 switch( type ) {
568                 case PLUGIN_TYPE_BUILTIN:
569                 case PLUGIN_TYPE_EXECUTABLE:
570                 case PLUGIN_TYPE_LADSPA: {
571                         char plugin_path[BCTEXTLEN];  struct stat st;
572                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
573                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
574                                 ret = 1; continue;
575                         }
576                         server = new PluginServer(mwindow, plugin_path, type);
577                         break; }
578                 case PLUGIN_TYPE_FFMPEG: {
579                         server = new_ffmpeg_server(mwindow, path);
580                         break; }
581                 case PLUGIN_TYPE_LV2: {
582                         server = new_lv2_server(mwindow, path);
583                         break; }
584                 }
585                 if( !server ) continue;
586                 plugins.append(server);
587 // Create plugin server from index entry
588                 server->set_title(title);
589                 if( server->read_table(index_line) ) {
590                         ret = 1;  continue;
591                 }
592         }
593
594         if( !ret )
595                 ret = check_plugin_index(plugins, plugin_dir, ".");
596
597         if( !ret )
598                 add_plugins(plugins);
599         else
600                 plugins.remove_all_objects();
601
602         return ret;
603 }
604
605 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
606         const char *plug_dir, const char *plug_path)
607 {
608         char plugin_path[BCTEXTLEN];
609         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
610         FileSystem fs;
611         fs.set_filter( "[*.plugin][*.so]" );
612         if( fs.update(plugin_path) )
613                 return 1;
614
615         for( int i=0; i<fs.dir_list.total; ++i ) {
616                 char fs_path[BCTEXTLEN];
617                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
618                 if( fs.is_dir(fs_path) ) {
619                         get_plugin_path(plugin_path, plug_dir, fs_path);
620                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
621                                 return 1;
622                 }
623                 else if( !plugin_exists(fs_path, plugins) )
624                         return 1;
625         }
626         return 0;
627 }
628
629
630 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
631 {
632         if( !plugindb )
633                 plugindb = new ArrayList<PluginServer*>;
634         init_ffmpeg();
635         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
636         create_defaults_path(index_path, PLUGIN_FILE);
637         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
638         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
639         FILE *fp = fopen(index_path,"a+");
640         if( !fp ) {
641                 fprintf(stderr,_("MWindow::init_plugins: "
642                         "can't open plugin index: %s\n"), index_path);
643                 return -1;
644         }
645         int fd = fileno(fp), ret = -1;
646         if( !flock(fd, LOCK_EX) ) {
647                 fseek(fp, 0, SEEK_SET);
648                 ret = load_plugin_index(mwindow, fp, plugin_path);
649         }
650         if( ret > 0 ) {
651                 ftruncate(fd, 0);
652                 fseek(fp, 0, SEEK_SET);
653                 printf("init plugin index: %s\n", plugin_path);
654                 fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
655                 fprintf(fp, "%s\n", plugin_path);
656                 init_plugin_index(mwindow, preferences, fp, plugin_path);
657                 init_ffmpeg_index(mwindow, preferences, fp);
658                 init_lv2_index(mwindow, preferences, fp);
659                 fseek(fp, 0, SEEK_SET);
660                 ret = load_plugin_index(mwindow, fp, plugin_path);
661         }
662         if( ret ) {
663                 fprintf(stderr,_("MWindow::init_plugins: "
664                         "can't %s plugin index: %s\n"),
665                         ret>0 ? _("create") : _("lock"), index_path);
666         }
667         fclose(fp);
668         return ret;
669 }
670
671 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
672 {
673         char *path = getenv("LADSPA_PATH");
674         char ladspa_path[BCTEXTLEN];
675         if( !path ) {
676                 strncpy(ladspa_path, File::get_ladspa_path(), sizeof(ladspa_path));
677                 path = ladspa_path;
678         }
679         for( int len=0; *path; path+=len ) {
680                 char *cp = strchr(path,':');
681                 len = !cp ? strlen(path) : cp-path;
682                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
683                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
684                 if( cp ) ++len;
685                 char *plugin_dir = FileSystem::basepath(plugin_path);
686                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
687                 create_defaults_path(index_path, LADSPA_FILE);
688                 cp = index_path + strlen(index_path);
689                 for( char *bp=plugin_path; *bp!=0; ++bp )
690                         *cp++ = *bp=='/' ? '_' : *bp;
691                 *cp = 0;
692                 FILE *fp = fopen(index_path,"a+");
693                 if( !fp ) {
694                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
695                                 "can't open ladspa plugin index: %s\n"), index_path);
696                         continue;
697                 }
698                 int fd = fileno(fp), ret = -1;
699                 if( !flock(fd, LOCK_EX) ) {
700                         fseek(fp, 0, SEEK_SET);
701                         ret = load_plugin_index(mwindow, fp, plugin_path);
702                 }
703                 if( ret > 0 ) {
704                         ftruncate(fd, 0);
705                         fseek(fp, 0, SEEK_SET);
706                         init_ladspa_index(mwindow, preferences, fp, plugin_path);
707                         fseek(fp, 0, SEEK_SET);
708                         ret = load_plugin_index(mwindow, fp, plugin_path);
709                 }
710                 if( ret ) {
711                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
712                                 "can't %s ladspa plugin index: %s\n"),
713                                 ret>0 ? _("create") : _("lock"), index_path);
714                 }
715                 fclose(fp);
716         }
717         return 1;
718 }
719
720 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
721         FILE *fp, const char *plugin_dir)
722 {
723         int idx = PLUGIN_IDS;
724         if( plugindb ) {
725                 for( int i=0; i<plugindb->size(); ++i ) {
726                         PluginServer *server = plugindb->get(i);
727                         if( server->dir_idx >= idx )
728                                 idx = server->dir_idx+1;
729                 }
730         }
731         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
732 }
733
734 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
735         const char *plug_dir, const char *plug_path, int &idx)
736 {
737         char plugin_path[BCTEXTLEN];
738         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
739         FileSystem fs;
740         fs.set_filter( "[*.plugin][*.so]" );
741         int result = fs.update(plugin_path);
742         if( result || !fs.dir_list.total ) return;
743         int vis_id = idx++;
744
745         for( int i=0; i<fs.dir_list.total; ++i ) {
746                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
747                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
748                 get_plugin_path(path, plug_dir, fs_path);
749                 if( fs.is_dir(fs_path) ) {
750                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
751                         continue;
752                 }
753                 if( plugin_exists(path) ) continue;
754                 struct stat st;
755                 if( stat(fs_path, &st) ) continue;
756                 int64_t mtime = st.st_mtime;
757                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
758                 result = server.open_plugin(1, preferences, 0, 0);
759                 if( !result ) {
760                         server.write_table(fp, path, vis_id, mtime);
761                         server.close_plugin();
762                 }
763                 else if( result == PLUGINSERVER_IS_LAD ) {
764                         int lad_index = 0;
765                         for(;;) {
766                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
767                                 ladspa.set_lad_index(lad_index++);
768                                 result = ladspa.open_plugin(1, preferences, 0, 0);
769                                 if( result ) break;
770                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
771                                 ladspa.close_plugin();
772                         }
773                 }
774         }
775 }
776
777 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
778 {
779         for( int i=0; i<plugins.size(); ++i )
780                 plugindb->append(plugins[i]);
781         plugins.remove_all();
782 }
783
784 void MWindow::init_plugin_tips(ArrayList<PluginServer*> &plugins, const char *lang)
785 {
786         const char *dat_path = File::get_cindat_path();
787         char msg_path[BCTEXTLEN];
788         FILE *fp = 0;
789         if( BC_Resources::language[0] ) {
790                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.%s",
791                         dat_path, lang);
792                 fp = fopen(msg_path, "r");
793         }
794         if( !fp ) {
795                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.txt",
796                         dat_path);
797                 fp = fopen(msg_path, "r");
798         }
799         if( !fp ) return;
800         char text[BCTEXTLEN];
801         char *tp = text, *ep = tp + sizeof(text)-1;
802         char title[BCTEXTLEN];
803         title[0] = 0;
804         int no = 0;
805         for(;;) {
806                 ++no;  int done = 1;
807                 char line[BCTEXTLEN], *cp = line;
808                 if( fgets(line,sizeof(line)-1,fp) ) {
809                         if( *cp == '#' ) continue;
810                         done = *cp == ' ' || *cp == '\t' ? 0 : -1;
811                 }
812                 if( done ) {
813                         if( tp > text && *--tp == '\n' ) *tp = 0;
814                         if( title[0] ) {
815                                 int idx = plugins.size();
816                                 while( --idx>=0 && strcmp(plugins[idx]->title, title) );
817                                 if( idx >= 0 ) {
818                                         delete [] plugins[idx]->tip;
819                                         plugins[idx]->tip = cstrdup(text);
820                                 }
821                                 title[0] = 0;
822                         }
823                         if( done > 0 ) break;
824                         tp = text;  *tp = 0;
825                         char *dp = strchr(cp, ':');
826                         if( !dp ) {
827                                 printf("plugin tips: error on line %d\n", no);
828                                 continue;
829                         }
830                         char *bp = title;
831                         while( cp < dp ) *bp++ = *cp++;
832                         *bp = 0;
833                         ++cp;
834                 }
835
836                 while( *cp == ' ' || *cp == '\t' ) ++cp;
837                 for( ; tp<ep && (*tp=*cp)!=0; ++tp,++cp );
838         }
839         fclose(fp);
840 }
841
842 void MWindow::delete_plugins()
843 {
844         plugindb->remove_all_objects();
845         delete plugindb;
846         plugindb = 0;
847 }
848
849 void MWindow::search_plugindb(int do_audio,
850                 int do_video,
851                 int is_realtime,
852                 int is_transition,
853                 int is_theme,
854                 ArrayList<PluginServer*> &results)
855 {
856 // Get plugins
857         for(int i = 0; i < MWindow::plugindb->total; i++)
858         {
859                 PluginServer *current = MWindow::plugindb->get(i);
860
861                 if(current->audio == do_audio &&
862                         current->video == do_video &&
863                         (current->realtime == is_realtime || is_realtime < 0) &&
864                         current->transition == is_transition &&
865                         current->theme == is_theme)
866                         results.append(current);
867         }
868
869 // Alphabetize list by title
870         int done = 0;
871         while(!done)
872         {
873                 done = 1;
874
875                 for(int i = 0; i < results.total - 1; i++)
876                 {
877                         PluginServer *value1 = results[i];
878                         PluginServer *value2 = results[i + 1];
879                         if(strcmp(_(value1->title), _(value2->title)) > 0)
880                         {
881                                 done = 0;
882                                 results[i] = value2;
883                                 results[i + 1] = value1;
884                         }
885                 }
886         }
887 }
888
889 PluginServer* MWindow::scan_plugindb(char *title,
890                 int data_type)
891 {
892 //      if(data_type < 0)
893 //      {
894 //              printf("MWindow::scan_plugindb data_type < 0\n");
895 //              return 0;
896 //      }
897
898         for(int i = 0; i < plugindb->total; i++)
899         {
900                 PluginServer *server = plugindb->get(i);
901                 if(server->title &&
902                         !strcasecmp(server->title, title) &&
903                         (data_type < 0 ||
904                                 (data_type == TRACK_AUDIO && server->audio) ||
905                                 (data_type == TRACK_VIDEO && server->video)))
906                         return plugindb->get(i);
907         }
908         return 0;
909 }
910
911 // repair session files with xlated plugin titles
912 void MWindow::fix_plugin_title(char *title)
913 {
914         for(int i = 0; i < plugindb->total; i++) {
915                 PluginServer *server = plugindb->get(i);
916                 if( !server->title ) continue;
917                 const char *server_title = server->title;
918                 if( !bstrcasecmp(title, _(server_title)) ) {
919                         strcpy(title, server_title);
920                         return;
921                 }
922         }
923 }
924
925 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
926 {
927         for( int i=0; i<plugins.size(); ++i )
928                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
929         return 0;
930 }
931
932 int MWindow::plugin_exists(char *plugin_path)
933 {
934         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
935 }
936
937 void MWindow::remove_plugin_index()
938 {
939         char index_path[BCTEXTLEN];
940         MWindow::create_defaults_path(index_path, PLUGIN_FILE);
941         ::remove(index_path);
942 }
943
944 void MWindow::init_preferences()
945 {
946         preferences = new Preferences;
947         preferences->load_defaults(defaults);
948         File::setenv_path("LV2_PATH",preferences->lv2_path, 1);
949         session = new MainSession(this);
950         session->load_defaults(defaults);
951         // set x11_host, screens, window_config
952         screens = session->set_default_x11_host();
953         BC_Signals::set_trap_hook(trap_hook, this);
954         BC_Signals::set_catch_segv(preferences->trap_sigsegv);
955         BC_Signals::set_catch_intr(preferences->trap_sigintr);
956         if( preferences->trap_sigsegv || preferences->trap_sigintr ) {
957                 BC_Trace::enable_locks();
958         }
959         else {
960                 BC_Trace::disable_locks();
961         }
962         BC_WindowBase::get_resources()->popupmenu_btnup = preferences->popupmenu_btnup;
963         BC_WindowBase::get_resources()->textbox_focus_policy = preferences->textbox_focus_policy;
964         BC_WindowBase::get_resources()->grab_input_focus = preferences->grab_input_focus;
965         YUV::yuv.yuv_set_colors(preferences->yuv_color_space, preferences->yuv_color_range);
966 }
967
968 void MWindow::clean_indexes()
969 {
970         FileSystem fs;
971         int total_excess;
972         long oldest = 0;
973         int oldest_item = -1;
974         int result;
975         char string[BCTEXTLEN];
976         char string2[BCTEXTLEN];
977
978 // Delete extra indexes
979         fs.set_filter("*.idx");
980         fs.complete_path(preferences->index_directory);
981         fs.update(preferences->index_directory);
982 //printf("MWindow::clean_indexes 1 %d\n", fs.dir_list.total);
983
984 // Eliminate directories
985         result = 1;
986         while(result)
987         {
988                 result = 0;
989                 for(int i = 0; i < fs.dir_list.total && !result; i++)
990                 {
991                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
992                         if(fs.is_dir(string))
993                         {
994                                 delete fs.dir_list[i];
995                                 fs.dir_list.remove_number(i);
996                                 result = 1;
997                         }
998                 }
999         }
1000         total_excess = fs.dir_list.total - preferences->index_count;
1001
1002 //printf("MWindow::clean_indexes 2 %d\n", fs.dir_list.total);
1003         while(total_excess > 0)
1004         {
1005 // Get oldest
1006                 for(int i = 0; i < fs.dir_list.total; i++)
1007                 {
1008                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
1009
1010                         if(i == 0 || fs.get_date(string) <= oldest)
1011                         {
1012                                 oldest = fs.get_date(string);
1013                                 oldest_item = i;
1014                         }
1015                 }
1016
1017                 if(oldest_item >= 0)
1018                 {
1019 // Remove index file
1020                         fs.join_names(string,
1021                                 preferences->index_directory,
1022                                 fs.dir_list[oldest_item]->name);
1023 //printf("MWindow::clean_indexes 1 %s\n", string);
1024                         if(remove(string))
1025                                 perror("delete_indexes");
1026                         delete fs.dir_list[oldest_item];
1027                         fs.dir_list.remove_number(oldest_item);
1028
1029 // Remove table of contents if it exists
1030                         strcpy(string2, string);
1031                         char *ptr = strrchr(string2, '.');
1032                         if(ptr)
1033                         {
1034 //printf("MWindow::clean_indexes 2 %s\n", string2);
1035                                 sprintf(ptr, ".toc");
1036                                 remove(string2);
1037                                 sprintf(ptr, ".mkr");
1038                                 remove(string2);
1039                         }
1040                 }
1041
1042                 total_excess--;
1043         }
1044 }
1045
1046 void MWindow::init_awindow()
1047 {
1048         awindow = new AWindow(this);
1049         awindow->create_objects();
1050 }
1051
1052 void MWindow::init_gwindow()
1053 {
1054         gwindow = new GWindow(this);
1055         gwindow->create_objects();
1056 }
1057
1058 void MWindow::init_tipwindow()
1059 {
1060         TipWindow::load_tips(cin_lang);
1061         if( !twindow )
1062                 twindow = new TipWindow(this);
1063         twindow->start();
1064 }
1065
1066 void MWindow::show_warning(int *do_warning, const char *text)
1067 {
1068         if( do_warning && !*do_warning ) return;
1069         if( !wwindow )
1070                 wwindow = new WWindow(this);
1071         wwindow->show_warning(do_warning, text);
1072 }
1073
1074 int MWindow::wait_warning()
1075 {
1076         return wwindow->wait_result();
1077 }
1078
1079 void MWindow::init_theme()
1080 {
1081         Timer timer;
1082         theme = 0;
1083
1084         PluginServer *theme_plugin = 0;
1085         for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1086                 if( plugindb->get(i)->theme &&
1087                     !strcasecmp(preferences->theme, plugindb->get(i)->title) )
1088                         theme_plugin = plugindb->get(i);
1089         }
1090
1091         if( !theme_plugin )
1092                 fprintf(stderr, _("MWindow::init_theme: prefered theme %s not found.\n"),
1093                          preferences->theme);
1094
1095         const char *default_theme = DEFAULT_THEME;
1096         if( !theme_plugin && strcasecmp(preferences->theme, default_theme) ) {
1097                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
1098                         default_theme);
1099                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1100                         if( plugindb->get(i)->theme &&
1101                             !strcasecmp(default_theme, plugindb->get(i)->title) )
1102                                 theme_plugin = plugindb->get(i);
1103                 }
1104         }
1105
1106         if(!theme_plugin) {
1107                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
1108                 exit(1);
1109         }
1110
1111         PluginServer *plugin = new PluginServer(*theme_plugin);
1112         if( plugin->open_plugin(0, preferences, 0, 0) ) {
1113                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
1114                         theme_plugin->title);
1115                 exit(1);
1116         }
1117
1118         theme = plugin->new_theme();
1119         theme->mwindow = this;
1120         strcpy(theme->path, plugin->path);
1121         delete plugin;
1122
1123 // Load default images & settings
1124         theme->Theme::initialize();
1125 // Load user images & settings
1126         theme->initialize();
1127 // Create menus with user colors
1128         theme->build_menus();
1129         init_menus();
1130
1131         theme->sort_image_sets();
1132         theme->check_used();
1133 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1134 }
1135
1136 void MWindow::init_3d()
1137 {
1138         playback_3d = new Playback3D(this);
1139         playback_3d->create_objects();
1140 }
1141
1142 void MWindow::init_edl()
1143 {
1144         edl = new EDL;
1145         edl->create_objects();
1146         fill_preset_defaults(default_standard, edl->session);
1147         edl->load_defaults(defaults);
1148         edl->session->brender_start = edl->session->brender_end = 0;
1149         edl->create_default_tracks();
1150         edl->tracks->update_y_pixels(theme);
1151 }
1152
1153 void MWindow::init_compositor()
1154 {
1155         cwindow = new CWindow(this);
1156         cwindow->create_objects();
1157 }
1158
1159 void MWindow::init_levelwindow()
1160 {
1161         lwindow = new LevelWindow(this);
1162         lwindow->create_objects();
1163 }
1164
1165 VWindow *MWindow::get_viewer(int start_it, int idx)
1166 {
1167         vwindows_lock->lock("MWindow::get_viewer");
1168         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
1169         if( !vwindow ) idx = vwindows.size();
1170         while( !vwindow && --idx >= 0 ) {
1171                 VWindow *vwin = vwindows[idx];
1172                 if( !vwin->is_running() || !vwin->get_edl() )
1173                         vwindow = vwin;
1174         }
1175         if( !vwindow ) {
1176                 vwindow = new VWindow(this);
1177                 vwindow->load_defaults();
1178                 vwindow->create_objects();
1179                 vwindows.append(vwindow);
1180         }
1181         vwindows_lock->unlock();
1182         if( start_it ) vwindow->start();
1183         return vwindow;
1184 }
1185
1186 ZWindow *MWindow::get_mixer(Mixer *&mixer)
1187 {
1188         zwindows_lock->lock("MWindow::get_mixer");
1189         if( !mixer ) mixer = edl->mixers.new_mixer();
1190         ZWindow *zwindow = 0;
1191         for( int i=0; !zwindow && i<zwindows.size(); ++i ) {
1192                 ZWindow *zwdw = zwindows[i];
1193                 if( zwdw->running() ) continue;
1194                 if( zwdw->idx >= 0 ) continue;
1195                 zwindow = zwindows[i];
1196         }
1197         if( !zwindow )
1198                 zwindows.append(zwindow = new ZWindow(this));
1199         zwindow->idx = mixer->idx;
1200         zwindows_lock->unlock();
1201         return zwindow;
1202 }
1203
1204 void MWindow::del_mixer(ZWindow *zwindow)
1205 {
1206         zwindows_lock->lock("MWindow::del_mixer 0");
1207         edl->mixers.del_mixer(zwindow->idx);
1208         if( session->selected_zwindow >= 0 ) {
1209                 int i = zwindows.number_of(zwindow);
1210                 if( i >= 0 && i < session->selected_zwindow )
1211                         --session->selected_zwindow;
1212                 else if( i == session->selected_zwindow )
1213                         session->selected_zwindow = -1;
1214         }
1215         zwindows_lock->unlock();
1216         gui->lock_window("MWindow::del_mixer 1");
1217         gui->update_mixers(0, -1);
1218         gui->unlock_window();
1219 }
1220
1221 void MWindow::start_mixer()
1222 {
1223         Mixer *mixer = 0;
1224         ZWindow *zwindow = get_mixer(mixer);
1225         const char *title = 0;
1226
1227         for( Track *track=edl->tracks->first; track!=0; track=track->next ) {
1228                 PatchGUI *patchgui = get_patchgui(track);
1229                 if( !patchgui || !patchgui->mixer ) continue;
1230                 mixer->mixer_ids.append(track->get_mixer_id());
1231                 if( !title ) title = track->title;
1232         }
1233
1234         session->selected_zwindow = -1;
1235         gui->lock_window("MWindow::start_mixer");
1236         gui->update_mixers(0, 0);
1237         gui->unlock_window();
1238
1239         zwindow->set_title(title);
1240         zwindow->start();
1241         refresh_mixers();
1242 }
1243
1244 int MWindow::mixer_track_active(Track *track)
1245 {
1246         int i = session->selected_zwindow;
1247         if( i < 0 || i >= zwindows.size() ) return 0;
1248         ZWindow *zwindow = zwindows[i];
1249         Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1250         if( !mixer ) return 0;
1251         int n = mixer->mixer_ids.number_of(track->get_mixer_id());
1252         return n >= 0 ? 1 : 0;
1253 }
1254
1255 void MWindow::update_mixer_tracks()
1256 {
1257         zwindows_lock->lock("MixPatch::handle_event");
1258         int i = session->selected_zwindow;
1259         if( i >= 0 && i < zwindows.size() ) {
1260                 ZWindow *zwindow = zwindows[i];
1261                 zwindow->update_mixer_ids();
1262         }
1263         zwindows_lock->unlock();
1264 }
1265
1266 void MWindow::handle_mixers(EDL *edl, int command, int wait_tracking,
1267                 int use_inout, int toggle_audio, int loop_play, float speed)
1268 {
1269         zwindows_lock->lock("MWindow::handle_mixers");
1270         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1271                 ZWindow *zwindow = zwindows[vidx];
1272                 if( zwindow->idx < 0 ) continue;
1273                 Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1274                 if( !mixer || !mixer->mixer_ids.size() ) continue;
1275                 int k = -1;
1276                 for( Track *track = edl->tracks->first; k<0 && track!=0; track=track->next ) {
1277                         if( track->data_type != TRACK_VIDEO ) continue;
1278                         int mixer_id = track->get_mixer_id();
1279                         k = mixer->mixer_ids.size();
1280                         while( --k >= 0 && mixer_id != mixer->mixer_ids[k] );
1281                 }
1282                 if( k < 0 ) continue;
1283                 EDL *mixer_edl = new EDL(this->edl);
1284                 mixer_edl->create_objects();
1285                 mixer_edl->copy_all(edl);
1286                 mixer_edl->remove_vwindow_edls();
1287                 for( Track *track = mixer_edl->tracks->first; track!=0; track=track->next ) {
1288                         k = mixer->mixer_ids.size();
1289                         while( --k >= 0 && track->get_mixer_id() != mixer->mixer_ids[k] );
1290                         if( k >= 0 ) {
1291                                 track->record = 1;
1292                                 track->play = track->data_type == TRACK_VIDEO ? 1 : 0;
1293                         }
1294                         else
1295                                 track->record = track->play = 0;
1296                 }
1297                 zwindow->change_source(mixer_edl);
1298                 zwindow->handle_mixer(command, 0,
1299                                 use_inout, toggle_audio, loop_play, speed);
1300         }
1301         zwindows_lock->unlock();
1302 }
1303
1304 void MWindow::refresh_mixers(int dir)
1305 {
1306         int command = dir >= 0 ? CURRENT_FRAME : LAST_FRAME;
1307         handle_mixers(edl, command, 0, 0, 0, 0, 0);
1308 }
1309
1310 void MWindow::stop_mixers()
1311 {
1312         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1313                 ZWindow *zwindow = zwindows[vidx];
1314                 if( zwindow->idx < 0 ) continue;
1315                 zwindow->handle_mixer(STOP, 0, 0, 0, 0, 0);
1316         }
1317 }
1318
1319 void MWindow::close_mixers(int result)
1320 {
1321         ArrayList<ZWindow*> closed;
1322         zwindows_lock->lock("MWindow::close_mixers");
1323         for( int i=zwindows.size(); --i>=0; ) {
1324                 ZWindow *zwindow = zwindows[i];
1325                 if( zwindow->idx < 0 ) continue;
1326                 zwindow->idx = -1;
1327                 ZWindowGUI *zgui = zwindow->zgui;
1328                 zgui->lock_window("MWindow::select_zwindow 0");
1329                 zgui->set_done(result);
1330                 zgui->unlock_window();
1331                 closed.append(zwindow);
1332         }
1333         zwindows_lock->unlock();
1334         for( int i=0; i<closed.size(); ++i ) {
1335                 ZWindow *zwindow = closed[i];
1336                 zwindow->join();
1337         }
1338 }
1339
1340 ZWindow *MWindow::create_mixer(Indexable *indexable, double position)
1341 {
1342         ArrayList<Indexable*> new_assets;
1343         new_assets.append(indexable);
1344         Track *track = edl->tracks->last;
1345         load_assets(&new_assets, position, LOADMODE_NEW_TRACKS, 0, 0, 0, 0, 0, 1);
1346         track = !track ? edl->tracks->first : track->next;
1347         Mixer *mixer = 0;
1348         ZWindow *zwindow = get_mixer(mixer);
1349         while( track ) {
1350                 track->play = track->record = 0;
1351                 if( track->data_type == TRACK_VIDEO ) {
1352                         sprintf(track->title, _("Mixer %d"), zwindow->idx);
1353                 }
1354                 mixer->mixer_ids.append(track->get_mixer_id());
1355                 track = track->next;
1356         }
1357         if(  indexable->is_asset ) {
1358                 char *path = indexable->path;
1359                 char *tp = strrchr(path, '/');
1360                 if( !tp ) tp = path; else ++tp;
1361                 zwindow->set_title(tp);
1362         }
1363         else {
1364                 char *title = ((EDL*)indexable)->local_session->clip_title;
1365                 zwindow->set_title(title);
1366         }
1367         return zwindow;
1368 }
1369
1370 void MWindow::create_mixers(double position)
1371 {
1372         if( !session->drag_assets->size() &&
1373             !session->drag_clips->size() ) return;
1374         undo_before();
1375
1376         select_zwindow(0);
1377         ArrayList<ZWindow *>new_mixers;
1378
1379         for( int i=0; i<session->drag_assets->size(); ++i ) {
1380                 Indexable *indexable = session->drag_assets->get(i);
1381                 if( !indexable->have_video() ) continue;
1382                 ZWindow *zwindow = create_mixer(indexable, position);
1383                 new_mixers.append(zwindow);
1384         }
1385         for( int i=0; i<session->drag_clips->size(); ++i ) {
1386                 Indexable *indexable = (Indexable*)session->drag_clips->get(i);
1387                 if( !indexable->have_video() ) continue;
1388                 ZWindow *zwindow = create_mixer(indexable, position);
1389                 new_mixers.append(zwindow);
1390         }
1391
1392         tile_mixers();
1393         for( int i=0; i<new_mixers.size(); ++i )
1394                 new_mixers[i]->start();
1395
1396         refresh_mixers();
1397         save_backup();
1398         undo_after(_("create mixers"), LOAD_ALL);
1399         restart_brender();
1400         gui->update(1, FORCE_REDRAW, 1, 1, 1, 1, 0);
1401         sync_parameters(CHANGE_ALL);
1402 }
1403
1404 void MWindow::open_mixers()
1405 {
1406         for( int i=0; i<edl->mixers.size(); ++i ) {
1407                 Mixer *mixer = edl->mixers[i];
1408                 ZWindow *zwindow = get_mixer(mixer);
1409                 zwindow->set_title(mixer->title);
1410                 zwindow->start();
1411         }
1412         refresh_mixers();
1413 }
1414
1415 int MWindow::select_zwindow(ZWindow *zwindow)
1416 {
1417         int ret = 0, n = zwindows.number_of(zwindow);
1418         if( session->selected_zwindow != n ) {
1419                 session->selected_zwindow = n;
1420                 for( int i=0; i<zwindows.size(); ++i ) {
1421                         ZWindow *zwindow = zwindows[i];
1422                         if( zwindow->idx < 0 ) continue;
1423                         ZWindowGUI *zgui = zwindow->zgui;
1424                         zgui->lock_window("MWindow::select_zwindow 0");
1425                         zwindow->highlighted = i == n ? 1 : 0;
1426                         if( zgui->draw_overlays() )
1427                                 zgui->canvas->get_canvas()->flash(1);
1428                         zgui->unlock_window();
1429                 }
1430                 ret = 1;
1431                 gui->lock_window("MWindow::select_window 1");
1432                 gui->update_mixers(0, -1);
1433                 gui->unlock_window();
1434         }
1435         return ret;
1436 }
1437
1438 void MWindow::tile_mixers()
1439 {
1440         int nz = 0;
1441         for( int i=0; i<zwindows.size(); ++i ) {
1442                 ZWindow *zwindow = zwindows[i];
1443                 if( zwindow->idx < 0 ) continue;
1444                 ++nz;
1445         }
1446         if( !nz ) return;
1447         int zn = ceil(sqrt(nz));
1448         int x1 = 1 + gui->get_x(), x2 = cwindow->gui->get_x();
1449         int y1 = 1, y2 = gui->get_y();
1450         int rw = gui->get_root_w(0), rh = gui->get_root_h(0);
1451         if( x1 < 0 ) x1 = 0;
1452         if( y1 < 0 ) y1 = 0;
1453         if( x2 > rw ) x2 = rw;
1454         if( y2 > rh ) y2 = rh;
1455         int dx = x2 - x1, dy = y2 - y1;
1456         int zw = dx / zn;
1457         int lt = BC_DisplayInfo::get_left_border();
1458         int top = BC_DisplayInfo::get_top_border();
1459         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1460         int bh = top + BC_DisplayInfo::get_bottom_border();
1461         int zx = 0, zy = 0;  // window origins
1462         int mw = xS(10+10), mh = yS(10+10); // canvas margins
1463         int rsz = 0, n = 0, dz = 0;
1464         int ow = edl->session->output_w, oh = edl->session->output_h;
1465         for( int i=0; i<zwindows.size(); ++i ) {
1466                 ZWindow *zwindow = zwindows[i];
1467                 if( zwindow->idx < 0 ) continue;
1468                 int ww = zw - bw, hh = (ww - mw) * oh / ow + mh, zh = hh + bh;
1469                 if( rsz < hh ) rsz = hh;
1470                 int xx = zx + x1, yy = zy + y1;
1471                 int mx = x2 - zw, my = y2 - zh;
1472                 if( xx > mx ) xx = mx;
1473                 if( yy > my ) yy = my;
1474                 xx += lt + xS(dz);  yy += top + yS(dz);
1475                 zwindow->reposition(xx,yy, ww,hh);
1476                 if( zwindow->running() ) {
1477                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1478                         gui->lock_window("MWindow::tile_mixers");
1479                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1480                         gui->unlock_window();
1481                 }
1482                 if( ++n >= zn ) {
1483                         n = 0;  rsz += bh;
1484                         if( (zy += rsz) > (dy - rsz) ) dz += 10;
1485                         rsz = 0;
1486                         zx = 0;
1487                 }
1488                 else
1489                         zx += zw;
1490         }
1491 }
1492
1493 void MWindow::init_cache()
1494 {
1495         audio_cache = new CICache(preferences);
1496         video_cache = new CICache(preferences);
1497         frame_cache = new FrameCache;
1498         wave_cache = new WaveCache;
1499 }
1500
1501 void MWindow::init_channeldb()
1502 {
1503         channeldb_buz->load("channeldb_buz");
1504         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1505 }
1506
1507 void MWindow::init_menus()
1508 {
1509         char string[BCTEXTLEN];
1510
1511         // Color Models
1512         BC_CModels::to_text(string, BC_RGB888);
1513         colormodels.append(new ColormodelItem(string, BC_RGB888));
1514         BC_CModels::to_text(string, BC_RGBA8888);
1515         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1516 //      BC_CModels::to_text(string, BC_RGB161616);
1517 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1518 //      BC_CModels::to_text(string, BC_RGBA16161616);
1519 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1520         BC_CModels::to_text(string, BC_RGB_FLOAT);
1521         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1522         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1523         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1524         BC_CModels::to_text(string, BC_YUV888);
1525         colormodels.append(new ColormodelItem(string, BC_YUV888));
1526         BC_CModels::to_text(string, BC_YUVA8888);
1527         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1528 //      BC_CModels::to_text(string, BC_YUV161616);
1529 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1530 //      BC_CModels::to_text(string, BC_YUVA16161616);
1531 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1532
1533 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1534                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1535
1536 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1537                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1538
1539         // Interlacing Modes
1540         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1541
1542         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1543         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1544
1545         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1546         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1547
1548         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1549         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1550
1551         mixers_align = new MixersAlign(this);
1552 }
1553
1554 void MWindow::init_indexes()
1555 {
1556         mainindexes = new MainIndexes(this);
1557         mainindexes->start_loop();
1558 }
1559
1560 void MWindow::init_gui()
1561 {
1562         gui = new MWindowGUI(this);
1563         gui->create_objects();
1564         gui->load_defaults(defaults);
1565 }
1566
1567 void MWindow::init_signals()
1568 {
1569         sighandler = new SigHandler;
1570         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1571 ENABLE_BUFFER
1572 }
1573
1574 void MWindow::init_render()
1575 {
1576         render = new Render(this);
1577         create_bd = new CreateBD_Thread(this);
1578         create_dvd = new CreateDVD_Thread(this);
1579         batch_render = new BatchRenderThread(this);
1580 }
1581
1582 void MWindow::init_exportedl()
1583 {
1584         exportedl = new ExportEDL(this);
1585 }
1586
1587
1588 void MWindow::init_shuttle()
1589 {
1590 #ifdef HAVE_SHUTTLE
1591         int ret = Shuttle::probe();
1592         if( ret >= 0 ) {
1593                 shuttle = new Shuttle(this);
1594                 if( shuttle->read_config_file() > 0 ) {
1595                         printf("shuttle: bad config file\n");
1596                         delete shuttle;  shuttle = 0;
1597                         return;
1598                 }
1599                 shuttle->start(ret);
1600         }
1601 #endif
1602 }
1603 void MWindow::init_wintv()
1604 {
1605 #ifdef HAVE_WINTV
1606         wintv = WinTV::probe(this);
1607         if( wintv )
1608                 wintv->start();
1609 #endif
1610 }
1611
1612
1613 void MWindow::init_brender()
1614 {
1615         if(preferences->use_brender && !brender)
1616         {
1617                 brender_lock->lock("MWindow::init_brender 1");
1618                 brender = new BRender(this);
1619                 brender->initialize();
1620                 session->brender_end = 0;
1621                 brender_lock->unlock();
1622         }
1623         else
1624         if(!preferences->use_brender && brender)
1625         {
1626                 brender_lock->lock("MWindow::init_brender 2");
1627                 delete brender;
1628                 brender = 0;
1629                 session->brender_end = 0;
1630                 brender_lock->unlock();
1631         }
1632         brender_active = 0;
1633         stop_brender();
1634 }
1635
1636 void MWindow::restart_brender()
1637 {
1638 //printf("MWindow::restart_brender 1\n");
1639         if( !brender_active || !preferences->use_brender ) return;
1640         if( !brender ) return;
1641         brender->restart(edl);
1642 }
1643
1644 void MWindow::stop_brender()
1645 {
1646         if( !brender ) return;
1647 // cannot be holding mwindow->gui display lock
1648         brender->stop();
1649 }
1650
1651 int MWindow::brender_available(int position)
1652 {
1653         int result = 0;
1654         brender_lock->lock("MWindow::brender_available 1");
1655         if(brender && brender_active)
1656         {
1657                 if(brender->map_valid)
1658                 {
1659                         brender->map_lock->lock("MWindow::brender_available 2");
1660                         if(position < brender->map_size &&
1661                                 position >= 0)
1662                         {
1663 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1664                                 if(brender->map[position] == BRender::RENDERED)
1665                                         result = 1;
1666                         }
1667                         brender->map_lock->unlock();
1668                 }
1669         }
1670         brender_lock->unlock();
1671         return result;
1672 }
1673
1674 void MWindow::set_brender_active(int v, int update)
1675 {
1676         if( !preferences->use_brender ) v = 0;
1677         brender_active = v;
1678         gui->mainmenu->brender_active->set_checked(v);
1679         if( v != 0 ) {
1680                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1681                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1682
1683                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1684                         edl->session->brender_end = edl->tracks->total_video_length();
1685                 }
1686                 restart_brender();
1687         }
1688         else {
1689                 edl->session->brender_start = edl->session->brender_end = 0;
1690                 gui->unlock_window();
1691                 stop_brender();
1692                 gui->lock_window("MWindow::set_brender_active");
1693         }
1694         if( update ) {
1695                 gui->update_timebar(0);
1696                 gui->draw_overlays(1);
1697         }
1698 }
1699
1700 int MWindow::has_commercials()
1701 {
1702 #ifdef HAVE_COMMERCIAL
1703         return theme->use_commercials;
1704 #else
1705         return 0;
1706 #endif
1707 }
1708
1709 void MWindow::init_commercials()
1710 {
1711 #ifdef HAVE_COMMERCIAL
1712         if( !commercials ) {
1713                 commercials = new Commercials(this);
1714                 commercial_active = 0;
1715         }
1716         else
1717                 commercials->add_user();
1718 #endif
1719 }
1720
1721 void MWindow::commit_commercial()
1722 {
1723 #ifdef HAVE_COMMERCIAL
1724         if( !commercial_active ) return;
1725         commercial_active = 0;
1726         if( !commercials ) return;
1727         commercials->commitDb();
1728 #endif
1729 }
1730
1731 void MWindow::undo_commercial()
1732 {
1733 #ifdef HAVE_COMMERCIAL
1734         if( !commercial_active ) return;
1735         commercial_active = 0;
1736         if( !commercials ) return;
1737         commercials->undoDb();
1738 #endif
1739 }
1740
1741 int MWindow::put_commercial()
1742 {
1743         int result = 0;
1744 #ifdef HAVE_COMMERCIAL
1745         double start = edl->local_session->get_selectionstart();
1746         double end = edl->local_session->get_selectionend();
1747         if( start >= end ) return 0;
1748
1749         const char *errmsg = 0;
1750         int count = 0;
1751         Tracks *tracks = edl->tracks;
1752         //check it
1753         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1754                 if( track->data_type != TRACK_VIDEO ) continue;
1755                 if( !track->record ) continue;
1756                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1757                 ++count;
1758                 int64_t units_start = track->to_units(start,0);
1759                 int64_t units_end = track->to_units(end,0);
1760                 Edits *edits = track->edits;
1761                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1762                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1763                 if(!edit1 && !edit2) continue;  // nothing selected
1764                 if(!edit2) {                    // edit2 beyond end of track
1765                         edit2 = edits->last;
1766                         units_end = edits->length();
1767                 }
1768                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1769                 Indexable *indexable = edit1->get_source();
1770                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1771         }
1772         //run it
1773         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1774                 if( track->data_type != TRACK_VIDEO ) continue;
1775                 if( !track->record ) continue;
1776                 int64_t units_start = track->to_units(start,0);
1777                 int64_t units_end = track->to_units(end,0);
1778                 Edits *edits = track->edits;
1779                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1780                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1781                 if(!edit1 && !edit2) continue;  // nothing selected
1782                 if(!edit2) {                    // edit2 beyond end of track
1783                         edit2 = edits->last;
1784                         units_end = edits->length();
1785                 }
1786                 Indexable *indexable = edit1->get_source();
1787                 Asset *asset = (Asset *)indexable;
1788                 File *file = video_cache->check_out(asset, edl);
1789                 if( !file ) { errmsg = _("no file"); break; }
1790                 int64_t edit_length = units_end - units_start;
1791                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1792                 result = commercials->put_clip(file, edit1->channel,
1793                         track->from_units(edit_start), track->from_units(edit_length));
1794                 video_cache->check_in(asset);
1795                 if( result ) { errmsg = _("db failed"); break; }
1796         }
1797         if( errmsg ) {
1798                 char string[BCTEXTLEN];
1799                 sprintf(string, _("put_commercial: %s"), errmsg);
1800                 MainError::show_error(string);
1801                 undo_commercial();
1802                 result = 1;
1803         }
1804 #endif
1805         return result;
1806 }
1807
1808 void MWindow::stop_playback(int wait)
1809 {
1810         gui->stop_drawing();
1811
1812         cwindow->stop_playback(wait);
1813
1814         for(int i = 0; i < vwindows.size(); i++) {
1815                 VWindow *vwindow = vwindows[i];
1816                 if( !vwindow->is_running() ) continue;
1817                 vwindow->stop_playback(wait);
1818         }
1819         for(int i = 0; i < zwindows.size(); i++) {
1820                 ZWindow *zwindow = zwindows[i];
1821                 if( zwindow->idx < 0 ) continue;
1822                 zwindow->stop_playback(wait);
1823         }
1824 }
1825
1826 void MWindow::stop_transport()
1827 {
1828         gui->stop_transport(gui->get_window_lock() ? "MWindow::stop_transport" : 0);
1829 }
1830
1831 void MWindow::undo_before(const char *description, void *creator)
1832 {
1833         undo->update_undo_before(description, creator);
1834 }
1835
1836 void MWindow::undo_after(const char *description, uint32_t load_flags, int changes_made)
1837 {
1838         undo->update_undo_after(description, load_flags, changes_made);
1839 }
1840
1841 void MWindow::beep(double freq, double secs, double gain)
1842 {
1843         if( !beeper ) beeper = new Beeper(this);
1844         beeper->tone(freq, secs, gain);
1845 }
1846
1847 Beeper::Beeper(MWindow *mwindow)
1848  : Thread(1, 0, 0)
1849 {
1850         this->mwindow = mwindow;
1851         audio = new AudioDevice(mwindow);
1852         playing_audio = 0;
1853         interrupted = -1;
1854 }
1855
1856 Beeper::~Beeper()
1857 {
1858         stop(0);
1859         delete audio;
1860 }
1861
1862 void Beeper::run()
1863 {
1864         int channels = 2;
1865         int64_t bfrsz = BEEP_SAMPLE_RATE;
1866         EDL *edl = mwindow->edl;
1867         EDLSession *session = edl->session;
1868         AudioOutConfig *aconfig = session->playback_config->aconfig;
1869         audio->open_output(aconfig, BEEP_SAMPLE_RATE, bfrsz, channels, 0);
1870         audio->start_playback();
1871
1872         double out0[bfrsz], out1[bfrsz], *out[2] = { out0, out1 };
1873         const double two_pi = 2*M_PI;
1874         int64_t audio_len = BEEP_SAMPLE_RATE * secs;
1875         const double dt = two_pi * freq/BEEP_SAMPLE_RATE;
1876         double th = 0;
1877
1878         audio_pos = 0;
1879         playing_audio = 1;
1880         while( !interrupted ) {
1881                 int len = audio_len - audio_pos;
1882                 if( len <= 0 ) break;
1883                 if( len > bfrsz ) len = bfrsz;
1884                 int k = audio_pos;
1885                 for( int i=0; i<len; ++i,++k,th+=dt ) {
1886                         double t = th - two_pi;
1887                         if( t >= 0 ) th = t;
1888                         out0[i] = out1[i] = sin(th) * gain;
1889                 }
1890                 audio->write_buffer(out, channels, len);
1891                 audio_pos = k;
1892         }
1893
1894         if( !interrupted )
1895                 audio->set_last_buffer();
1896         audio->stop_audio(interrupted ? 0 : 1);
1897         playing_audio = 0;
1898
1899         audio->close_all();
1900 }
1901
1902 void Beeper::start()
1903 {
1904         if( running() ) return;
1905         audio_pos = -1;
1906         interrupted = 0;
1907         Thread::start();
1908 }
1909
1910 void Beeper::stop(int wait)
1911 {
1912         if( running() && !interrupted ) {
1913                 interrupted = 1;
1914                 audio->stop_audio(wait);
1915         }
1916         Thread::join();
1917 }
1918
1919 void Beeper::tone(double freq, double secs, double gain)
1920 {
1921         stop(0);
1922         this->freq = freq;
1923         this->secs = secs;
1924         this->gain = gain;
1925         start();
1926 }
1927
1928
1929 int MWindow::load_filenames(ArrayList<char*> *filenames,
1930                 int load_mode, int edl_mode, int update_filename)
1931 {
1932         ArrayList<EDL*> new_edls;
1933         ArrayList<Asset*> new_assets;
1934         ArrayList<File*> new_files;
1935
1936 //      save_defaults();
1937         gui->start_hourglass();
1938
1939 // Need to stop playback since tracking depends on the EDL not getting
1940 // deleted.
1941         gui->unlock_window();
1942         stop_playback(1);
1943         gui->lock_window("MWindow::load_filenames 0");
1944         undo_before();
1945
1946 const int debug = 0;
1947 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1948
1949 // Define new_edls and new_assets to load
1950         int result = 0, ftype = -1;
1951
1952         for( int i=0; i<filenames->size(); ++i ) {
1953 // Get type of file
1954                 File *new_file = new File;
1955                 Asset *new_asset = new Asset(filenames->get(i));
1956                 EDL *new_edl = new EDL;
1957                 new_edl->create_objects();
1958                 new_edl->copy_session(edl, -1);
1959                 new_file->set_program(edl->session->program_no);
1960
1961                 char string[BCTEXTLEN];
1962                 sprintf(string, _("Loading %s"), new_asset->path);
1963                 gui->show_message(string);
1964
1965                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1966
1967                 result = 1;
1968                 switch( ftype ) {
1969 // Convert media file to EDL
1970                 case FILE_OK: {
1971 // Warn about odd image dimensions
1972                         if( new_asset->video_data &&
1973                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
1974                                 eprintf(_("%s's resolution is %dx%d.\n"
1975                                         "Images with odd dimensions may not decode properly."),
1976                                         new_asset->path, new_asset->width, new_asset->height);
1977                         }
1978
1979                         if( new_asset->program >= 0 &&
1980                             edl->session->program_no != new_asset->program ) {
1981                                 eprintf(_("%s's index was built for program number %d\n"
1982                                         "Playback preference is %d.\n  Using program %d."),
1983                                         new_asset->path, new_asset->program,
1984                                         edl->session->program_no, new_asset->program);
1985                         }
1986
1987                         if( load_mode == LOADMODE_RESOURCESONLY ) {
1988                                 new_assets.append(new_asset);
1989                                 new_asset->add_user();
1990                                 result = 0;
1991                                 break;
1992                         }
1993
1994                         RecordLabels *labels = edl->session->label_cells ?
1995                                 new RecordLabels(new_file) : 0;
1996                         asset_to_edl(new_edl, new_asset, labels);
1997                         new_edls.append(new_edl);
1998                         new_edl->add_user();
1999                         delete labels;
2000
2001                         if( load_mode == LOADMODE_REPLACE ||
2002                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2003 // Set filename to nothing for assets since save EDL would overwrite them.
2004                                 set_filename("");
2005 // Reset timeline position
2006                                 for( int i=0; i<TOTAL_PANES; ++i ) {
2007                                         new_edl->local_session->view_start[i] = 0;
2008                                         new_edl->local_session->track_start[i] = 0;
2009                                 }
2010                         }
2011                         result = 0;
2012                         break; }
2013
2014                 case FILE_NOT_FOUND: {
2015                         eprintf(_("Failed to open %s"), new_asset->path);
2016                         sprintf(string, _("Failed to open %s"), new_asset->path);
2017                         gui->show_message(string, theme->message_error);
2018                         gui->update_default_message();
2019                         break; }
2020
2021 // Unknown format
2022                 case FILE_UNRECOGNIZED_CODEC: {
2023 // Test index file
2024                         { IndexFile indexfile(this, new_asset);
2025                         if( !(result = indexfile.open_index()) )
2026                                 indexfile.close_index(); }
2027
2028 // Test existing EDLs
2029                         for( int j=0; result && j<new_edls.total; ++j ) {
2030                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
2031                                 if( old_asset ) {
2032                                         new_asset->copy_from(old_asset,1);
2033                                         result = 0;
2034                                 }
2035                         }
2036                         if( result ) {
2037                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
2038                                 if( old_asset ) {
2039                                         new_asset->copy_from(old_asset,1);
2040                                         result = 0;
2041                                 }
2042                         }
2043
2044 // Prompt user
2045                         if( result ) {
2046                                 new_asset->audio_data = 1;
2047                                 new_asset->format = FILE_PCM;
2048                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
2049                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
2050                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
2051                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
2052                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
2053                                 new_asset->header = defaults->get("HEADER", 0);
2054
2055                                 FileSystem fs;
2056                                 fs.extract_name(string, new_asset->path);
2057                                 strcat(string, _("'s format couldn't be determined."));
2058                                 FileFormat fwindow(this);
2059                                 fwindow.create_objects(new_asset, string);
2060                                 result = fwindow.run_window();
2061
2062                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
2063                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
2064                                 defaults->update("AUDIO_BITS", new_asset->bits);
2065                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
2066                                 defaults->update("SIGNED_", new_asset->signed_);
2067                                 defaults->update("HEADER", new_asset->header);
2068                                 save_defaults();
2069                         }
2070 // Append to list
2071                         if( !result ) {
2072 // Recalculate length
2073                                 delete new_file;
2074                                 new_file = new File;
2075                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2076
2077                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
2078                                         RecordLabels *labels = edl->session->label_cells ?
2079                                                 new RecordLabels(new_file) : 0;
2080                                         asset_to_edl(new_edl, new_asset, labels);
2081                                         new_edls.append(new_edl);
2082                                         new_edl->add_user();
2083                                         delete labels;
2084                                 }
2085                                 else {
2086                                         new_assets.append(new_asset);
2087                                         new_asset->add_user();
2088                                 }
2089                         }
2090                         break; }
2091
2092                 case FILE_IS_XML: {
2093                         FileXML xml_file;
2094                         const char *filename = filenames->get(i);
2095                         if( xml_file.read_from_file(filename, 1) ) {
2096                                 eprintf(_("Error: unable to open:\n  %s"), filename);
2097                                 break;
2098                         }
2099                         const char *cin_version = 0;
2100                         while( !xml_file.read_tag() ) {
2101                                 if( xml_file.tag.title_is("EDL") ) {
2102                                         cin_version = xml_file.tag.get_property("VERSION");
2103                                         break;
2104                                 }
2105                         }
2106                         xml_file.rewind();
2107                         if( !cin_version ) {
2108                                 eprintf(_("XML file %s\n not from cinelerra."),filename);
2109                                 char string[BCTEXTLEN];
2110                                 sprintf(string,_("Unknown %s"), filename);
2111                                 gui->show_message(string);
2112                                 break;
2113                         }
2114                         if( strcmp(cin_version, CINELERRA_VERSION) &&
2115                             strcmp(cin_version, "Unify") &&
2116                             strcmp(cin_version, "5.1") ) {
2117                                 eprintf(_("Warning: XML from cinelerra version %s\n"
2118                                         "Session data may be incompatible."), cin_version);
2119                         }
2120                         if( new_edl->load_xml(&xml_file, LOAD_ALL) ) {
2121                                 eprintf(_("Error: unable to load:\n  %s"), filename);
2122                                 break;
2123                         }
2124                         test_plugins(new_edl, filename);
2125                         int groups = new_edl->regroup(session->group_number);
2126                         session->group_number += groups;
2127                         switch( edl_mode ) {
2128                         case LOADMODE_EDL_CLIP: {
2129                                 sprintf(new_edl->local_session->clip_title, _("Clip %d"),
2130                                         session->clip_number++);
2131                                 char string[BCSTRLEN];
2132                                 time_t t;  time(&t);
2133                                 ctime_r(&t, string);
2134                                 snprintf(new_edl->local_session->clip_notes,
2135                                         sizeof(new_edl->local_session->clip_notes),
2136                                         +("%sFrom: %s"), string, filename);
2137                                 switch( load_mode ) {
2138                                 case LOADMODE_REPLACE:
2139                                 case LOADMODE_REPLACE_CONCATENATE:
2140                                         strcpy(session->filename, filename);
2141                                         if( update_filename ) set_filename(filename);
2142                                         break;
2143                                 }
2144                                 result = 0;
2145                                 break; }
2146                         case LOADMODE_EDL_NESTED: {
2147                                 EDL *nested_edl = new EDL;
2148                                 nested_edl->create_objects();
2149                                 nested_edl->copy_session(edl, -1);
2150                                 nested_edl->create_nested(new_edl);
2151                                 nested_edl->set_path(filename);
2152                                 new_edl->remove_user();
2153                                 new_edl = nested_edl;
2154                                 result = 0;
2155                                 break; }
2156                         case LOADMODE_EDL_FILEREF: {
2157                                 result = create_ref(new_asset, new_edl);
2158                                 if( result ) break;
2159                                 new_assets.append(new_asset);
2160                                 new_asset->add_user();
2161                                 new_edl->remove_user();
2162                                 new_edl = new EDL;
2163                                 new_edl->create_objects();
2164                                 new_edl->copy_session(edl, -1);
2165                                 asset_to_edl(new_edl, new_asset);
2166                                 delete new_file;
2167                                 new_file = new File;
2168                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2169                                 break; }
2170                         }
2171                         if( !result ) {
2172                                 new_edls.append(new_edl);
2173                                 new_edl->add_user();
2174                         }
2175                         else
2176                                 eprintf(_("Error: Unable to load xml:\n  %s"), new_asset->path);
2177                         break; }
2178                 }
2179
2180                 new_edl->Garbage::remove_user();
2181                 new_asset->Garbage::remove_user();
2182
2183 // Store for testing index
2184                 new_files.append(new_file);
2185         }
2186
2187 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2188
2189         if(!result) {
2190                 gui->reset_default_message();
2191                 gui->default_message();
2192         }
2193
2194 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2195
2196 // Paste them.
2197 // Don't back up here.
2198         if( new_edls.size() ) {
2199 // For pasting, clear the active region
2200                 if( load_mode == LOADMODE_PASTE ) {
2201                         double start = edl->local_session->get_selectionstart();
2202                         double end = edl->local_session->get_selectionend();
2203                         if(!EQUIV(start, end))
2204                                 edl->clear(start, end,
2205                                         edl->session->labels_follow_edits,
2206                                         edl->session->plugins_follow_edits,
2207                                         edl->session->autos_follow_edits);
2208
2209                         paste_edls(&new_edls, load_mode, 0, -1,
2210                                 edl->session->labels_follow_edits,
2211                                 edl->session->plugins_follow_edits,
2212                                 edl->session->autos_follow_edits,
2213                                 0); // overwrite
2214                 }
2215                 else if( load_mode == LOADMODE_NEW_TRACKS &&
2216                          edl_mode != LOADMODE_EDL_CLIP )
2217                         paste_edls(&new_edls, load_mode, 0, -1, 0, 0, 0, 0);
2218                 else if( load_mode != LOADMODE_RESOURCESONLY ||
2219                          edl_mode == LOADMODE_EDL_CLIP )
2220                         paste_edls(&new_edls, load_mode, 0, -1, 1, 1, 1, 0);
2221                 else
2222                         paste_edls(&new_edls, LOADMODE_NOTHING, 0, -1, 0, 0, 0, 0);
2223
2224         }
2225
2226 // Add new assets to EDL and schedule assets for index building.
2227         int got_indexes = 0;
2228         for( int i=0; i<new_edls.size(); ++i ) {
2229                 EDL *new_edl = new_edls[i];
2230                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2231                         mainindexes->add_indexable(new_edl->nested_edls[j]);
2232                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2233                         got_indexes = 1;
2234                 }
2235
2236         }
2237
2238         for( int i=0; i<new_assets.size(); ++i ) {
2239                 Asset *new_asset = new_assets[i];
2240                 mainindexes->add_indexable(new_asset);
2241                 edl->assets->update(new_asset);
2242                 got_indexes = 1;
2243         }
2244
2245 // Start examining next batch of index files
2246         if(got_indexes) mainindexes->start_build();
2247
2248 // Open plugin GUIs
2249         Track *track = edl->tracks->first;
2250         while( track ) {
2251                 for( int j = 0; j < track->plugin_set.size(); j++ ) {
2252                         PluginSet *plugins = track->plugin_set[j];
2253                         Plugin *plugin = plugins->get_first_plugin();
2254
2255                         while(plugin) {
2256                                 if( load_mode == LOADMODE_REPLACE ||
2257                                     load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2258                                         if( plugin->plugin_type == PLUGIN_STANDALONE &&
2259                                             plugin->show ) {
2260                                                 show_plugin(plugin);
2261                                         }
2262                                 }
2263
2264                                 plugin = (Plugin*)plugin->next;
2265                         }
2266                 }
2267
2268                 track = track->next;
2269         }
2270
2271         // opening new session
2272         if( ( load_mode == LOADMODE_REPLACE ||
2273               load_mode == LOADMODE_REPLACE_CONCATENATE ) &&
2274             (ftype != FILE_IS_XML || edl_mode != LOADMODE_EDL_CLIP) ) {
2275                 select_asset(0, 0);
2276                 edl->session->proxy_scale = 1;
2277                 edl->session->proxy_disabled_scale = 1;
2278                 edl->session->proxy_use_scaler = 0;
2279                 edl->session->proxy_auto_scale = 0;
2280                 edl->session->proxy_beep = 0;
2281                 edl->local_session->preview_start = 0;
2282                 edl->local_session->preview_end = -1;
2283                 edl->local_session->loop_playback = 0;
2284                 edl->local_session->set_selectionstart(0);
2285                 edl->local_session->set_selectionend(0);
2286                 edl->local_session->unset_inpoint();
2287                 edl->local_session-> unset_outpoint();
2288                 set_brender_active(0, 0);
2289                 fit_selection();
2290                 goto_start();
2291         }
2292
2293         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
2294             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
2295                 ArrayList<Indexable *> orig_idxbls;
2296                 for( int i=0; i<new_assets.size(); ++i )
2297                         orig_idxbls.append(new_assets.get(i));
2298                 for( int i=0; i<new_edls.size(); ++i ) {
2299                         EDL *new_edl = new_edls[i];
2300                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2301                                 if( track->data_type != TRACK_VIDEO ) continue;
2302                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2303                                         Indexable *idxbl = (Indexable *)edit->asset;
2304                                         if( !idxbl ) continue;
2305                                         if( !idxbl->have_video() ) continue;
2306                                         if( edit->channel != 0 ) continue; // first layer only
2307                                         orig_idxbls.append(edit->asset);
2308                                 }
2309                         }
2310                 }
2311                 gui->unlock_window(); // to update progress bar
2312                 int ret = render_proxy(orig_idxbls);
2313                 gui->lock_window("MWindow::load_filenames");
2314                 float gain = edl->session->proxy_beep;
2315                 if( ret >= 0 && gain > 0 ) {
2316                         if( ret > 0 )
2317                                 beep(2000., 1.5, gain);
2318                         else
2319                                 beep(4000., 0.25, gain);
2320                 }
2321         }
2322
2323 // need to update undo before project, since mwindow is unlocked & a new load
2324 // can begin here.  Should really prevent loading until we're done.
2325 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2326         undo_after(_("load"), LOAD_ALL);
2327
2328         for(int i = 0; i < new_edls.size(); i++)
2329         {
2330                 new_edls[i]->remove_user();
2331         }
2332 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2333
2334         new_edls.remove_all();
2335
2336         for(int i = 0; i < new_assets.size(); i++)
2337         {
2338                 new_assets[i]->Garbage::remove_user();
2339         }
2340
2341         new_assets.remove_all();
2342         new_files.remove_all_objects();
2343
2344
2345 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2346         if(load_mode == LOADMODE_REPLACE ||
2347                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2348         {
2349                 session->changes_made = 0;
2350         }
2351         else
2352         {
2353                 session->changes_made = 1;
2354         }
2355
2356         gui->stop_hourglass();
2357
2358
2359 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2360         update_project(load_mode);
2361
2362 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2363
2364         return 0;
2365 }
2366
2367 int MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2368 {
2369         Asset *format_asset = new Asset;
2370         format_asset->format = FILE_FFMPEG;
2371         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2372         int new_scale = edl->session->proxy_scale;
2373         ProxyRender proxy_render(this, format_asset, new_scale);
2374
2375         for( int i=0; i<new_idxbls.size(); ++i ) {
2376                 Indexable *orig = new_idxbls.get(i);
2377                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2378                 if( !proxy ) continue;
2379                 FileSystem fs;
2380                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2381                 int got_it = exists && // if proxy exists, and is newer than orig
2382                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2383                 if( got_it ) continue;
2384                 proxy_render.add_needed(orig, proxy);
2385         }
2386
2387 // render needed proxies
2388         int result = proxy_render.create_needed_proxies(new_scale);
2389         if( !result ) {
2390                 add_proxy(&proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2391         }
2392         format_asset->remove_user();
2393         return !result ? proxy_render.needed_proxies.size() : -1;
2394 }
2395
2396 int MWindow::enable_proxy()
2397 {
2398         int ret = 0;
2399         if( edl->session->proxy_scale == 1 &&
2400             edl->session->proxy_disabled_scale != 1 ) {
2401                 int new_scale = edl->session->proxy_disabled_scale;
2402                 int new_use_scaler = edl->session->proxy_use_scaler;
2403                 Asset *asset = new Asset;
2404                 asset->format = FILE_FFMPEG;
2405                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2406                 ret = to_proxy(asset, new_scale, new_use_scaler);
2407                 asset->remove_user();
2408                 if( ret > 0 ) {
2409                         float gain = edl->session->proxy_beep;
2410                         beep(2000., 1.5, gain);
2411                 }
2412                 edl->session->proxy_disabled_scale = 1;
2413                 gui->lock_window("MWindow::to_proxy");
2414                 update_project(LOADMODE_REPLACE);
2415                 gui->unlock_window();
2416         }
2417         return 1;
2418 }
2419
2420 int MWindow::disable_proxy()
2421 {
2422         if( edl->session->proxy_scale != 1 &&
2423             edl->session->proxy_disabled_scale == 1 ) {
2424                 int old_scale = edl->session->proxy_scale, new_scale = 1;
2425                 int new_use_scaler = edl->session->proxy_use_scaler;
2426                 Asset *asset = new Asset;
2427                 asset->format = FILE_FFMPEG;
2428                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2429                 to_proxy(asset, new_scale, new_use_scaler);
2430                 asset->remove_user();
2431                 edl->session->proxy_disabled_scale = old_scale;
2432                 gui->lock_window("MWindow::to_proxy");
2433                 update_project(LOADMODE_REPLACE);
2434                 gui->unlock_window();
2435         }
2436         return 1;
2437 }
2438
2439 int MWindow::to_proxy(Asset *asset, int new_scale, int new_use_scaler)
2440 {
2441         ArrayList<Indexable*> orig_idxbls;
2442         ArrayList<Indexable*> proxy_assets;
2443
2444         edl->Garbage::add_user();
2445         save_backup();
2446         undo_before(_("proxy"), this);
2447         int asset_scale = new_scale == 1 ? 0 :
2448                         !new_use_scaler ? 1 : new_scale;
2449         ProxyRender proxy_render(this, asset, asset_scale);
2450
2451 // revert project to original size from current size
2452 // remove all session proxy assets at the at the current proxy_scale
2453         int proxy_scale = edl->session->proxy_scale;
2454
2455         if( proxy_scale > 1 ) {
2456                 Asset *orig_asset = edl->assets->first;
2457                 for( ; orig_asset; orig_asset=orig_asset->next ) {
2458                         char new_path[BCTEXTLEN];
2459                         proxy_render.to_proxy_path(new_path, orig_asset, proxy_scale);
2460 // test if proxy asset was already added to proxy_assets
2461                         int got_it = 0;
2462                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2463                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2464                         if( got_it ) continue;
2465                         Asset *proxy_asset = edl->assets->get_asset(new_path);
2466                         if( !proxy_asset ) continue;
2467 // add pointer to existing EDL asset if it exists
2468 // EDL won't delete it unless it's the same pointer.
2469                         proxy_assets.append(proxy_asset);
2470                         proxy_asset->add_user();
2471                         orig_idxbls.append(orig_asset);
2472                         orig_asset->add_user();
2473                 }
2474                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2475                         EDL *orig_nested = edl->nested_edls[i];
2476                         char new_path[BCTEXTLEN];
2477                         if( !ProxyRender::from_proxy_path(new_path, orig_nested, proxy_scale) )
2478                                 continue;
2479                         proxy_render.to_proxy_path(new_path, orig_nested, proxy_scale);
2480 // test if proxy asset was already added to proxy_assets
2481                         int got_it = 0;
2482                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2483                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2484                         if( got_it ) continue;
2485                         Asset *proxy_nested = edl->assets->get_asset(new_path);
2486                         if( !proxy_nested ) continue;
2487 // add pointer to existing EDL asset if it exists
2488 // EDL won't delete it unless it's the same pointer.
2489                         proxy_assets.append(proxy_nested);
2490                         proxy_nested->add_user();
2491                         orig_idxbls.append(orig_nested);
2492                         orig_nested->add_user();
2493                 }
2494
2495 // convert from the proxy assets to the original assets
2496                 edl->set_proxy(1, 0, &proxy_assets, &orig_idxbls);
2497
2498 // remove the references
2499                 for( int i=0; i<proxy_assets.size(); ++i ) {
2500                         Asset *proxy = (Asset *) proxy_assets[i];
2501                         proxy->width = proxy->actual_width;
2502                         proxy->height = proxy->actual_height;
2503                         proxy->remove_user();
2504                         edl->assets->remove_pointer(proxy);
2505                         proxy->remove_user();
2506                 }
2507                 proxy_assets.remove_all();
2508                 for( int i = 0; i < orig_idxbls.size(); i++ )
2509                         orig_idxbls[i]->remove_user();
2510                 orig_idxbls.remove_all();
2511         }
2512
2513         ArrayList<char *> confirm_paths;    // test for new files
2514         confirm_paths.set_array_delete();
2515
2516 // convert to new size if not original size
2517         if( new_scale != 1 ) {
2518                 FileSystem fs;
2519                 Asset *orig = edl->assets->first;
2520                 for( ; orig; orig=orig->next ) {
2521                         Asset *proxy = proxy_render.add_original(orig, new_scale);
2522                         if( !proxy ) continue;
2523                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2524                         int got_it = exists && // if proxy exists, and is newer than orig
2525                             fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2526                         if( !got_it ) {
2527                                 if( exists ) // prompt user to overwrite
2528                                         confirm_paths.append(cstrdup(proxy->path));
2529                                 proxy_render.add_needed(orig, proxy);
2530                         }
2531                 }
2532                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2533                         EDL *orig_nested = edl->nested_edls[i];
2534                         Asset *proxy = proxy_render.add_original(orig_nested, new_scale);
2535                         if( !proxy ) continue;
2536                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2537                         int got_it = exists && // if proxy exists, and is newer than orig_nested
2538                             fs.get_date(proxy->path) > fs.get_date(orig_nested->path) ? 1 : 0;
2539                         if( !got_it ) {
2540                                 if( exists ) // prompt user to overwrite
2541                                         confirm_paths.append(cstrdup(proxy->path));
2542                                 proxy_render.add_needed(orig_nested, proxy);
2543                         }
2544                 }
2545         }
2546
2547         int result = 0;
2548 // test for existing files
2549         if( confirm_paths.size() ) {
2550                 result = ConfirmSave::test_files(this, &confirm_paths);
2551                 confirm_paths.remove_all_objects();
2552         }
2553
2554         if( !result )
2555                 result = proxy_render.create_needed_proxies(new_scale);
2556
2557         if( !result ) // resize project
2558                 edl->set_proxy(new_scale, new_use_scaler,
2559                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2560
2561         undo_after(_("proxy"), LOAD_ALL);
2562         edl->Garbage::remove_user();
2563         restart_brender();
2564
2565         return !result ? proxy_render.needed_proxies.size() : -1;
2566 }
2567
2568 void MWindow::test_plugins(EDL *new_edl, const char *path)
2569 {
2570         char string[BCTEXTLEN];
2571
2572 // Do a check whether plugins exist
2573         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2574                 for( int k=0; k<track->plugin_set.total; ++k ) {
2575                         PluginSet *plugin_set = track->plugin_set[k];
2576                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2577                                         plugin; plugin = (Plugin*)plugin->next ) {
2578                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2579 // ok we need to find it in plugindb
2580                                 PluginServer *server =
2581                                         scan_plugindb(plugin->title, track->data_type);
2582                                 if( !server || server->transition ) {
2583                                         sprintf(string,
2584         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2585           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2586                                                 "effect", _(plugin->title), path);
2587                                         MainError::show_error(string);
2588                                 }
2589                         }
2590                 }
2591
2592                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2593                         if( !edit->transition ) continue;
2594 // ok we need to find transition in plugindb
2595                         PluginServer *server =
2596                                 scan_plugindb(edit->transition->title, track->data_type);
2597                         if( !server || !server->transition ) {
2598                                 sprintf(string,
2599         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2600           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2601                                         "transition", _(edit->transition->title), path);
2602                                 MainError::show_error(string);
2603                         }
2604                 }
2605         }
2606 }
2607
2608
2609 void MWindow::init_shm(const char *pfn, int64_t min)
2610 {
2611         int64_t result = 0;
2612 // Fix shared memory
2613         FILE *fd = fopen(pfn, "r");
2614         if( fd ) {
2615                 fscanf(fd, "%jd", &result);
2616                 fclose(fd);
2617                 if( result >= min ) return;
2618         }
2619
2620         fd = fopen(pfn, "w");
2621         if( !fd ) return;
2622         fprintf(fd, "0x%jx", min);
2623         fclose(fd);
2624
2625         fd = fopen(pfn, "r");
2626         if( !fd ) {
2627                 eprintf(_("MWindow::init_shm: couldn't open %s for reading.\n"), pfn);
2628                 return;
2629         }
2630
2631         fscanf(fd, "%jd", &result);
2632         fclose(fd);
2633         if( result < min ) {
2634                 eprintf(_("MWindow::init_shm: %s is %p.\n"
2635                         "you probably need to be root, or:\n"
2636                         "as root, run: echo 0x%jx > %s\n"
2637                         "before trying to start cinelerra.\n"
2638                         "It should be at least 0x%jx for Cinelerra.\n"),
2639                         pfn, (void *)result, min, pfn, min);
2640         }
2641 }
2642
2643 void MWindow::create_objects(int want_gui,
2644         int want_new,
2645         char *config_path)
2646 {
2647         const int debug = 0;
2648         if(debug) PRINT_TRACE
2649
2650 // For some reason, init_signals must come after show_splash or the signals won't
2651 // get trapped.
2652         init_signals();
2653         if(debug) PRINT_TRACE
2654         init_3d();
2655
2656         if(debug) PRINT_TRACE
2657         show_splash();
2658
2659         if(debug) PRINT_TRACE
2660         default_standard = default_std();
2661         init_defaults(defaults, config_path);
2662         check_language();
2663         init_preferences();
2664         if(splash_window)
2665                 splash_window->update_status(_("Initializing Plugins"));
2666         init_plugins(this, preferences);
2667         if(debug) PRINT_TRACE
2668         init_ladspa_plugins(this, preferences);
2669         if(debug) PRINT_TRACE
2670         init_plugin_tips(*plugindb, cin_lang);
2671         if(splash_window)
2672                 splash_window->update_status(_("Initializing GUI"));
2673         if(debug) PRINT_TRACE
2674         init_theme();
2675
2676         if(debug) PRINT_TRACE
2677         init_error();
2678
2679         if(splash_window)
2680                 splash_window->update_status(_("Initializing Fonts"));
2681         char string[BCTEXTLEN];
2682         strcpy(string, preferences->plugin_dir);
2683         strcat(string, "/" FONT_SEARCHPATH);
2684         BC_Resources::init_fontconfig(string);
2685         if(debug) PRINT_TRACE
2686         init_wintv();
2687
2688 // Default project created here
2689         init_edl();
2690         if(debug) PRINT_TRACE
2691
2692         init_cache();
2693         if(debug) PRINT_TRACE
2694
2695         Timer timer;
2696
2697         init_awindow();
2698         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2699
2700         init_compositor();
2701         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2702
2703 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2704         if(session->show_vwindow)
2705                 get_viewer(1, DEFAULT_VWINDOW);
2706         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2707
2708         init_gui();
2709         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2710
2711         init_levelwindow();
2712         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2713
2714         init_indexes();
2715         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2716
2717         init_channeldb();
2718         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2719
2720         init_gwindow();
2721         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2722
2723         init_render();
2724         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2725
2726         init_shuttle();
2727         init_brender();
2728         init_exportedl();
2729         init_commercials();
2730         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2731         mainprogress = new MainProgress(this, gui);
2732         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2733         undo = new MainUndo(this);
2734
2735         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2736
2737         plugin_guis = new PluginGUIs(this);
2738         dead_plugins = new ArrayList<PluginServer*>;
2739         keyframe_threads = new ArrayList<KeyFrameThread*>;
2740
2741         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2742                 __LINE__,
2743                 vwindows.size(),
2744                 session->show_vwindow);
2745
2746 // Show all vwindows
2747 //      if(session->show_vwindow) {
2748 //              for(int j = 0; j < vwindows.size(); j++) {
2749 //                      VWindow *vwindow = vwindows[j];
2750 //                      if( !vwindow->is_running() ) continue;
2751 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2752 //                              __LINE__,
2753 //                              vwindow);
2754 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2755 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2756 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2757 //                      vwindow->gui->show_window();
2758 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2759 //                      vwindow->gui->unlock_window();
2760 //              }
2761 //      }
2762
2763
2764         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2765
2766         if(session->show_cwindow)
2767         {
2768                 cwindow->gui->lock_window("MWindow::create_objects 1");
2769                 cwindow->gui->show_window();
2770                 cwindow->gui->unlock_window();
2771         }
2772
2773         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2774         if(session->show_awindow)
2775         {
2776                 awindow->gui->lock_window("MWindow::create_objects 1");
2777                 awindow->gui->show_window();
2778                 awindow->gui->unlock_window();
2779         }
2780
2781         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2782         if(session->show_lwindow)
2783         {
2784                 lwindow->gui->lock_window("MWindow::create_objects 1");
2785                 lwindow->gui->show_window();
2786                 lwindow->gui->unlock_window();
2787         }
2788
2789         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2790                 __LINE__,
2791                 (int)timer.get_difference(),
2792                 gwindow->gui);
2793         if(session->show_gwindow)
2794         {
2795                 gwindow->gui->lock_window("MWindow::create_objects 1");
2796                 gwindow->gui->show_window();
2797                 gwindow->gui->unlock_window();
2798         }
2799
2800         if(debug) PRINT_TRACE
2801
2802         gui->lock_window("MWindow::create_objects 1");
2803         gui->mainmenu->load_defaults(defaults);
2804         gui->mainmenu->update_toggles(0);
2805         gui->update_patchbay();
2806         gui->draw_canvas(0, 0);
2807         gui->draw_cursor(1);
2808         gui->show_window();
2809         gui->raise_window();
2810         gui->unlock_window();
2811         cwindow->gui->lock_window("MWindow::create_objects 1");
2812         cwindow->gui->tool_panel->raise_tool();
2813         cwindow->gui->unlock_window();
2814         if(debug) PRINT_TRACE
2815
2816         if(preferences->use_tipwindow)
2817                 init_tipwindow();
2818         if(debug) PRINT_TRACE
2819
2820         gui->add_keyboard_listener(
2821                 (int (BC_WindowBase::*)(BC_WindowBase *))
2822                 &MWindowGUI::keyboard_listener);
2823
2824         hide_splash();
2825         init_shm("/proc/sys/kernel/shmmax", 0x7fffffff);
2826         init_shm("/proc/sys/kernel/shmmni", 0x4000);
2827         if(debug) PRINT_TRACE
2828
2829         BC_WindowBase::get_resources()->vframe_shm = 1;
2830 }
2831
2832 int MWindow::uses_opengl()
2833 {
2834         if( !playback_3d || !playback_3d->running() ) return 0;
2835         PlaybackConfig *playback_config = edl->session->playback_config;
2836         return playback_config->vconfig->driver == PLAYBACK_X11_GL ? 1 : 0;
2837 }
2838
2839 void MWindow::show_splash()
2840 {
2841 #include "data/heroine_logo9_png.h"
2842         VFrame *frame = new VFramePng(heroine_logo9_png);
2843         BC_DisplayInfo dpyi;
2844         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2845         int rr = (rw < rh ? rw : rh) / 4;
2846         splash_window = new SplashGUI(frame, rr, rr);
2847         splash_window->create_objects();
2848 }
2849
2850 void MWindow::hide_splash()
2851 {
2852         if(splash_window)
2853                 delete splash_window;
2854         splash_window = 0;
2855 }
2856
2857
2858 void MWindow::start()
2859 {
2860 ENABLE_BUFFER
2861 //PRINT_TRACE
2862 //      vwindows[DEFAULT_VWINDOW]->start();
2863         awindow->start();
2864 //PRINT_TRACE
2865         cwindow->start();
2866 //PRINT_TRACE
2867         lwindow->start();
2868 //PRINT_TRACE
2869         gwindow->start();
2870 //PRINT_TRACE
2871 //      Thread::start();
2872 //PRINT_TRACE
2873         playback_3d->start();
2874 //PRINT_TRACE
2875 }
2876
2877 void MWindow::run()
2878 {
2879         run_lock->lock("MWindow::run");
2880         gui->run_window();
2881         stop_playback(1);
2882
2883         brender_lock->lock("MWindow::run 1");
2884         delete brender;         brender = 0;
2885         brender_lock->unlock();
2886
2887         interrupt_indexes();
2888         clean_indexes();
2889         save_defaults();
2890         run_lock->unlock();
2891 }
2892
2893 void MWindow::show_vwindow()
2894 {
2895         int total_running = 0;
2896         session->show_vwindow = 1;
2897
2898 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2899 // Raise all windows which are visible
2900         for(int j = 0; j < vwindows.size(); j++) {
2901                 VWindow *vwindow = vwindows[j];
2902                 if( !vwindow->is_running() ) continue;
2903                 vwindow->gui->lock_window("MWindow::show_vwindow");
2904                 vwindow->gui->show_window(0);
2905                 vwindow->gui->raise_window();
2906                 vwindow->gui->flush();
2907                 vwindow->gui->unlock_window();
2908                 total_running++;
2909         }
2910
2911 // If no windows visible
2912         if(!total_running)
2913         {
2914                 get_viewer(1, DEFAULT_VWINDOW);
2915         }
2916
2917         gui->mainmenu->show_vwindow->set_checked(1);
2918 }
2919
2920 void MWindow::show_awindow()
2921 {
2922         session->show_awindow = 1;
2923         awindow->gui->lock_window("MWindow::show_awindow");
2924         awindow->gui->show_window();
2925         awindow->gui->raise_window();
2926         awindow->gui->flush();
2927         awindow->gui->unlock_window();
2928         gui->mainmenu->show_awindow->set_checked(1);
2929 }
2930
2931 char *MWindow::get_cwindow_display()
2932 {
2933         char *x11_host = screens < 2 || session->window_config == 0 ?
2934                 session->a_x11_host : session->b_x11_host;
2935         return *x11_host ? x11_host : 0;
2936 }
2937
2938 void MWindow::show_cwindow()
2939 {
2940         session->show_cwindow = 1;
2941         cwindow->show_window();
2942         gui->mainmenu->show_cwindow->set_checked(1);
2943 }
2944
2945 void MWindow::show_gwindow()
2946 {
2947         session->show_gwindow = 1;
2948
2949         gwindow->gui->lock_window("MWindow::show_gwindow");
2950         gwindow->gui->show_window();
2951         gwindow->gui->raise_window();
2952         gwindow->gui->flush();
2953         gwindow->gui->unlock_window();
2954
2955         gui->mainmenu->show_gwindow->set_checked(1);
2956 }
2957 void MWindow::hide_gwindow()
2958 {
2959         session->show_gwindow = 0;
2960
2961         gwindow->gui->lock_window("MWindow::show_gwindow");
2962         gwindow->gui->hide_window();
2963         gwindow->gui->unlock_window();
2964 }
2965
2966 void MWindow::show_lwindow()
2967 {
2968         session->show_lwindow = 1;
2969         lwindow->gui->lock_window("MWindow::show_lwindow");
2970         lwindow->gui->show_window();
2971         lwindow->gui->raise_window();
2972         lwindow->gui->flush();
2973         lwindow->gui->unlock_window();
2974         gui->mainmenu->show_lwindow->set_checked(1);
2975 }
2976
2977 void MWindow::restore_windows()
2978 {
2979         if( !session->show_vwindow ) {
2980                 for( int i=0, n=vwindows.size(); i<n; ++i ) {
2981                         VWindow *vwindow = vwindows[i];
2982                         if( !vwindow || !vwindow->is_running() ) continue;
2983                         vwindow->gui->lock_window("MWindow::restore_windows");
2984                         vwindow->gui->close(1);
2985                         vwindow->gui->unlock_window();
2986                 }
2987         }
2988         else
2989                 show_vwindow();
2990
2991         if( !session->show_awindow && !awindow->gui->is_hidden() ) {
2992                 awindow->gui->lock_window("MWindow::restore_windows");
2993                 awindow->gui->close_event();
2994                 awindow->gui->unlock_window();
2995         }
2996         else if( session->show_awindow && awindow->gui->is_hidden() )
2997                 show_awindow();
2998
2999         if( !session->show_cwindow && !cwindow->gui->is_hidden() ) {
3000                 cwindow->gui->lock_window("MWindow::restore_windows");
3001                 cwindow->hide_window();
3002                 cwindow->gui->unlock_window();
3003         }
3004         else if( session->show_cwindow && cwindow->gui->is_hidden() )
3005                 cwindow->show_window();
3006
3007         if( !session->show_gwindow && !gwindow->gui->is_hidden() ) {
3008                 gwindow->gui->lock_window("MWindow::restore_windows");
3009                 gwindow->gui->close_event();
3010                 gwindow->gui->unlock_window();
3011         }
3012         else if( session->show_gwindow && gwindow->gui->is_hidden() )
3013                 show_gwindow();
3014
3015         if( !session->show_lwindow && !lwindow->gui->is_hidden() ) {
3016                 lwindow->gui->lock_window("MWindow::restore_windows");
3017                 lwindow->gui->close_event();
3018                 lwindow->gui->unlock_window();
3019         }
3020         else if( session->show_lwindow && lwindow->gui->is_hidden() )
3021                 show_lwindow();
3022
3023         gui->focus();
3024 }
3025
3026 void MWindow::load_layout(const char *layout)
3027 {
3028         char path[BCTEXTLEN];
3029         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3030         session->load_file(path);
3031         restore_windows();
3032         gui->default_positions();
3033         save_defaults();
3034 }
3035
3036 void MWindow::save_layout(const char *layout)
3037 {
3038         char path[BCTEXTLEN];
3039         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3040         session->save_file(path);
3041 }
3042
3043 void MWindow::delete_layout(const char *layout)
3044 {
3045         char path[BCTEXTLEN];
3046         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3047         unlink(path);
3048 }
3049
3050 int MWindow::tile_windows(int window_config)
3051 {
3052         int need_reload = 0;
3053         int play_config = window_config==0 ? 0 : 1;
3054         edl->session->playback_config->load_defaults(defaults, play_config);
3055         session->default_window_positions(window_config);
3056         if( screens == 1 ) {
3057                 gui->default_positions();
3058                 sync_parameters(CHANGE_ALL);
3059         }
3060         else
3061                 need_reload = 1;
3062         return need_reload;
3063 }
3064
3065 void MWindow::toggle_loop_playback()
3066 {
3067         edl->local_session->loop_playback = !edl->local_session->loop_playback;
3068         set_loop_boundaries();
3069         save_backup();
3070
3071         gui->draw_overlays(1);
3072         sync_parameters(CHANGE_PARAMS);
3073 }
3074
3075 void MWindow::set_screens(int value)
3076 {
3077         screens = value;
3078 }
3079
3080 void MWindow::set_auto_keyframes(int value)
3081 {
3082         edl->session->auto_keyframes = value;
3083         gui->mbuttons->edit_panel->keyframe->update(value);
3084         gui->flush();
3085         cwindow->gui->lock_window("MWindow::set_auto_keyframes");
3086         cwindow->gui->edit_panel->keyframe->update(value);
3087         cwindow->gui->flush();
3088         cwindow->gui->unlock_window();
3089 }
3090
3091 void MWindow::set_span_keyframes(int value)
3092 {
3093         edl->session->span_keyframes = value;
3094         gui->mbuttons->edit_panel->span_keyframe->update(value);
3095         gui->flush();
3096         cwindow->gui->lock_window("MWindow::set_span_keyframes");
3097         cwindow->gui->edit_panel->span_keyframe->update(value);
3098         cwindow->gui->flush();
3099         cwindow->gui->unlock_window();
3100 }
3101
3102 void MWindow::set_auto_visibility(Autos *autos, int value)
3103 {
3104         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
3105                 edl->session->auto_conf->plugins = value;
3106         else if( autos->autoidx >= 0 )
3107                 edl->session->auto_conf->autos[autos->autoidx] = value;
3108         else
3109                 return;
3110
3111         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3112         gui->mainmenu->update_toggles(1);
3113         gui->unlock_window();
3114         gwindow->gui->update_toggles(1);
3115         gui->lock_window("MWindow::set_auto_visibility");
3116 }
3117
3118 void MWindow::set_keyframe_type(int mode)
3119 {
3120         gui->lock_window("MWindow::set_keyframe_type");
3121         edl->local_session->floatauto_type = mode;
3122         gui->mainmenu->update_toggles(0);
3123         gui->unlock_window();
3124 }
3125
3126 int MWindow::set_editing_mode(int new_editing_mode)
3127 {
3128         edl->session->editing_mode = new_editing_mode;
3129         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
3130         gui->mbuttons->edit_panel->update();
3131         gui->set_editing_mode(1);
3132
3133         cwindow->gui->lock_window("MWindow::set_editing_mode");
3134         cwindow->gui->edit_panel->update();
3135         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
3136         cwindow->gui->unlock_window();
3137         return 0;
3138 }
3139
3140 void MWindow::toggle_editing_mode()
3141 {
3142         int mode = edl->session->editing_mode;
3143         if( mode == EDITING_ARROW )
3144                 set_editing_mode(EDITING_IBEAM);
3145         else
3146                 set_editing_mode(EDITING_ARROW);
3147 }
3148
3149 void MWindow::toggle_camera_xyz()
3150 {
3151         gwindow->gui->lock_window("MWindow::toggle_camera_xyz");
3152         gwindow->gui->toggle_camera_xyz();
3153         gwindow->gui->unlock_window();
3154 }
3155
3156 void MWindow::toggle_projector_xyz()
3157 {
3158         gwindow->gui->lock_window("MWindow::toggle_projector_xyz");
3159         gwindow->gui->toggle_projector_xyz();
3160         gwindow->gui->unlock_window();
3161 }
3162
3163 void MWindow::set_labels_follow_edits(int value)
3164 {
3165         edl->session->labels_follow_edits = value;
3166         gui->mbuttons->edit_panel->locklabels->update(value);
3167         gui->mainmenu->labels_follow_edits->set_checked(value);
3168         gui->flush();
3169 }
3170
3171 void MWindow::sync_parameters(int change_type)
3172 {
3173         if( in_destructor ) return;
3174
3175 // Sync engines which are playing back
3176         if( cwindow->playback_engine->is_playing_back ) {
3177                 if( change_type == CHANGE_PARAMS ) {
3178 // TODO: block keyframes until synchronization is done
3179                         cwindow->playback_engine->sync_parameters(edl);
3180                 }
3181                 else {
3182 // Stop and restart
3183                         int command = cwindow->playback_engine->command->command;
3184 // Waiting for tracking to finish would make the restart position more
3185 // accurate but it can't lock the window to stop tracking for some reason.
3186 // Not waiting for tracking gives a faster response but restart position is
3187 // only as accurate as the last tracking update.
3188                         cwindow->playback_engine->transport_stop(0);
3189                         cwindow->playback_engine->next_command->realtime = 1;
3190                         cwindow->playback_engine->transport_command(command, change_type, edl, 0);
3191                 }
3192         }
3193         else {
3194                 cwindow->refresh_frame(change_type);
3195         }
3196 }
3197
3198 void MWindow::age_caches()
3199 {
3200 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
3201 // __LINE__,
3202 // preferences->cache_size,
3203 // audio_cache->get_memory_usage(1),
3204 // video_cache->get_memory_usage(1),
3205 // frame_cache->get_memory_usage(),
3206 // wave_cache->get_memory_usage(),
3207 // memory_usage);
3208         frame_cache->age_cache(512);
3209         wave_cache->age_cache(8192);
3210
3211         int64_t memory_usage;
3212         int64_t prev_memory_usage = 0;
3213         int result = 0;
3214         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
3215         while( !result && prev_memory_usage !=
3216                 (memory_usage=video_cache->get_memory_usage(1)) &&
3217                 memory_usage > video_size ) {
3218                 video_cache->delete_oldest();
3219                 prev_memory_usage = memory_usage;
3220         }
3221
3222         prev_memory_usage = 0;
3223         result = 0;
3224         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
3225         while( !result && prev_memory_usage !=
3226                 (memory_usage=audio_cache->get_memory_usage(1)) &&
3227                 memory_usage > audio_size ) {
3228                 audio_cache->delete_oldest();
3229                 prev_memory_usage = memory_usage;
3230         }
3231 }
3232
3233 void MWindow::reset_android_remote()
3234 {
3235         gui->use_android_remote(preferences->android_remote);
3236 }
3237
3238
3239 void MWindow::show_keyframe_gui(Plugin *plugin)
3240 {
3241         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
3242 // Find existing thread
3243         for(int i = 0; i < keyframe_threads->size(); i++)
3244         {
3245                 if(keyframe_threads->get(i)->plugin == plugin)
3246                 {
3247                         keyframe_threads->get(i)->start_window(plugin, 0);
3248                         keyframe_gui_lock->unlock();
3249                         return;
3250                 }
3251         }
3252
3253 // Find unused thread
3254         for(int i = 0; i < keyframe_threads->size(); i++)
3255         {
3256                 if(!keyframe_threads->get(i)->plugin)
3257                 {
3258                         keyframe_threads->get(i)->start_window(plugin, 0);
3259                         keyframe_gui_lock->unlock();
3260                         return;
3261                 }
3262         }
3263
3264 // Create new thread
3265         KeyFrameThread *thread = new KeyFrameThread(this);
3266         keyframe_threads->append(thread);
3267         thread->start_window(plugin, 0);
3268
3269         keyframe_gui_lock->unlock();
3270 }
3271
3272
3273 void MWindow::show_plugin(Plugin *plugin)
3274 {
3275         int done = 0;
3276
3277 SET_TRACE
3278 // Remove previously deleted plugin GUIs
3279         dead_plugin_lock->lock("MWindow::show_plugin");
3280         dead_plugins->remove_all_objects();
3281         dead_plugin_lock->unlock();
3282
3283 //printf("MWindow::show_plugin %d\n", __LINE__);
3284 SET_TRACE
3285
3286
3287         plugin_gui_lock->lock("MWindow::show_plugin");
3288         for(int i = 0; i < plugin_guis->total; i++)
3289         {
3290 // Pointer comparison
3291                 if(plugin_guis->get(i)->plugin == plugin)
3292                 {
3293                         plugin_guis->get(i)->raise_window();
3294                         done = 1;
3295                         break;
3296                 }
3297         }
3298 SET_TRACE
3299
3300 //printf("MWindow::show_plugin 1\n");
3301         if( !done && !plugin->track ) {
3302                 printf("MWindow::show_plugin track not defined.\n");
3303                 done = 1;
3304         }
3305         if( !done ) {
3306                 PluginServer *server = scan_plugindb(plugin->title,
3307                         plugin->track->data_type);
3308
3309 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
3310                 if(server && server->uses_gui)
3311                 {
3312                         PluginServer *gui = new PluginServer(*server);
3313                         plugin_guis->append(gui);
3314 // Needs mwindow to do GUI
3315                         gui->set_mwindow(this);
3316                         gui->open_plugin(0, preferences, edl, plugin);
3317                         plugin->show = 1;
3318                         gui->show_gui();
3319                 }
3320         }
3321         plugin_gui_lock->unlock();
3322 // update show/gui_id
3323         sync_parameters(CHANGE_PARAMS);
3324 //printf("MWindow::show_plugin %d\n", __LINE__);
3325 SET_TRACE
3326 //sleep(1);
3327 //printf("MWindow::show_plugin 2\n");
3328 }
3329
3330 void MWindow::hide_plugin(Plugin *plugin, int lock)
3331 {
3332         plugin->show = 0;
3333 // Update the toggle
3334         gui->lock_window("MWindow::hide_plugin");
3335         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3336         gui->unlock_window();
3337
3338         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
3339         for(int i = 0; i < plugin_guis->total; i++)
3340         {
3341                 if(plugin_guis->get(i)->plugin == plugin)
3342                 {
3343                         PluginServer *ptr = plugin_guis->get(i);
3344                         plugin_guis->remove(ptr);
3345                         if(lock) plugin_gui_lock->unlock();
3346 // Last command executed in client side close
3347 // Schedule for deletion
3348                         ptr->hide_gui();
3349                         delete_plugin(ptr);
3350 //sleep(1);
3351                         return;
3352                 }
3353         }
3354         if(lock) plugin_gui_lock->unlock();
3355 // update show/gui_id
3356         sync_parameters(CHANGE_PARAMS);
3357 }
3358
3359 void MWindow::delete_plugin(PluginServer *plugin)
3360 {
3361         dead_plugin_lock->lock("MWindow::delete_plugin");
3362         dead_plugins->append(plugin);
3363         dead_plugin_lock->unlock();
3364 }
3365
3366 void MWindow::hide_plugins()
3367 {
3368         plugin_gui_lock->lock("MWindow::hide_plugins 1");
3369         while(plugin_guis->size())
3370         {
3371                 PluginServer *ptr = plugin_guis->get(0);
3372                 plugin_guis->remove(ptr);
3373                 plugin_gui_lock->unlock();
3374 // Last command executed in client side close
3375 // Schedule for deletion
3376                 ptr->hide_gui();
3377                 delete_plugin(ptr);
3378                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
3379         }
3380         plugin_gui_lock->unlock();
3381
3382         hide_keyframe_guis();
3383 }
3384
3385 void MWindow::hide_keyframe_guis()
3386 {
3387         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
3388         for(int i = 0; i < keyframe_threads->size(); i++)
3389         {
3390                 keyframe_threads->get(i)->close_window();
3391         }
3392         keyframe_gui_lock->unlock();
3393 }
3394
3395 void MWindow::hide_keyframe_gui(Plugin *plugin)
3396 {
3397         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
3398         for(int i = 0; i < keyframe_threads->size(); i++)
3399         {
3400                 if(keyframe_threads->get(i)->plugin == plugin)
3401                 {
3402                         keyframe_threads->get(i)->close_window();
3403                         break;
3404                 }
3405         }
3406         keyframe_gui_lock->unlock();
3407 }
3408
3409 int MWindow::get_hash_color(Edit *edit)
3410 {
3411         Indexable *idxbl = edit->asset ?
3412                 (Indexable*)edit->asset : (Indexable*)edit->nested_edl;
3413         if( !idxbl ) return 0;
3414         char path[BCTEXTLEN];
3415         if( !edit->asset || edit->track->data_type != TRACK_VIDEO ||
3416             edl->session->proxy_scale == 1 ||
3417             ProxyRender::from_proxy_path(path, idxbl, edl->session->proxy_scale) )
3418                 strcpy(path, idxbl->path);
3419         char *cp = strrchr(path, '/');
3420         cp = !cp ? path : cp+1;
3421         uint8_t *bp = (uint8_t*)cp;
3422         int v = 0;
3423         while( *bp ) v += *bp++;
3424         return get_hash_color(v);
3425 }
3426
3427 int MWindow::get_hash_color(int v)
3428 {
3429         int hash = 0x303030;
3430         if( v & 0x01 ) hash ^= 0x000040;
3431         if( v & 0x02 ) hash ^= 0x004000;
3432         if( v & 0x04 ) hash ^= 0x400000;
3433         if( v & 0x08 ) hash ^= 0x080000;
3434         if( v & 0x10 ) hash ^= 0x000800;
3435         if( v & 0x20 ) hash ^= 0x000008;
3436         if( v & 0x40 ) hash ^= 0x404040;
3437         if( v & 0x80 ) hash ^= 0x080808;
3438         return hash;
3439 }
3440
3441 int MWindow::get_group_color(int v)
3442 {
3443         int color = 0x606060;
3444         if( v & 0x01 ) color ^= 0x000080;
3445         if( v & 0x02 ) color ^= 0x008000;
3446         if( v & 0x04 ) color ^= 0x800000;
3447         if( v & 0x08 ) color ^= 0x100000;
3448         if( v & 0x10 ) color ^= 0x001000;
3449         if( v & 0x20 ) color ^= 0x000010;
3450         if( v & 0x40 ) color ^= 0x080808;
3451         if( v & 0x80 ) color ^= 0x909090;
3452         return color;
3453 }
3454
3455 int MWindow::get_title_color(Edit *edit)
3456 {
3457         unsigned color = edit->color & 0xffffff;
3458         unsigned alpha = (~edit->color>>24) & 0xff;
3459         if( !color ) {
3460                 if( edit->group_id )
3461                         color = get_group_color(edit->group_id);
3462                 else if( preferences->autocolor_assets )
3463                         color = get_hash_color(edit);
3464                 else
3465                         return 0;
3466         }
3467         if( alpha == 0xff )
3468                 alpha = session->title_bar_alpha*255;
3469         return color | (~alpha<<24);
3470 }
3471
3472 void MWindow::update_keyframe_guis()
3473 {
3474 // Send new configuration to keyframe GUI's
3475         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
3476         for(int i = 0; i < keyframe_threads->size(); i++)
3477         {
3478                 KeyFrameThread *ptr = keyframe_threads->get(i);
3479                 if(edl->tracks->plugin_exists(ptr->plugin))
3480                         ptr->update_gui(1);
3481                 else
3482                 {
3483                         ptr->close_window();
3484                 }
3485         }
3486         keyframe_gui_lock->unlock();
3487 }
3488
3489 void MWindow::update_plugin_guis(int do_keyframe_guis)
3490 {
3491 // Send new configuration to plugin GUI's
3492         plugin_gui_lock->lock("MWindow::update_plugin_guis");
3493
3494         for(int i = 0; i < plugin_guis->size(); i++)
3495         {
3496                 PluginServer *ptr = plugin_guis->get(i);
3497                 if(edl->tracks->plugin_exists(ptr->plugin))
3498                         ptr->update_gui();
3499                 else
3500                 {
3501 // Schedule for deletion if no plugin
3502                         plugin_guis->remove_number(i);
3503                         i--;
3504
3505                         ptr->hide_gui();
3506                         delete_plugin(ptr);
3507                 }
3508         }
3509
3510
3511 // Change plugin variable if not visible
3512         Track *track = edl->tracks->first;
3513         while(track)
3514         {
3515                 for(int i = 0; i < track->plugin_set.size(); i++)
3516                 {
3517                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3518                         while(plugin)
3519                         {
3520                                 int got_it = 0;
3521                                 for(int i = 0; i < plugin_guis->size(); i++)
3522                                 {
3523                                         PluginServer *server = plugin_guis->get(i);
3524                                         if(server->plugin == plugin)
3525                                         {
3526                                                 got_it = 1;
3527                                                 break;
3528                                         }
3529                                 }
3530
3531                                 if(!got_it) plugin->show = 0;
3532                                 plugin = (Plugin*)plugin->next;
3533                         }
3534                 }
3535
3536                 track = track->next;
3537         }
3538
3539         plugin_gui_lock->unlock();
3540
3541
3542         if(do_keyframe_guis) update_keyframe_guis();
3543 }
3544
3545 void MWindow::stop_plugin_guis()
3546 {
3547 // Send new configuration to plugin GUI's
3548         plugin_gui_lock->lock("MWindow::stop_plugin_guis");
3549
3550         for( int i=0; i<plugin_guis->size(); ++i ) {
3551                 PluginServer *ptr = plugin_guis->get(i);
3552                 if( edl->tracks->plugin_exists(ptr->plugin) ) {
3553                         ptr->render_stop();
3554                 }
3555         }
3556         plugin_gui_lock->unlock(); 
3557 }
3558
3559 int MWindow::plugin_gui_open(Plugin *plugin)
3560 {
3561         int gui_id = plugin->gui_id;
3562         if( gui_id < 0 ) return 0;
3563         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3564         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3565         int result = plugin_server ? 1 : 0;
3566         plugin_gui_lock->unlock();
3567         return result;
3568 }
3569
3570
3571 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3572 {
3573         int gui_id = plugin->gui_id;
3574         if( gui_id < 0 ) return;
3575         plugin_gui_lock->lock("MWindow::render_plugin_gui 0");
3576         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3577         if( plugin_server )
3578                 plugin_server->render_gui(data);
3579         plugin_gui_lock->unlock();
3580 }
3581
3582 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3583 {
3584         int gui_id = plugin->gui_id;
3585         if( gui_id < 0 ) return;
3586         plugin_gui_lock->lock("MWindow::render_plugin_gui 1");
3587         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3588         if( plugin_server )
3589                 plugin_server->render_gui(data, size);
3590         plugin_gui_lock->unlock();
3591 }
3592
3593 void MWindow::reset_plugin_gui_frames(Plugin *plugin)
3594 {
3595         int gui_id = plugin->gui_id;
3596         if( gui_id < 0 ) return;
3597         plugin_gui_lock->lock("MWindow::reset_plugin_gui_frames");
3598         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3599         if( plugin_server )
3600                 plugin_server->reset_plugin_gui_frames();
3601         plugin_gui_lock->unlock();
3602 }
3603
3604 void MWindow::render_plugin_gui_frames(PluginClientFrames *frames, Plugin *plugin)
3605 {
3606         int gui_id = plugin->gui_id;
3607         if( gui_id < 0 ) return;
3608         plugin_gui_lock->lock("MWindow::render_plugin_gui_frames");
3609         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3610         if( plugin_server )
3611                 plugin_server->render_plugin_gui_frames(frames);
3612         plugin_gui_lock->unlock();
3613 }
3614
3615 double MWindow::get_tracking_position()
3616 {
3617         return edl->local_session->get_selectionstart(1);
3618 }
3619
3620 int MWindow::get_tracking_direction()
3621 {
3622         return cwindow->playback_engine->get_direction();
3623 }
3624
3625 void MWindow::update_plugin_states()
3626 {
3627         plugin_gui_lock->lock("MWindow::update_plugin_states");
3628         for(int i = 0; i <&nbs