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