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