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