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