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