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