ff4de5071a26300fa2277b87fd5bb6256c4f3661
[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         //file_server = 0;
214         plugin_guis = 0;
215         dead_plugins = 0;
216         keyframe_threads = 0;
217         create_bd = 0;
218         create_dvd = 0;
219         batch_render = 0;
220         render = 0;
221         edl = 0;
222         gui = 0;
223         cwindow = 0;
224         awindow = 0;
225         gwindow = 0;
226         twindow = 0;
227         wwindow = 0;
228         lwindow = 0;
229         sighandler = 0;
230         restart_status = 0;
231         screens = 1;
232         in_destructor = 0;
233 }
234
235
236 // Need to delete brender temporary here.
237 MWindow::~MWindow()
238 {
239         run_lock->lock("MWindow::~MWindow");
240         in_destructor = 1;
241 //printf("MWindow::~MWindow %d\n", __LINE__);
242         gui->remote_control->deactivate();
243         gui->record->stop();
244 #ifdef HAVE_DVB
245         gui->channel_info->stop();
246 #endif
247         delete create_bd;       create_bd = 0;
248         delete create_dvd;      create_dvd = 0;
249         delete batch_render;    batch_render = 0;
250         delete render;          render = 0;
251         commit_commercial();
252         if( commercials && !commercials->remove_user() ) commercials = 0;
253         close_mixers();
254
255 // Save defaults for open plugins
256         plugin_gui_lock->lock("MWindow::~MWindow");
257         for(int i = 0; i < plugin_guis->size(); i++) {
258                 plugin_guis->get(i)->hide_gui();
259                 delete_plugin(plugin_guis->get(i));
260         }
261         plugin_gui_lock->unlock();
262         hide_keyframe_guis();
263         clean_indexes();
264         save_defaults();
265 // Give up and go to a movie
266 //  cant run valgrind if this is used
267
268         gui->del_keyboard_listener(
269                 (int (BC_WindowBase::*)(BC_WindowBase *))
270                 &MWindowGUI::keyboard_listener);
271 #if 0
272 // release the hounds
273         if( awindow && awindow->gui ) awindow->gui->close(0);
274         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
275         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
276         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
277         if( twindow && twindow->is_running() ) twindow->close_window();
278         if( wwindow && wwindow->is_running() ) wwindow->close_window();
279         vwindows.remove_all_objects();
280         zwindows.remove_all_objects();
281         gui->close(0);
282         if( awindow ) awindow->join();
283         if( cwindow ) cwindow->join();
284         if( lwindow ) lwindow->join();
285         if( twindow ) twindow->join();
286         if( wwindow ) wwindow->join();
287         if( gwindow ) gwindow->join();
288         join();
289 #else
290 // one at a time, or nouveau chokes
291 #define close_gui(win) if( win ) { \
292   if( win->gui ) win->gui->close(0); \
293   win->join(); }
294         close_gui(awindow);
295         close_gui(cwindow);
296         close_gui(lwindow);
297         close_gui(gwindow);
298         close_gui(twindow);
299         close_gui(wwindow);
300         vwindows.remove_all_objects();
301         zwindows.remove_all_objects();
302         gui->close(0);
303         join();
304 #endif
305         reset_caches();
306         dead_plugins->remove_all_objects();
307 // must delete theme before destroying plugindb
308 //  theme destructor will be deleted by delete_plugins
309         delete theme;           theme = 0;
310         delete_plugins();
311         finit_error();
312         keyframe_threads->remove_all_objects();
313         colormodels.remove_all_objects();
314         delete awindow;         awindow = 0;
315         delete lwindow;         lwindow = 0;
316         delete twindow;         twindow = 0;
317         delete wwindow;         wwindow = 0;
318         delete gwindow;         gwindow = 0;
319         delete cwindow;         cwindow = 0;
320         delete gui;             gui = 0;
321         //delete file_server;  file_server = 0; // reusable
322         delete mainindexes;     mainindexes = 0;
323         delete mainprogress;    mainprogress = 0;
324         delete audio_cache;     audio_cache = 0;  // delete the cache after the assets
325         delete video_cache;     video_cache = 0;  // delete the cache after the assets
326         delete frame_cache;     frame_cache = 0;
327         delete wave_cache;      wave_cache = 0;
328         delete plugin_guis;     plugin_guis = 0;
329         delete dead_plugins;    dead_plugins = 0;
330         delete keyframe_threads;  keyframe_threads = 0;
331         delete undo;            undo = 0;
332         delete preferences;     preferences = 0;
333         delete exportedl;       exportedl = 0;
334         delete session;         session = 0;
335         delete defaults;        defaults = 0;
336         delete assets;          assets = 0;
337         delete splash_window;   splash_window = 0;
338         if( !edl->Garbage::remove_user() ) edl = 0;
339         delete channeldb_buz;
340         delete channeldb_v4l2jpeg;
341 // This must be last thread to exit
342         delete playback_3d;     playback_3d = 0;
343         delete dead_plugin_lock;
344         delete plugin_gui_lock;
345         delete vwindows_lock;
346         delete zwindows_lock;
347         delete brender_lock;
348         delete keyframe_gui_lock;
349         colormodels.remove_all_objects();
350         interlace_project_modes.remove_all_objects();
351         interlace_asset_modes.remove_all_objects();
352         interlace_asset_fixmethods.remove_all_objects();
353         sighandler->terminate();
354         delete sighandler;
355         delete run_lock;
356 }
357
358
359 void MWindow::quit()
360 {
361         gui->set_done(0);
362 }
363
364 void MWindow::init_error()
365 {
366         MainError::init_error(this);
367 }
368
369 void MWindow::finit_error()
370 {
371         MainError::finit_error();
372 }
373
374 void MWindow::create_defaults_path(char *string, const char *config_file)
375 {
376 // set the .bcast path
377         FileSystem fs;
378
379         sprintf(string, "%s/", File::get_config_path());
380         fs.complete_path(string);
381         if(!fs.is_dir(string))
382                 fs.create_dir(string);
383
384 // load the defaults
385         strcat(string, config_file);
386 }
387 const char *MWindow::default_std()
388 {
389         char buf[BCTEXTLEN], *p = 0;
390
391         int fd = open(TIMEZONE_NAME, O_RDONLY);
392         if( fd >= 0 ) {
393                 int l = read(fd, buf, sizeof(buf)-1);
394                 close(fd);
395                 if( l > 0 ) {
396                         if( buf[l-1] == '\n' ) --l;
397                         buf[l] = 0;
398                         p = buf;
399                 }
400         }
401         if( !p ) {
402                 int l = readlink(LOCALTIME_LINK, buf, sizeof(buf)-1);
403                 if( l > 0 ) {
404                         buf[l] = 0;
405                         if( !(p=strstr(buf, ZONEINFO_STR)) != 0 ) return "PAL";
406                         p += strlen(ZONEINFO_STR);
407                 }
408         }
409
410         if( p ) {
411                 for( int i=0; ntsc_zones[i]; ++i ) {
412                         if( !strcmp(ntsc_zones[i], p) )
413                                 return "NTSC";
414                 }
415         }
416
417         p = getenv("TZ");
418         if( p ) {
419                 for( int i=0; ntsc_zones[i]; ++i ) {
420                         if( !strcmp(ntsc_zones[i], p) )
421                                 return "NTSC";
422                 }
423         }
424
425 //__timezone: Seconds west of UTC.  240sec/deg
426         double tz_deg = -__timezone / 240.;
427 // from Honolulu = -10, to New York = -5, 15deg/hr   lat -150..-75
428         return tz_deg >= -10*15 && tz_deg <= -5*15 ? "NTSC" : "PAL";
429 }
430
431 void MWindow::fill_preset_defaults(const char *preset, EDLSession *session)
432 {
433         struct formatpresets *fpr;
434
435         for(fpr = &format_presets[0]; fpr->name; fpr++)
436         {
437                 if(strcmp(_(fpr->name), preset) == 0)
438                 {
439                         session->audio_channels = fpr->audio_channels;
440                         session->audio_tracks = fpr->audio_tracks;
441                         session->sample_rate = fpr->sample_rate;
442                         session->video_channels = fpr->video_channels;
443                         session->video_tracks = fpr->video_tracks;
444                         session->frame_rate = fpr->frame_rate;
445                         session->output_w = fpr->output_w;
446                         session->output_h = fpr->output_h;
447                         session->aspect_w = fpr->aspect_w;
448                         session->aspect_h = fpr->aspect_h;
449                         session->interlace_mode = fpr->interlace_mode;
450                         session->color_model = fpr->color_model;
451                         return;
452                 }
453         }
454 }
455
456 const char *MWindow::get_preset_name(int index)
457 {
458         if(index < 0 || index >= (int)MAX_NUM_PRESETS)
459                 return "Error";
460         return _(format_presets[index].name);
461 }
462
463
464 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
465 {
466         char path[BCTEXTLEN];
467 // Use user supplied path
468         if(config_path[0])
469                 strcpy(path, config_path);
470         else
471                 create_defaults_path(path, CONFIG_FILE);
472
473         defaults = new BC_Hash(path);
474         defaults->load();
475 }
476
477
478 void MWindow::check_language()
479 {
480         char curr_lang[BCTEXTLEN]; curr_lang[0] = 0;
481         const char *env_lang = getenv("LANGUAGE");
482         if( !env_lang ) env_lang = getenv("LC_ALL");
483         if( !env_lang ) env_lang = getenv("LANG");
484         if( !env_lang ) {
485                 snprintf(curr_lang, sizeof(curr_lang), "%s_%s-%s",
486                         BC_Resources::language, BC_Resources::region, BC_Resources::encoding);
487                 env_lang = curr_lang;
488         }
489         char last_lang[BCTEXTLEN]; last_lang[0] = 0;
490         defaults->get("LAST_LANG",last_lang);
491         if( strcmp(env_lang,last_lang)) {
492                 printf("lang changed from '%s' to '%s'\n", last_lang, env_lang);
493                 defaults->update("LAST_LANG",env_lang);
494                 char plugin_path[BCTEXTLEN];
495                 create_defaults_path(plugin_path, PLUGIN_FILE);
496                 ::remove(plugin_path);
497                 char ladspa_path[BCTEXTLEN];
498                 create_defaults_path(ladspa_path, LADSPA_FILE);
499                 ::remove(ladspa_path);
500                 defaults->save();
501         }
502         if( strlen(env_lang) > 1 &&
503             ( env_lang[2] == 0 || env_lang[2] == '_'  || env_lang[2] == '.' ) ) {
504                 cin_lang[0] = env_lang[0];  cin_lang[1] = env_lang[1];  cin_lang[2] = 0;
505         }
506         else
507                 strcpy(cin_lang, "en");
508 }
509
510 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
511 {
512         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
513         if( plug_dir ) {
514                 const char *dp = plug_dir;
515                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
516                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
517         }
518         strcpy(path, bp);
519         delete [] base_path;
520 }
521
522 int MWindow::load_plugin_index(MWindow *mwindow, const char *index_path, const char *plugin_dir)
523 {
524 // load index
525         FILE *fp = fopen(index_path, "r");
526         if( !fp ) return -1;
527
528         int ret = 0;
529         char index_line[BCTEXTLEN];
530         int index_version = -1, len = strlen(plugin_dir);
531         if( !fgets(index_line, BCTEXTLEN, fp) ||
532             sscanf(index_line, "%d", &index_version) != 1 ||
533             index_version != PLUGIN_FILE_VERSION ||
534             !fgets(index_line, BCTEXTLEN, fp) ||
535             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
536             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
537
538         ArrayList<PluginServer*> plugins;
539         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
540                 if( index_line[0] == ';' ) continue;
541                 if( index_line[0] == '#' ) continue;
542                 int type = PLUGIN_TYPE_UNKNOWN;
543                 char path[BCTEXTLEN], title[BCTEXTLEN];
544                 int64_t mtime = 0;
545                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
546                         ret = 1; continue;
547                 }
548                 PluginServer *server = 0;
549                 switch( type ) {
550                 case PLUGIN_TYPE_BUILTIN:
551                 case PLUGIN_TYPE_EXECUTABLE:
552                 case PLUGIN_TYPE_LADSPA: {
553                         char plugin_path[BCTEXTLEN];  struct stat st;
554                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
555                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
556                                 ret = 1; continue;
557                         }
558                         server = new PluginServer(mwindow, plugin_path, type);
559                         break; }
560                 case PLUGIN_TYPE_FFMPEG: {
561                         server = new_ffmpeg_server(mwindow, path);
562                         break; }
563                 }
564                 if( !server ) continue;
565                 plugins.append(server);
566 // Create plugin server from index entry
567                 server->set_title(title);
568                 if( server->read_table(index_line) ) {
569                         ret = 1;  continue;
570                 }
571         }
572         fclose(fp);
573
574         if( !ret )
575                 ret = check_plugin_index(plugins, plugin_dir, ".");
576
577         if( !ret )
578                 add_plugins(plugins);
579         else
580                 plugins.remove_all_objects();
581
582         return ret;
583 }
584
585 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
586         const char *plug_dir, const char *plug_path)
587 {
588         char plugin_path[BCTEXTLEN];
589         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
590         FileSystem fs;
591         fs.set_filter( "[*.plugin][*.so]" );
592         if( fs.update(plugin_path) )
593                 return 1;
594
595         for( int i=0; i<fs.dir_list.total; ++i ) {
596                 char fs_path[BCTEXTLEN];
597                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
598                 if( fs.is_dir(fs_path) ) {
599                         get_plugin_path(plugin_path, plug_dir, fs_path);
600                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
601                                 return 1;
602                 }
603                 else if( !plugin_exists(fs_path, plugins) )
604                         return 1;
605         }
606         return 0;
607 }
608
609
610 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
611 {
612         if( !plugindb )
613                 plugindb = new ArrayList<PluginServer*>;
614         init_ffmpeg();
615         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
616         create_defaults_path(index_path, PLUGIN_FILE);
617         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
618         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
619         if( !load_plugin_index(mwindow, index_path, plugin_path) ) return 1;
620         printf("init plugin index: %s\n", plugin_path);
621         FILE *fp = fopen(index_path,"w");
622         if( !fp ) {
623                 fprintf(stderr,_("MWindow::init_plugins: "
624                         "can't create plugin index: %s\n"), index_path);
625                 return 1;
626         }
627         fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
628         fprintf(fp, "%s\n", plugin_path);
629         init_plugin_index(mwindow, preferences, fp, plugin_path);
630         init_ffmpeg_index(mwindow, preferences, fp);
631         fclose(fp);
632         return load_plugin_index(mwindow, index_path, plugin_path);
633 }
634
635 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
636 {
637         char *path = getenv("LADSPA_PATH");
638         char ladspa_path[BCTEXTLEN];
639         if( !path ) {
640                 strncpy(ladspa_path, File::get_ladspa_path(), sizeof(ladspa_path));
641                 path = ladspa_path;
642         }
643         for( int len=0; *path; path+=len ) {
644                 char *cp = strchr(path,':');
645                 len = !cp ? strlen(path) : cp-path;
646                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
647                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
648                 if( cp ) ++len;
649                 char *plugin_dir = FileSystem::basepath(plugin_path);
650                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
651                 create_defaults_path(index_path, LADSPA_FILE);
652                 cp = index_path + strlen(index_path);
653                 for( char *bp=plugin_path; *bp!=0; ++bp )
654                         *cp++ = *bp=='/' ? '_' : *bp;
655                 *cp = 0;
656                 if( !load_plugin_index(mwindow, index_path, plugin_path) ) continue;
657                 if( init_ladspa_index(mwindow, preferences, index_path, plugin_path) ) continue;
658                 load_plugin_index(mwindow, index_path, plugin_path);
659         }
660         return 1;
661 }
662
663 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
664         FILE *fp, const char *plugin_dir)
665 {
666         int idx = PLUGIN_IDS;
667         if( plugindb ) {
668                 for( int i=0; i<plugindb->size(); ++i ) {
669                         PluginServer *server = plugindb->get(i);
670                         if( server->dir_idx >= idx )
671                                 idx = server->dir_idx+1;
672                 }
673         }
674         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
675 }
676
677 int MWindow::init_ladspa_index(MWindow *mwindow, Preferences *preferences,
678         const char *index_path, const char *plugin_dir)
679 {
680         char plugin_path[BCTEXTLEN], *path = FileSystem::basepath(plugin_dir);
681         strcpy(plugin_path, path);  delete [] path;
682         printf("init ladspa index: %s\n", plugin_dir);
683         FILE *fp = fopen(index_path,"w");
684         if( !fp ) {
685                 fprintf(stderr,_("MWindow::init_ladspa_index: "
686                         "can't create plugin index: %s\n"), index_path);
687                 return 1;
688         }
689         fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
690         fprintf(fp, "%s\n", plugin_dir);
691         init_plugin_index(mwindow, preferences, fp, plugin_path);
692         fclose(fp);
693         return 0;
694 }
695
696 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
697         const char *plug_dir, const char *plug_path, int &idx)
698 {
699         char plugin_path[BCTEXTLEN];
700         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
701         FileSystem fs;
702         fs.set_filter( "[*.plugin][*.so]" );
703         int result = fs.update(plugin_path);
704         if( result || !fs.dir_list.total ) return;
705         int vis_id = idx++;
706
707         for( int i=0; i<fs.dir_list.total; ++i ) {
708                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
709                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
710                 get_plugin_path(path, plug_dir, fs_path);
711                 if( fs.is_dir(fs_path) ) {
712                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
713                         continue;
714                 }
715                 if( plugin_exists(path) ) continue;
716                 struct stat st;
717                 if( stat(fs_path, &st) ) continue;
718                 int64_t mtime = st.st_mtime;
719                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
720                 result = server.open_plugin(1, preferences, 0, 0);
721                 if( !result ) {
722                         server.write_table(fp, path, vis_id, mtime);
723                         server.close_plugin();
724                 }
725                 else if( result == PLUGINSERVER_IS_LAD ) {
726                         int lad_index = 0;
727                         for(;;) {
728                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
729                                 ladspa.set_lad_index(lad_index++);
730                                 result = ladspa.open_plugin(1, preferences, 0, 0);
731                                 if( result ) break;
732                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
733                                 ladspa.close_plugin();
734                         }
735                 }
736         }
737 }
738
739 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
740 {
741         for( int i=0; i<plugins.size(); ++i )
742                 plugindb->append(plugins[i]);
743         plugins.remove_all();
744 }
745
746 void MWindow::init_plugin_tips(ArrayList<PluginServer*> &plugins, const char *lang)
747 {
748         const char *cfg_path = File::get_cindat_path();
749         char msg_path[BCTEXTLEN];
750         FILE *fp = 0;
751         if( BC_Resources::language[0] ) {
752                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.%s",
753                         cfg_path, lang);
754                 fp = fopen(msg_path, "r");
755         }
756         if( !fp ) {
757                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.txt",
758                         cfg_path);
759                 fp = fopen(msg_path, "r");
760         }
761         if( !fp ) return;
762         char text[BCTEXTLEN];
763         char *tp = text, *ep = tp + sizeof(text)-1;
764         char title[BCTEXTLEN];
765         title[0] = 0;
766         int no = 0;
767         for(;;) {
768                 ++no;  int done = 1;
769                 char line[BCTEXTLEN], *cp = line;
770                 if( fgets(line,sizeof(line)-1,fp) ) {
771                         if( *cp == '#' ) continue;
772                         done = *cp == ' ' || *cp == '\t' ? 0 : -1;
773                 }
774                 if( done ) {
775                         if( tp > text && *--tp == '\n' ) *tp = 0;
776                         if( title[0] ) {
777                                 int idx = plugins.size();
778                                 while( --idx>=0 && strcmp(plugins[idx]->title, title) );
779                                 if( idx >= 0 ) {
780                                         delete [] plugins[idx]->tip;
781                                         plugins[idx]->tip = cstrdup(text);
782                                 }
783                                 title[0] = 0;
784                         }
785                         if( done > 0 ) break;
786                         tp = text;  *tp = 0;
787                         char *dp = strchr(cp, ':');
788                         if( !dp ) {
789                                 printf("plugin tips: error on line %d\n", no);
790                                 continue;
791                         }
792                         char *bp = title;
793                         while( cp < dp ) *bp++ = *cp++;
794                         *bp = 0;
795                         ++cp;
796                 }
797
798                 while( *cp == ' ' || *cp == '\t' ) ++cp;
799                 for( ; tp<ep && (*tp=*cp)!=0; ++tp,++cp );
800         }
801         fclose(fp);
802 }
803
804 void MWindow::delete_plugins()
805 {
806         plugindb->remove_all_objects();
807         delete plugindb;
808         plugindb = 0;
809 }
810
811 void MWindow::search_plugindb(int do_audio,
812                 int do_video,
813                 int is_realtime,
814                 int is_transition,
815                 int is_theme,
816                 ArrayList<PluginServer*> &results)
817 {
818 // Get plugins
819         for(int i = 0; i < MWindow::plugindb->total; i++)
820         {
821                 PluginServer *current = MWindow::plugindb->get(i);
822
823                 if(current->audio == do_audio &&
824                         current->video == do_video &&
825                         (current->realtime == is_realtime || is_realtime < 0) &&
826                         current->transition == is_transition &&
827                         current->theme == is_theme)
828                         results.append(current);
829         }
830
831 // Alphabetize list by title
832         int done = 0;
833         while(!done)
834         {
835                 done = 1;
836
837                 for(int i = 0; i < results.total - 1; i++)
838                 {
839                         PluginServer *value1 = results[i];
840                         PluginServer *value2 = results[i + 1];
841                         if(strcmp(_(value1->title), _(value2->title)) > 0)
842                         {
843                                 done = 0;
844                                 results[i] = value2;
845                                 results[i + 1] = value1;
846                         }
847                 }
848         }
849 }
850
851 PluginServer* MWindow::scan_plugindb(char *title,
852                 int data_type)
853 {
854 //      if(data_type < 0)
855 //      {
856 //              printf("MWindow::scan_plugindb data_type < 0\n");
857 //              return 0;
858 //      }
859
860         for(int i = 0; i < plugindb->total; i++)
861         {
862                 PluginServer *server = plugindb->get(i);
863                 if(server->title &&
864                         !strcasecmp(server->title, title) &&
865                         (data_type < 0 ||
866                                 (data_type == TRACK_AUDIO && server->audio) ||
867                                 (data_type == TRACK_VIDEO && server->video)))
868                         return plugindb->get(i);
869         }
870         return 0;
871 }
872
873 // repair session files with xlated plugin titles
874 void MWindow::fix_plugin_title(char *title)
875 {
876         for(int i = 0; i < plugindb->total; i++) {
877                 PluginServer *server = plugindb->get(i);
878                 if( !server->title ) continue;
879                 const char *server_title = server->title;
880                 if( !bstrcasecmp(title, _(server_title)) ) {
881                         strcpy(title, server_title);
882                         return;
883                 }
884         }
885 }
886
887 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
888 {
889         for( int i=0; i<plugins.size(); ++i )
890                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
891         return 0;
892 }
893
894 int MWindow::plugin_exists(char *plugin_path)
895 {
896         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
897 }
898
899 void MWindow::init_preferences()
900 {
901         preferences = new Preferences;
902         preferences->load_defaults(defaults);
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         return theme->use_commercials;
1632 }
1633
1634 void MWindow::init_commercials()
1635 {
1636         if( !commercials ) {
1637                 commercials = new Commercials(this);
1638                 commercial_active = 0;
1639         }
1640         else
1641                 commercials->add_user();
1642 }
1643
1644 void MWindow::commit_commercial()
1645 {
1646         if( !commercial_active ) return;
1647         commercial_active = 0;
1648         if( !commercials ) return;
1649         commercials->commitDb();
1650 }
1651
1652 void MWindow::undo_commercial()
1653 {
1654         if( !commercial_active ) return;
1655         commercial_active = 0;
1656         if( !commercials ) return;
1657         commercials->undoDb();
1658 }
1659
1660 int MWindow::put_commercial()
1661 {
1662         double start = edl->local_session->get_selectionstart();
1663         double end = edl->local_session->get_selectionend();
1664         if( start >= end ) return 0;
1665
1666         const char *errmsg = 0;
1667         int count = 0;
1668         Tracks *tracks = edl->tracks;
1669         int result = 0;
1670         //check it
1671         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1672                 if( track->data_type != TRACK_VIDEO ) continue;
1673                 if( !track->record ) continue;
1674                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1675                 ++count;
1676                 int64_t units_start = track->to_units(start,0);
1677                 int64_t units_end = track->to_units(end,0);
1678                 Edits *edits = track->edits;
1679                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1680                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1681                 if(!edit1 && !edit2) continue;  // nothing selected
1682                 if(!edit2) {                    // edit2 beyond end of track
1683                         edit2 = edits->last;
1684                         units_end = edits->length();
1685                 }
1686                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1687                 Indexable *indexable = edit1->get_source();
1688                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1689         }
1690         //run it
1691         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1692                 if( track->data_type != TRACK_VIDEO ) continue;
1693                 if( !track->record ) continue;
1694                 int64_t units_start = track->to_units(start,0);
1695                 int64_t units_end = track->to_units(end,0);
1696                 Edits *edits = track->edits;
1697                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1698                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1699                 if(!edit1 && !edit2) continue;  // nothing selected
1700                 if(!edit2) {                    // edit2 beyond end of track
1701                         edit2 = edits->last;
1702                         units_end = edits->length();
1703                 }
1704                 Indexable *indexable = edit1->get_source();
1705                 Asset *asset = (Asset *)indexable;
1706                 File *file = video_cache->check_out(asset, edl);
1707                 if( !file ) { errmsg = _("no file"); break; }
1708                 int64_t edit_length = units_end - units_start;
1709                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1710                 result = commercials->put_clip(file, edit1->channel,
1711                         track->from_units(edit_start), track->from_units(edit_length));
1712                 video_cache->check_in(asset);
1713                 if( result ) { errmsg = _("db failed"); break; }
1714         }
1715         if( errmsg ) {
1716                 char string[BCTEXTLEN];
1717                 sprintf(string, _("put_commercial: %s"), errmsg);
1718                 MainError::show_error(string);
1719                 undo_commercial();
1720                 result = 1;
1721         }
1722         return result;
1723 }
1724
1725 void MWindow::stop_playback(int wait)
1726 {
1727         gui->stop_drawing();
1728
1729         cwindow->stop_playback(wait);
1730
1731         for(int i = 0; i < vwindows.size(); i++) {
1732                 VWindow *vwindow = vwindows[i];
1733                 if( !vwindow->is_running() ) continue;
1734                 vwindow->stop_playback(wait);
1735         }
1736         for(int i = 0; i < zwindows.size(); i++) {
1737                 ZWindow *zwindow = zwindows[i];
1738                 if( zwindow->idx < 0 ) continue;
1739                 zwindow->stop_playback(wait);
1740         }
1741 }
1742
1743 void MWindow::stop_transport()
1744 {
1745         gui->stop_transport(gui->get_window_lock() ? "MWindow::stop_transport" : 0);
1746 }
1747
1748 int MWindow::load_filenames(ArrayList<char*> *filenames,
1749         int load_mode,
1750         int update_filename)
1751 {
1752         ArrayList<EDL*> new_edls;
1753         ArrayList<Asset*> new_assets;
1754         ArrayList<File*> new_files;
1755         const int debug = 0;
1756 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1757
1758 //      save_defaults();
1759         gui->start_hourglass();
1760
1761 // Need to stop playback since tracking depends on the EDL not getting
1762 // deleted.
1763         gui->unlock_window();
1764         stop_playback(1);
1765         gui->lock_window("MWindow::load_filenames 0");
1766
1767 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1768         undo->update_undo_before();
1769
1770
1771 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1772
1773 // Define new_edls and new_assets to load
1774         int result = 0, ftype = -1;
1775
1776         for( int i=0; i<filenames->size(); ++i ) {
1777 // Get type of file
1778                 File *new_file = new File;
1779                 Asset *new_asset = new Asset(filenames->get(i));
1780                 EDL *new_edl = new EDL;
1781                 char string[BCTEXTLEN];
1782
1783                 new_edl->create_objects();
1784                 new_edl->copy_session(edl);
1785                 new_file->set_program(edl->session->program_no);
1786
1787                 sprintf(string, _("Loading %s"), new_asset->path);
1788                 gui->show_message(string);
1789 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1790
1791                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1792 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1793
1794                 result = 1;
1795                 switch( ftype ) {
1796 // Convert media file to EDL
1797                 case FILE_OK:
1798 // Warn about odd image dimensions
1799                         if( new_asset->video_data &&
1800                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
1801                                 char string[BCTEXTLEN];
1802                                 sprintf(string, _("%s's resolution is %dx%d.\nImages with odd dimensions may not decode properly."),
1803                                         new_asset->path, new_asset->width, new_asset->height);
1804                                 MainError::show_error(string);
1805                         }
1806
1807                         if( new_asset->program >= 0 &&
1808                             edl->session->program_no != new_asset->program ) {
1809                                 char string[BCTEXTLEN];
1810                                 sprintf(string, _("%s's index was built for program number %d\n"
1811                                         "Playback preference is %d.\n  Using program %d."),
1812                                         new_asset->path, new_asset->program,
1813                                         edl->session->program_no, new_asset->program);
1814                                 MainError::show_error(string);
1815                         }
1816
1817                         if( load_mode != LOADMODE_RESOURCESONLY ) {
1818                                 RecordLabels *labels = edl->session->label_cells ?
1819                                         new RecordLabels(new_file) : 0;
1820                                 asset_to_edl(new_edl, new_asset, labels);
1821                                 new_edls.append(new_edl);
1822                                 new_edl->add_user();
1823                                 delete labels;
1824                         }
1825                         else {
1826                                 new_assets.append(new_asset);
1827                                 new_asset->add_user();
1828                         }
1829
1830 // Set filename to nothing for assets since save EDL would overwrite them.
1831                         if( load_mode == LOADMODE_REPLACE ||
1832                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
1833                                 set_filename("");
1834 // Reset timeline position
1835                                 for( int i=0; i<TOTAL_PANES; ++i ) {
1836                                         new_edl->local_session->view_start[i] = 0;
1837                                         new_edl->local_session->track_start[i] = 0;
1838                                 }
1839                         }
1840
1841                         result = 0;
1842                         break;
1843
1844 // File not found
1845                 case FILE_NOT_FOUND:
1846                         sprintf(string, _("Failed to open %s"), new_asset->path);
1847                         gui->show_message(string, theme->message_error);
1848                         gui->update_default_message();
1849                         break;
1850
1851 // Unknown format
1852                 case FILE_UNRECOGNIZED_CODEC: {
1853 // Test index file
1854                         { IndexFile indexfile(this, new_asset);
1855                         if( !(result = indexfile.open_index()) )
1856                                 indexfile.close_index(); }
1857
1858 // Test existing EDLs
1859                         for( int j=0; result && j<new_edls.total; ++j ) {
1860                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
1861                                 if( old_asset ) {
1862                                         new_asset->copy_from(old_asset,1);
1863                                         result = 0;
1864                                 }
1865                         }
1866                         if( result ) {
1867                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
1868                                 if( old_asset ) {
1869                                         new_asset->copy_from(old_asset,1);
1870                                         result = 0;
1871                                 }
1872                         }
1873
1874 // Prompt user
1875                         if( result ) {
1876                                 char string[BCTEXTLEN];
1877                                 FileSystem fs;
1878                                 fs.extract_name(string, new_asset->path);
1879
1880                                 strcat(string, _("'s format couldn't be determined."));
1881                                 new_asset->audio_data = 1;
1882                                 new_asset->format = FILE_PCM;
1883                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
1884                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
1885                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
1886                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
1887                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
1888                                 new_asset->header = defaults->get("HEADER", 0);
1889
1890                                 FileFormat fwindow(this);
1891                                 fwindow.create_objects(new_asset, string);
1892                                 result = fwindow.run_window();
1893
1894                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
1895                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
1896                                 defaults->update("AUDIO_BITS", new_asset->bits);
1897                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
1898                                 defaults->update("SIGNED_", new_asset->signed_);
1899                                 defaults->update("HEADER", new_asset->header);
1900                                 save_defaults();
1901                         }
1902
1903 // Append to list
1904                         if( !result ) {
1905 // Recalculate length
1906                                 delete new_file;
1907                                 new_file = new File;
1908                                 result = new_file->open_file(preferences, new_asset, 1, 0);
1909
1910                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
1911                                         RecordLabels *labels = edl->session->label_cells ?
1912                                                 new RecordLabels(new_file) : 0;
1913                                         asset_to_edl(new_edl, new_asset, labels);
1914                                         new_edls.append(new_edl);
1915                                         new_edl->add_user();
1916                                         delete labels;
1917                                 }
1918                                 else {
1919                                         new_assets.append(new_asset);
1920                                         new_asset->add_user();
1921                                 }
1922                         }
1923                         else {
1924                                 result = 1;
1925                         }
1926                         break; }
1927
1928                 case FILE_IS_XML: {
1929                         FileXML xml_file;
1930 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1931                         xml_file.read_from_file(filenames->get(i));
1932 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1933                         const char *cin_version = 0;
1934                         while( !xml_file.read_tag() ) {
1935                                 if( xml_file.tag.title_is("EDL") ) {
1936                                         cin_version = xml_file.tag.get_property("VERSION");
1937                                         break;
1938                                 }
1939                         }
1940                         xml_file.rewind();
1941                         if( !cin_version ) {
1942                                 eprintf(_("XML file %s\n not from cinelerra."),filenames->get(i));
1943                                 char string[BCTEXTLEN];
1944                                 sprintf(string,_("Unknown %s"), filenames->get(i));
1945                                 gui->show_message(string);
1946                                 result = 1;
1947                                 break;
1948                         }
1949                         if( strcmp(cin_version, CINELERRA_VERSION) ) {
1950                                 char string[BCTEXTLEN];
1951                                 snprintf(string, sizeof(string),
1952                                          _("Warning: XML from cinelerra version %s\n"
1953                                         "Session data may be incompatible."), cin_version);
1954                                 show_warning(&preferences->warn_version, string);
1955                         }
1956                         if( load_mode == LOADMODE_NESTED ) {
1957 // Load temporary EDL for nesting.
1958                                 EDL *nested_edl = new EDL;
1959                                 nested_edl->create_objects();
1960                                 nested_edl->load_xml(&xml_file, LOAD_ALL);
1961 //printf("MWindow::load_filenames %p %s\n", nested_edl, nested_edl->project_path);
1962                                 new_edl->create_nested(nested_edl);
1963                                 new_edl->set_path(filenames->get(i));
1964                                 nested_edl->Garbage::remove_user();
1965                         }
1966                         else {
1967 // Load EDL for pasting
1968                                 new_edl->load_xml(&xml_file, LOAD_ALL);
1969 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1970                                 test_plugins(new_edl, filenames->get(i));
1971 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1972
1973                                 if( load_mode == LOADMODE_REPLACE ||
1974                                     load_mode == LOADMODE_REPLACE_CONCATENATE ) {
1975                                         strcpy(session->filename, filenames->get(i));
1976                                         strcpy(new_edl->local_session->clip_title,
1977                                                 filenames->get(i));
1978                                         if(update_filename)
1979                                                 set_filename(new_edl->local_session->clip_title);
1980                                 }
1981                                 else if( load_mode == LOADMODE_RESOURCESONLY ) {
1982                                         strcpy(new_edl->local_session->clip_title,
1983                                                 filenames->get(i));
1984                                         struct stat st;
1985                                         time_t t = !stat(filenames->get(i),&st) ?
1986                                                 st.st_mtime : time(&t);
1987                                         ctime_r(&t, new_edl->local_session->clip_notes);
1988                                 }
1989                         }
1990
1991                         new_edls.append(new_edl);
1992                         new_edl->add_user();
1993                         result = 0;
1994                         break; }
1995                 }
1996
1997                 new_edl->Garbage::remove_user();
1998                 new_asset->Garbage::remove_user();
1999
2000 // Store for testing index
2001                 new_files.append(new_file);
2002         }
2003
2004 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2005
2006
2007         if(!result) {
2008                 gui->reset_default_message();
2009                 gui->default_message();
2010         }
2011
2012
2013 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2014
2015 // Paste them.
2016 // Don't back up here.
2017         if(new_edls.size())
2018         {
2019 // For pasting, clear the active region
2020                 if(load_mode == LOADMODE_PASTE ||
2021                         load_mode == LOADMODE_NESTED)
2022                 {
2023                         double start = edl->local_session->get_selectionstart();
2024                         double end = edl->local_session->get_selectionend();
2025                         if(!EQUIV(start, end))
2026                                 edl->clear(start,
2027                                         end,
2028                                         edl->session->labels_follow_edits,
2029                                         edl->session->plugins_follow_edits,
2030                                         edl->session->autos_follow_edits);
2031                 }
2032
2033                 paste_edls(&new_edls, load_mode, 0, -1,
2034                         edl->session->labels_follow_edits,
2035                         edl->session->plugins_follow_edits,
2036                         edl->session->autos_follow_edits,
2037                         0); // overwrite
2038         }
2039
2040
2041
2042
2043 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2044
2045 // Add new assets to EDL and schedule assets for index building.
2046         int got_indexes = 0;
2047         for( int i=0; i<new_edls.size(); ++i ) {
2048                 EDL *new_edl = new_edls[i];
2049                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2050                         mainindexes->add_next_asset(0, new_edl->nested_edls[j]);
2051                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2052                         got_indexes = 1;
2053                 }
2054
2055         }
2056
2057 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2058         for( int i=0; i<new_assets.size(); ++i ) {
2059                 Asset *new_asset = new_assets[i];
2060
2061                 File *new_file = 0;
2062                 int got_it = 0;
2063                 for( int j=0; j<new_files.size(); ++j ) {
2064                         new_file = new_files[j];
2065                         if( !strcmp(new_file->asset->path, new_asset->path) ) {
2066                                 got_it = 1;
2067                                 break;
2068                         }
2069                 }
2070
2071                 mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
2072                 edl->assets->update(new_asset);
2073                 got_indexes = 1;
2074         }
2075 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2076
2077 // Start examining next batch of index files
2078         if(got_indexes) mainindexes->start_build();
2079 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2080
2081 // Open plugin GUIs
2082         Track *track = edl->tracks->first;
2083         while(track)
2084         {
2085                 for(int j = 0; j < track->plugin_set.size(); j++)
2086                 {
2087                         PluginSet *plugins = track->plugin_set[j];
2088                         Plugin *plugin = plugins->get_first_plugin();
2089
2090                         while(plugin)
2091                         {
2092                                 if(load_mode == LOADMODE_REPLACE ||
2093                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
2094                                 {
2095                                         if(plugin->plugin_type == PLUGIN_STANDALONE &&
2096                                                 plugin->show)
2097                                         {
2098                                                 show_plugin(plugin);
2099                                         }
2100                                 }
2101
2102                                 plugin = (Plugin*)plugin->next;
2103                         }
2104                 }
2105
2106                 track = track->next;
2107         }
2108
2109         // if just opening one new resource in replace mode
2110         if( ftype != FILE_IS_XML &&
2111             ( load_mode == LOADMODE_REPLACE ||
2112               load_mode == LOADMODE_REPLACE_CONCATENATE ) ) {
2113                 select_asset(0, 0);
2114                 edl->session->proxy_scale = 1;
2115                 edl->session->proxy_use_scaler = 0;
2116                 edl->session->proxy_auto_scale = 0;
2117                 edl->local_session->preview_start = 0;
2118                 edl->local_session->preview_end = 0;
2119                 edl->local_session->loop_playback = 0;
2120                 edl->local_session->set_selectionstart(0);
2121                 edl->local_session->set_selectionend(0);
2122                 set_brender_active(0, 0);
2123                 fit_selection();
2124                 goto_start();
2125         }
2126
2127         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
2128             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
2129                 ArrayList<Indexable *> orig_idxbls;
2130                 for( int i=0; i<new_assets.size(); ++i )
2131                         orig_idxbls.append(new_assets.get(i));
2132                 for( int i=0; i<new_edls.size(); ++i ) {
2133                         EDL *new_edl = new_edls[i];
2134                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2135                                 if( track->data_type != TRACK_VIDEO ) continue;
2136                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2137                                         Indexable *idxbl = (Indexable *)edit->asset;
2138                                         if( !idxbl ) continue;
2139                                         if( !idxbl->have_video() ) continue;
2140                                         if( edit->channel != 0 ) continue; // first layer only
2141                                         orig_idxbls.append(edit->asset);
2142                                 }
2143                         }
2144                 }
2145                 gui->unlock_window(); // to update progress bar
2146                 render_proxy(orig_idxbls);
2147                 gui->lock_window("MWindow::load_filenames");
2148         }
2149
2150 // need to update undo before project, since mwindow is unlocked & a new load
2151 // can begin here.  Should really prevent loading until we're done.
2152 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2153         undo->update_undo_after(_("load"), LOAD_ALL);
2154
2155         for(int i = 0; i < new_edls.size(); i++)
2156         {
2157                 new_edls[i]->remove_user();
2158         }
2159 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2160
2161         new_edls.remove_all();
2162
2163         for(int i = 0; i < new_assets.size(); i++)
2164         {
2165                 new_assets[i]->Garbage::remove_user();
2166         }
2167
2168         new_assets.remove_all();
2169         new_files.remove_all_objects();
2170
2171
2172 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2173         if(load_mode == LOADMODE_REPLACE ||
2174                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2175         {
2176                 session->changes_made = 0;
2177         }
2178         else
2179         {
2180                 session->changes_made = 1;
2181         }
2182
2183         gui->stop_hourglass();
2184
2185
2186 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2187         update_project(load_mode);
2188
2189 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2190
2191         return 0;
2192 }
2193
2194 void MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2195 {
2196         Asset *format_asset = new Asset;
2197         format_asset->format = FILE_FFMPEG;
2198         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2199         ProxyRender proxy_render(this, format_asset);
2200         int new_scale = edl->session->proxy_scale;
2201         int use_scaler = edl->session->proxy_use_scaler;
2202
2203         for( int i=0; i<new_idxbls.size(); ++i ) {
2204                 Indexable *orig = new_idxbls.get(i);
2205                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2206                 if( !proxy ) continue;
2207                 FileSystem fs;
2208                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2209                 int got_it = exists && // if proxy exists, and is newer than orig
2210                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2211                 if( got_it ) continue;
2212                 proxy_render.add_needed(orig, proxy);
2213         }
2214
2215 // render needed proxies
2216         int result = proxy_render.create_needed_proxies(new_scale);
2217         if( !result ) {
2218                 add_proxy(use_scaler,
2219                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2220         }
2221         format_asset->remove_user();
2222 }
2223
2224 void MWindow::test_plugins(EDL *new_edl, char *path)
2225 {
2226         char string[BCTEXTLEN];
2227
2228 // Do a check whether plugins exist
2229         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2230                 for( int k=0; k<track->plugin_set.total; ++k ) {
2231                         PluginSet *plugin_set = track->plugin_set[k];
2232                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2233                                         plugin; plugin = (Plugin*)plugin->next ) {
2234                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2235 // ok we need to find it in plugindb
2236                                 PluginServer *server =
2237                                         scan_plugindb(plugin->title, track->data_type);
2238                                 if( !server || server->transition ) {
2239                                         sprintf(string,
2240         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2241           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2242                                                 "effect", _(plugin->title), path);
2243                                         MainError::show_error(string);
2244                                 }
2245                         }
2246                 }
2247
2248                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2249                         if( !edit->transition ) continue;
2250 // ok we need to find transition in plugindb
2251                         PluginServer *server =
2252                                 scan_plugindb(edit->transition->title, track->data_type);
2253                         if( !server || !server->transition ) {
2254                                 sprintf(string,
2255         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2256           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2257                                         "transition", _(edit->transition->title), path);
2258                                 MainError::show_error(string);
2259                         }
2260                 }
2261         }
2262 }
2263
2264
2265 void MWindow::init_shm()
2266 {
2267 // Fix shared memory
2268         FILE *fd = fopen("/proc/sys/kernel/shmmax", "w");
2269         if(fd) {
2270                 fprintf(fd, "0x7fffffff");
2271                 fclose(fd);
2272         }
2273         fd = 0;
2274
2275         fd = fopen("/proc/sys/kernel/shmmax", "r");
2276         if(!fd) {
2277                 MainError::show_error("MWindow::init_shm: couldn't open /proc/sys/kernel/shmmax for reading.\n");
2278                 return;
2279         }
2280
2281         int64_t result = 0;
2282         fscanf(fd, "%jd", &result);
2283         fclose(fd);
2284         fd = 0;
2285         if(result < 0x7fffffff) {
2286                 eprintf(_("MWindow::init_shm: /proc/sys/kernel/shmmax is %p.\n"
2287                         "you probably need to be root, or:\n"
2288                         "as root, run: echo 0x7fffffff > /proc/sys/kernel/shmmax\n"
2289                         "before trying to start cinelerra.\n"
2290                         "It should be at least 0x7fffffff for Cinelerra.\n"), (void *)result);
2291         }
2292 }
2293
2294 void MWindow::create_objects(int want_gui,
2295         int want_new,
2296         char *config_path)
2297 {
2298         const int debug = 0;
2299         if(debug) PRINT_TRACE
2300
2301 // For some reason, init_signals must come after show_splash or the signals won't
2302 // get trapped.
2303         init_signals();
2304         if(debug) PRINT_TRACE
2305         init_3d();
2306
2307         if(debug) PRINT_TRACE
2308         show_splash();
2309
2310         if(debug) PRINT_TRACE
2311         default_standard = default_std();
2312         init_defaults(defaults, config_path);
2313         check_language();
2314         init_preferences();
2315         if(splash_window)
2316                 splash_window->operation->update(_("Initializing Plugins"));
2317         init_plugins(this, preferences);
2318         if(debug) PRINT_TRACE
2319         init_ladspa_plugins(this, preferences);
2320         if(debug) PRINT_TRACE
2321         init_plugin_tips(*plugindb, cin_lang);
2322         if(splash_window)
2323                 splash_window->operation->update(_("Initializing GUI"));
2324         if(debug) PRINT_TRACE
2325         init_theme();
2326
2327         if(debug) PRINT_TRACE
2328         init_error();
2329
2330         if(splash_window)
2331                 splash_window->operation->update(_("Initializing Fonts"));
2332         char string[BCTEXTLEN];
2333         strcpy(string, preferences->plugin_dir);
2334         strcat(string, "/" FONT_SEARCHPATH);
2335         BC_Resources::init_fontconfig(string);
2336         if(debug) PRINT_TRACE
2337
2338 // Initialize before too much else is running
2339 // Preferences & theme are required for building MPEG table of contents
2340
2341 // Default project created here
2342         init_edl();
2343         if(debug) PRINT_TRACE
2344
2345         init_cache();
2346         if(debug) PRINT_TRACE
2347
2348         Timer timer;
2349
2350         init_awindow();
2351         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2352
2353         init_compositor();
2354         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2355
2356 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2357         if(session->show_vwindow)
2358                 get_viewer(1, DEFAULT_VWINDOW);
2359         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2360
2361         init_gui();
2362         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2363
2364         init_levelwindow();
2365         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2366
2367         init_indexes();
2368         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2369
2370         init_channeldb();
2371         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2372
2373         init_gwindow();
2374         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2375
2376         init_render();
2377         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2378
2379         init_brender();
2380         init_exportedl();
2381         init_commercials();
2382         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2383         mainprogress = new MainProgress(this, gui);
2384         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2385         undo = new MainUndo(this);
2386
2387         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2388
2389         plugin_guis = new ArrayList<PluginServer*>;
2390         dead_plugins = new ArrayList<PluginServer*>;
2391         keyframe_threads = new ArrayList<KeyFrameThread*>;
2392
2393         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2394                 __LINE__,
2395                 vwindows.size(),
2396                 session->show_vwindow);
2397
2398 // Show all vwindows
2399 //      if(session->show_vwindow) {
2400 //              for(int j = 0; j < vwindows.size(); j++) {
2401 //                      VWindow *vwindow = vwindows[j];
2402 //                      if( !vwindow->is_running() ) continue;
2403 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2404 //                              __LINE__,
2405 //                              vwindow);
2406 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2407 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2408 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2409 //                      vwindow->gui->show_window();
2410 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2411 //                      vwindow->gui->unlock_window();
2412 //              }
2413 //      }
2414
2415
2416         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2417
2418         if(session->show_cwindow)
2419         {
2420                 cwindow->gui->lock_window("MWindow::create_objects 1");
2421                 cwindow->gui->show_window();
2422                 cwindow->gui->unlock_window();
2423         }
2424
2425         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2426         if(session->show_awindow)
2427         {
2428                 awindow->gui->lock_window("MWindow::create_objects 1");
2429                 awindow->gui->show_window();
2430                 awindow->gui->unlock_window();
2431         }
2432
2433         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2434         if(session->show_lwindow)
2435         {
2436                 lwindow->gui->lock_window("MWindow::create_objects 1");
2437                 lwindow->gui->show_window();
2438                 lwindow->gui->unlock_window();
2439         }
2440
2441         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2442                 __LINE__,
2443                 (int)timer.get_difference(),
2444                 gwindow->gui);
2445         if(session->show_gwindow)
2446         {
2447                 gwindow->gui->lock_window("MWindow::create_objects 1");
2448                 gwindow->gui->show_window();
2449                 gwindow->gui->unlock_window();
2450         }
2451
2452         if(debug) PRINT_TRACE
2453
2454         gui->lock_window("MWindow::create_objects 1");
2455         gui->mainmenu->load_defaults(defaults);
2456         gui->mainmenu->update_toggles(0);
2457         gui->update_patchbay();
2458         gui->draw_canvas(0, 0);
2459         gui->draw_cursor(1);
2460         gui->show_window();
2461         gui->raise_window();
2462         gui->unlock_window();
2463
2464         if(debug) PRINT_TRACE
2465
2466         if(preferences->use_tipwindow)
2467                 init_tipwindow();
2468         if(debug) PRINT_TRACE
2469
2470         gui->add_keyboard_listener(
2471                 (int (BC_WindowBase::*)(BC_WindowBase *))
2472                 &MWindowGUI::keyboard_listener);
2473
2474         hide_splash();
2475         init_shm();
2476         if(debug) PRINT_TRACE
2477
2478         BC_WindowBase::get_resources()->vframe_shm = 1;
2479 }
2480
2481
2482 void MWindow::show_splash()
2483 {
2484 #include "data/heroine_logo9_png.h"
2485         VFrame *frame = new VFramePng(heroine_logo9_png);
2486         BC_DisplayInfo dpyi;
2487         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2488         int rr = (rw < rh ? rw : rh) / 4;
2489         splash_window = new SplashGUI(frame, rr, rr);
2490         splash_window->create_objects();
2491 }
2492
2493 void MWindow::hide_splash()
2494 {
2495         if(splash_window)
2496                 delete splash_window;
2497         splash_window = 0;
2498 }
2499
2500
2501 void MWindow::start()
2502 {
2503 ENABLE_BUFFER
2504 //PRINT_TRACE
2505 //      vwindows[DEFAULT_VWINDOW]->start();
2506         awindow->start();
2507 //PRINT_TRACE
2508         cwindow->start();
2509 //PRINT_TRACE
2510         lwindow->start();
2511 //PRINT_TRACE
2512         gwindow->start();
2513 //PRINT_TRACE
2514 //      Thread::start();
2515 //PRINT_TRACE
2516         playback_3d->start();
2517 //PRINT_TRACE
2518 }
2519
2520 void MWindow::run()
2521 {
2522         run_lock->lock("MWindow::run");
2523         gui->run_window();
2524         stop_playback(1);
2525
2526         brender_lock->lock("MWindow::run 1");
2527         delete brender;         brender = 0;
2528         brender_lock->unlock();
2529
2530         interrupt_indexes();
2531         clean_indexes();
2532         save_defaults();
2533         run_lock->unlock();
2534 }
2535
2536 void MWindow::show_vwindow()
2537 {
2538         int total_running = 0;
2539         session->show_vwindow = 1;
2540
2541 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2542 // Raise all windows which are visible
2543         for(int j = 0; j < vwindows.size(); j++) {
2544                 VWindow *vwindow = vwindows[j];
2545                 if( !vwindow->is_running() ) continue;
2546                 vwindow->gui->lock_window("MWindow::show_vwindow");
2547                 vwindow->gui->show_window(0);
2548                 vwindow->gui->raise_window();
2549                 vwindow->gui->flush();
2550                 vwindow->gui->unlock_window();
2551                 total_running++;
2552         }
2553
2554 // If no windows visible
2555         if(!total_running)
2556         {
2557                 get_viewer(1, DEFAULT_VWINDOW);
2558         }
2559
2560         gui->mainmenu->show_vwindow->set_checked(1);
2561 }
2562
2563 void MWindow::show_awindow()
2564 {
2565         session->show_awindow = 1;
2566         awindow->gui->lock_window("MWindow::show_awindow");
2567         awindow->gui->show_window();
2568         awindow->gui->raise_window();
2569         awindow->gui->flush();
2570         awindow->gui->unlock_window();
2571         gui->mainmenu->show_awindow->set_checked(1);
2572 }
2573
2574 char *MWindow::get_cwindow_display()
2575 {
2576         char *x11_host = screens < 2 || session->window_config == 0 ?
2577                 session->a_x11_host : session->b_x11_host;
2578         return *x11_host ? x11_host : 0;
2579 }
2580
2581 void MWindow::show_cwindow()
2582 {
2583         session->show_cwindow = 1;
2584         cwindow->show_window();
2585         gui->mainmenu->show_cwindow->set_checked(1);
2586 }
2587
2588 void MWindow::show_gwindow()
2589 {
2590         session->show_gwindow = 1;
2591
2592         gwindow->gui->lock_window("MWindow::show_gwindow");
2593         gwindow->gui->show_window();
2594         gwindow->gui->raise_window();
2595         gwindow->gui->flush();
2596         gwindow->gui->unlock_window();
2597
2598         gui->mainmenu->show_gwindow->set_checked(1);
2599 }
2600 void MWindow::hide_gwindow()
2601 {
2602         session->show_gwindow = 0;
2603
2604         gwindow->gui->lock_window("MWindow::show_gwindow");
2605         gwindow->gui->hide_window();
2606         gwindow->gui->unlock_window();
2607 }
2608
2609 void MWindow::show_lwindow()
2610 {
2611         session->show_lwindow = 1;
2612         lwindow->gui->lock_window("MWindow::show_lwindow");
2613         lwindow->gui->show_window();
2614         lwindow->gui->raise_window();
2615         lwindow->gui->flush();
2616         lwindow->gui->unlock_window();
2617         gui->mainmenu->show_lwindow->set_checked(1);
2618 }
2619
2620 int MWindow::tile_windows(int window_config)
2621 {
2622         int need_reload = 0;
2623         int play_config = window_config==0 ? 0 : 1;
2624         edl->session->playback_config->load_defaults(defaults, play_config);
2625         session->default_window_positions(window_config);
2626         if( screens == 1 ) {
2627                 gui->default_positions();
2628                 sync_parameters(CHANGE_ALL);
2629         }
2630         else
2631                 need_reload = 1;
2632         return need_reload;
2633 }
2634
2635 void MWindow::toggle_loop_playback()
2636 {
2637         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2638         set_loop_boundaries();
2639         save_backup();
2640
2641         gui->draw_overlays(1);
2642         sync_parameters(CHANGE_PARAMS);
2643 }
2644
2645 //void MWindow::set_titles(int value)
2646 //{
2647 //      edl->session->show_titles = value;
2648 //      trackmovement(edl->local_session->track_start);
2649 //}
2650
2651 void MWindow::set_screens(int value)
2652 {
2653         screens = value;
2654 }
2655
2656 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2657 {
2658         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2659         edl->session->auto_keyframes = value;
2660         gui->mbuttons->edit_panel->keyframe->update(value);
2661         gui->flush();
2662         if(lock_mwindow) gui->unlock_window();
2663
2664         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2665         cwindow->gui->edit_panel->keyframe->update(value);
2666         cwindow->gui->flush();
2667         if(lock_cwindow) cwindow->gui->unlock_window();
2668 }
2669
2670 void MWindow::set_auto_visibility(Autos *autos, int value)
2671 {
2672         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2673                 edl->session->auto_conf->plugins = value;
2674         else if( autos->autoidx >= 0 )
2675                 edl->session->auto_conf->autos[autos->autoidx] = value;
2676         else
2677                 return;
2678
2679         gui->update(0, 1, 0, 0, 0, 0, 0);
2680         gui->mainmenu->update_toggles(1);
2681         gui->unlock_window();
2682         gwindow->gui->update_toggles(1);
2683         gui->lock_window("MWindow::set_auto_visibility");
2684 }
2685
2686 void MWindow::set_keyframe_type(int mode)
2687 {
2688         gui->lock_window("MWindow::set_keyframe_type");
2689         edl->local_session->floatauto_type = mode;
2690         gui->mainmenu->update_toggles(0);
2691         gui->unlock_window();
2692 }
2693
2694 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
2695 {
2696         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
2697         edl->session->editing_mode = new_editing_mode;
2698         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
2699         gui->mbuttons->edit_panel->update();
2700         gui->set_editing_mode(1);
2701         if(lock_mwindow) gui->unlock_window();
2702
2703
2704         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
2705         cwindow->gui->edit_panel->update();
2706         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
2707         if(lock_cwindow) cwindow->gui->unlock_window();
2708         return 0;
2709 }
2710
2711 void MWindow::toggle_editing_mode()
2712 {
2713         int mode = edl->session->editing_mode;
2714         if( mode == EDITING_ARROW )
2715                 set_editing_mode(EDITING_IBEAM, 0, 1);
2716         else
2717                 set_editing_mode(EDITING_ARROW, 0, 1);
2718 }
2719
2720
2721 void MWindow::set_labels_follow_edits(int value)
2722 {
2723         gui->lock_window("MWindow::set_labels_follow_edits");
2724         edl->session->labels_follow_edits = value;
2725         gui->mbuttons->edit_panel->locklabels->update(value);
2726         gui->mainmenu->labels_follow_edits->set_checked(value);
2727         gui->flush();
2728         gui->unlock_window();
2729 }
2730
2731 void MWindow::sync_parameters(int change_type)
2732 {
2733         if( in_destructor ) return;
2734
2735 // Sync engines which are playing back
2736         if(cwindow->playback_engine->is_playing_back)
2737         {
2738                 if(change_type == CHANGE_PARAMS)
2739                 {
2740 // TODO: block keyframes until synchronization is done
2741                         cwindow->playback_engine->sync_parameters(edl);
2742                 }
2743                 else
2744 // Stop and restart
2745                 {
2746                         int command = cwindow->playback_engine->command->command;
2747                         cwindow->playback_engine->que->send_command(STOP,
2748                                 CHANGE_NONE,
2749                                 0,
2750                                 0);
2751 // Waiting for tracking to finish would make the restart position more
2752 // accurate but it can't lock the window to stop tracking for some reason.
2753 // Not waiting for tracking gives a faster response but restart position is
2754 // only as accurate as the last tracking update.
2755                         cwindow->playback_engine->interrupt_playback(0);
2756                         cwindow->playback_engine->que->send_command(command,
2757                                         change_type,
2758                                         edl,
2759                                         1,
2760                                         0);
2761                 }
2762         }
2763         else
2764         {
2765                 cwindow->refresh_frame(change_type);
2766         }
2767 }
2768
2769 void MWindow::age_caches()
2770 {
2771 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
2772 // __LINE__,
2773 // preferences->cache_size,
2774 // audio_cache->get_memory_usage(1),
2775 // video_cache->get_memory_usage(1),
2776 // frame_cache->get_memory_usage(),
2777 // wave_cache->get_memory_usage(),
2778 // memory_usage);
2779         frame_cache->age_cache(512);
2780         wave_cache->age_cache(8192);
2781
2782         int64_t memory_usage;
2783         int64_t prev_memory_usage = 0;
2784         int result = 0;
2785         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
2786         while( !result && prev_memory_usage !=
2787                 (memory_usage=video_cache->get_memory_usage(1)) &&
2788                 memory_usage > video_size ) {
2789                 video_cache->delete_oldest();
2790                 prev_memory_usage = memory_usage;
2791         }
2792
2793         prev_memory_usage = 0;
2794         result = 0;
2795         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
2796         while( !result && prev_memory_usage !=
2797                 (memory_usage=audio_cache->get_memory_usage(1)) &&
2798                 memory_usage > audio_size ) {
2799                 audio_cache->delete_oldest();
2800                 prev_memory_usage = memory_usage;
2801         }
2802 }
2803
2804 void MWindow::reset_android_remote()
2805 {
2806         gui->use_android_remote(preferences->android_remote);
2807 }
2808
2809
2810 void MWindow::show_keyframe_gui(Plugin *plugin)
2811 {
2812         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
2813 // Find existing thread
2814         for(int i = 0; i < keyframe_threads->size(); i++)
2815         {
2816                 if(keyframe_threads->get(i)->plugin == plugin)
2817                 {
2818                         keyframe_threads->get(i)->start_window(plugin, 0);
2819                         keyframe_gui_lock->unlock();
2820                         return;
2821                 }
2822         }
2823
2824 // Find unused thread
2825         for(int i = 0; i < keyframe_threads->size(); i++)
2826         {
2827                 if(!keyframe_threads->get(i)->plugin)
2828                 {
2829                         keyframe_threads->get(i)->start_window(plugin, 0);
2830                         keyframe_gui_lock->unlock();
2831                         return;
2832                 }
2833         }
2834
2835 // Create new thread
2836         KeyFrameThread *thread = new KeyFrameThread(this);
2837         keyframe_threads->append(thread);
2838         thread->start_window(plugin, 0);
2839
2840         keyframe_gui_lock->unlock();
2841 }
2842
2843
2844
2845
2846
2847 void MWindow::show_plugin(Plugin *plugin)
2848 {
2849         int done = 0;
2850
2851 SET_TRACE
2852 // Remove previously deleted plugin GUIs
2853         dead_plugin_lock->lock("MWindow::show_plugin");
2854         dead_plugins->remove_all_objects();
2855         dead_plugin_lock->unlock();
2856
2857 //printf("MWindow::show_plugin %d\n", __LINE__);
2858 SET_TRACE
2859
2860
2861         plugin_gui_lock->lock("MWindow::show_plugin");
2862         for(int i = 0; i < plugin_guis->total; i++)
2863         {
2864 // Pointer comparison
2865                 if(plugin_guis->get(i)->plugin == plugin)
2866                 {
2867                         plugin_guis->get(i)->raise_window();
2868                         done = 1;
2869                         break;
2870                 }
2871         }
2872 SET_TRACE
2873
2874 //printf("MWindow::show_plugin 1\n");
2875         if( !done && !plugin->track ) {
2876                 printf("MWindow::show_plugin track not defined.\n");
2877                 done = 1;
2878         }
2879         if( !done ) {
2880                 PluginServer *server = scan_plugindb(plugin->title,
2881                         plugin->track->data_type);
2882
2883 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
2884                 if(server && server->uses_gui)
2885                 {
2886                         PluginServer *gui = new PluginServer(*server);
2887                         plugin_guis->append(gui);
2888 // Needs mwindow to do GUI
2889                         gui->set_mwindow(this);
2890                         gui->open_plugin(0, preferences, edl, plugin);
2891                         plugin->show = 1;
2892                         gui->show_gui();
2893                 }
2894         }
2895         plugin_gui_lock->unlock();
2896 //printf("MWindow::show_plugin %d\n", __LINE__);
2897 SET_TRACE
2898 //sleep(1);
2899 //printf("MWindow::show_plugin 2\n");
2900 }
2901
2902 void MWindow::hide_plugin(Plugin *plugin, int lock)
2903 {
2904         plugin->show = 0;
2905 // Update the toggle
2906         gui->lock_window("MWindow::hide_plugin");
2907         gui->update(0, 1, 0, 0, 0, 0, 0);
2908         gui->unlock_window();
2909
2910         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
2911         for(int i = 0; i < plugin_guis->total; i++)
2912         {
2913                 if(plugin_guis->get(i)->plugin == plugin)
2914                 {
2915                         PluginServer *ptr = plugin_guis->get(i);
2916                         plugin_guis->remove(ptr);
2917                         if(lock) plugin_gui_lock->unlock();
2918 // Last command executed in client side close
2919 // Schedule for deletion
2920                         ptr->hide_gui();
2921                         delete_plugin(ptr);
2922 //sleep(1);
2923                         return;
2924                 }
2925         }
2926         if(lock) plugin_gui_lock->unlock();
2927 }
2928
2929 void MWindow::delete_plugin(PluginServer *plugin)
2930 {
2931         dead_plugin_lock->lock("MWindow::delete_plugin");
2932         dead_plugins->append(plugin);
2933         dead_plugin_lock->unlock();
2934 }
2935
2936 void MWindow::hide_plugins()
2937 {
2938         plugin_gui_lock->lock("MWindow::hide_plugins 1");
2939         while(plugin_guis->size())
2940         {
2941                 PluginServer *ptr = plugin_guis->get(0);
2942                 plugin_guis->remove(ptr);
2943                 plugin_gui_lock->unlock();
2944 // Last command executed in client side close
2945 // Schedule for deletion
2946                 ptr->hide_gui();
2947                 delete_plugin(ptr);
2948                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
2949         }
2950         plugin_gui_lock->unlock();
2951
2952         hide_keyframe_guis();
2953 }
2954
2955 void MWindow::hide_keyframe_guis()
2956 {
2957         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
2958         for(int i = 0; i < keyframe_threads->size(); i++)
2959         {
2960                 keyframe_threads->get(i)->close_window();
2961         }
2962         keyframe_gui_lock->unlock();
2963 }
2964
2965 void MWindow::hide_keyframe_gui(Plugin *plugin)
2966 {
2967         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
2968         for(int i = 0; i < keyframe_threads->size(); i++)
2969         {
2970                 if(keyframe_threads->get(i)->plugin == plugin)
2971                 {
2972                         keyframe_threads->get(i)->close_window();
2973                         break;
2974                 }
2975         }
2976         keyframe_gui_lock->unlock();
2977 }
2978
2979 void MWindow::update_keyframe_guis()
2980 {
2981 // Send new configuration to keyframe GUI's
2982         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
2983         for(int i = 0; i < keyframe_threads->size(); i++)
2984         {
2985                 KeyFrameThread *ptr = keyframe_threads->get(i);
2986                 if(edl->tracks->plugin_exists(ptr->plugin))
2987                         ptr->update_gui(1);
2988                 else
2989                 {
2990                         ptr->close_window();
2991                 }
2992         }
2993         keyframe_gui_lock->unlock();
2994 }
2995
2996 void MWindow::update_plugin_guis(int do_keyframe_guis)
2997 {
2998 // Send new configuration to plugin GUI's
2999         plugin_gui_lock->lock("MWindow::update_plugin_guis");
3000
3001         for(int i = 0; i < plugin_guis->size(); i++)
3002         {
3003                 PluginServer *ptr = plugin_guis->get(i);
3004                 if(edl->tracks->plugin_exists(ptr->plugin))
3005                         ptr->update_gui();
3006                 else
3007                 {
3008 // Schedule for deletion if no plugin
3009                         plugin_guis->remove_number(i);
3010                         i--;
3011
3012                         ptr->hide_gui();
3013                         delete_plugin(ptr);
3014                 }
3015         }
3016
3017
3018 // Change plugin variable if not visible
3019         Track *track = edl->tracks->first;
3020         while(track)
3021         {
3022                 for(int i = 0; i < track->plugin_set.size(); i++)
3023                 {
3024                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3025                         while(plugin)
3026                         {
3027                                 int got_it = 0;
3028                                 for(int i = 0; i < plugin_guis->size(); i++)
3029                                 {
3030                                         PluginServer *server = plugin_guis->get(i);
3031                                         if(server->plugin == plugin)
3032                                         {
3033                                                 got_it = 1;
3034                                                 break;
3035                                         }
3036                                 }
3037
3038                                 if(!got_it) plugin->show = 0;
3039
3040                                 plugin = (Plugin*)plugin->next;
3041                         }
3042                 }
3043
3044                 track = track->next;
3045         }
3046
3047         plugin_gui_lock->unlock();
3048
3049
3050         if(do_keyframe_guis) update_keyframe_guis();
3051 }
3052
3053 int MWindow::plugin_gui_open(Plugin *plugin)
3054 {
3055         int result = 0;
3056         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3057         for(int i = 0; i < plugin_guis->total; i++)
3058         {
3059                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3060                 {
3061                         result = 1;
3062                         break;
3063                 }
3064         }
3065         plugin_gui_lock->unlock();
3066         return result;
3067 }
3068
3069 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3070 {
3071         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3072         for(int i = 0; i < plugin_guis->total; i++)
3073         {
3074                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3075                 {
3076                         plugin_guis->get(i)->render_gui(data);
3077                         break;
3078                 }
3079         }
3080         plugin_gui_lock->unlock();
3081 }
3082
3083 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3084 {
3085         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3086         for(int i = 0; i < plugin_guis->total; i++)
3087         {
3088                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3089                 {
3090                         plugin_guis->get(i)->render_gui(data, size);
3091                         break;
3092                 }
3093         }
3094         plugin_gui_lock->unlock();
3095 }
3096
3097
3098 void MWindow::update_plugin_states()
3099 {
3100         plugin_gui_lock->lock("MWindow::update_plugin_states");
3101         for(int i = 0; i < plugin_guis->total; i++)
3102         {
3103                 int result = 0;
3104 // Get a plugin GUI
3105                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
3106                 PluginServer *src_plugingui = plugin_guis->get(i);
3107
3108 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
3109                 for(Track *track = edl->tracks->first;
3110                         track && !result;
3111                         track = track->next)
3112                 {
3113                         for(int j = 0;
3114                                 j < track->plugin_set.total && !result;
3115                                 j++)
3116                         {
3117                                 PluginSet *plugin_set = track->plugin_set[j];
3118                                 for(Plugin *plugin = (Plugin*)plugin_set->first;
3119                                         plugin && !result;
3120                                         plugin = (Plugin*)plugin->next)
3121                                 {
3122                                         if(plugin == src_plugin &&
3123                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
3124                                 }
3125                         }
3126                 }
3127
3128
3129 // Doesn't exist anymore
3130                 if(!result)
3131                 {
3132                         hide_plugin(src_plugin, 0);
3133                         i--;
3134                 }
3135         }
3136         plugin_gui_lock->unlock();
3137 }
3138
3139
3140 void MWindow::update_plugin_titles()
3141 {
3142         for(int i = 0; i < plugin_guis->total; i++)
3143         {
3144                 plugin_guis->get(i)->update_title();
3145         }
3146 }
3147
3148 int MWindow::asset_to_edl(EDL *new_edl,
3149         Asset *new_asset,
3150         RecordLabels *labels)
3151 {
3152 const int debug = 0;
3153 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3154 __LINE__,
3155 new_asset->layers);
3156 // Keep frame rate, sample rate, and output size unchanged.
3157 // These parameters would revert the project if VWindow displayed an asset
3158 // of different size than the project.
3159         if(new_asset->video_data)
3160         {
3161                 new_edl->session->video_tracks = new_asset->layers;
3162         }
3163         else
3164                 new_edl->session->video_tracks = 0;
3165
3166 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3167
3168
3169
3170
3171
3172         if(new_asset->audio_data)
3173         {
3174                 new_edl->session->audio_tracks = new_asset->channels;
3175         }
3176         else
3177                 new_edl->session->audio_tracks = 0;
3178 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3179
3180 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3181         new_edl->create_default_tracks();
3182 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3183 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3184
3185
3186
3187 //printf("MWindow::asset_to_edl 3\n");
3188         new_edl->insert_asset(new_asset,
3189                 0,
3190                 0,
3191                 0,
3192                 labels);
3193 //printf("MWindow::asset_to_edl 3\n");
3194 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3195
3196 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3197         if(edl->session->cursor_on_frames)
3198         {
3199                 double length = new_edl->tracks->total_length();
3200                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3201                 new_edl->tracks->clear(length, edl_length, 1, 1);
3202         }
3203
3204
3205
3206
3207         char string[BCTEXTLEN];
3208         FileSystem fs;
3209         fs.extract_name(string, new_asset->path);
3210 //printf("MWindow::asset_to_edl 3\n");
3211
3212         strcpy(new_edl->local_session->clip_title, string);
3213 //printf("MWindow::asset_to_edl 4 %s\n", string);
3214 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3215
3216         return 0;
3217 }
3218
3219
3220 // Reset everything after a load.
3221 void MWindow::update_project(int load_mode)
3222 {
3223         const int debug = 0;
3224
3225         if(debug) PRINT_TRACE
3226         edl->tracks->update_y_pixels(theme);
3227
3228         if(debug) PRINT_TRACE
3229
3230         if(load_mode == LOADMODE_REPLACE ||
3231                 load_mode == LOADMODE_REPLACE_CONCATENATE)
3232         {
3233                 gui->load_panes();
3234         }
3235
3236         gui->update(1, 1, 1, 1, 1, 1, 1);
3237         if(debug) PRINT_TRACE
3238         gui->unlock_window();
3239         init_brender();
3240
3241         cwindow->gui->lock_window("MWindow::update_project 1");
3242         cwindow->update(0, 0, 1, 1, 1);
3243         cwindow->gui->unlock_window();
3244
3245         if(debug) PRINT_TRACE
3246
3247 // Close all the vwindows
3248         if( load_mode == LOADMODE_REPLACE ||
3249             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3250                 if(debug) PRINT_TRACE
3251                 int first_vwindow = 0;
3252                 if(session->show_vwindow) first_vwindow = 1;
3253 // Change visible windows to no source
3254                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3255                         VWindow *vwindow = vwindows[i];
3256                         if( !vwindow->is_running() ) continue;
3257                         vwindow->change_source(-1);
3258                 }
3259
3260 // Close remaining windows
3261                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3262                         VWindow *vwindow = vwindows[i];
3263                         if( !vwindow->is_running() ) continue;
3264                         vwindow->close_window();
3265                 }
3266                 for( int i=0; i<edl->vwindow_edls.size(); ++i ) {
3267                         VWindow *vwindow = get_viewer(1, -1);
3268                         vwindow->change_source(i);
3269                 }
3270                 if(debug) PRINT_TRACE
3271                 select_zwindow(0);
3272                 close_mixers();
3273
3274                 for( int i=0; i<edl->mixers.size(); ++i ) {
3275                         Mixer *mixer = edl->mixers[i];
3276                         ZWindow *zwindow = get_mixer(mixer);
3277                         zwindow->set_title(mixer->title);
3278                         zwindow->start();
3279                 }
3280         }
3281         else {
3282                 if(vwindows.size()) {
3283                         VWindow *vwindow = vwindows[DEFAULT_VWINDOW];
3284                         if( vwindow->is_running() ) {
3285                                 vwindow->gui->lock_window("MWindow::update_project");
3286                                 vwindow->update(1);
3287                                 vwindow->gui->unlock_window();
3288                         }
3289                 }
3290         }
3291
3292         if(debug) PRINT_TRACE
3293         cwindow->gui->lock_window("MWindow::update_project 2");
3294         cwindow->gui->timebar->update(0);
3295         cwindow->gui->unlock_window();
3296
3297         if(debug) PRINT_TRACE
3298         cwindow->refresh_frame(CHANGE_ALL);
3299
3300         awindow->gui->async_update_assets();
3301         if(debug) PRINT_TRACE
3302
3303         gui->lock_window("MWindow::update_project");
3304         gui->update_mixers(0, 0);
3305         gui->flush();
3306         if(debug) PRINT_TRACE
3307 }
3308
3309 void MWindow::remove_indexfile(Indexable *indexable)
3310 {
3311         if( !indexable->is_asset ) return;
3312         Asset *asset = (Asset *)indexable;
3313 // Erase file
3314         IndexFile::delete_index(preferences, asset, ".toc");
3315         IndexFile::delete_index(preferences, asset, ".idx");
3316         IndexFile::delete_index(preferences, asset, ".mkr");
3317 }
3318
3319 void MWindow::rebuild_indices()
3320 {
3321         for(int i = 0; i < session->drag_assets->total; i++)
3322         {
3323                 Indexable *indexable = session->drag_assets->get(i);
3324 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3325                 remove_indexfile(indexable);
3326 // Schedule index build
3327                 IndexState *index_state = indexable->index_state;
3328                 index_state->index_status = INDEX_NOTTESTED;
3329                 if( indexable->is_asset ) {
3330                         Asset *asset = (Asset *)indexable;
3331                         if( asset->format != FILE_PCM ) {
3332                                 asset->format = FILE_UNKNOWN;
3333                                 asset->reset_audio();
3334                         }
3335                         asset->reset_video();
3336                         remove_asset_from_caches(asset);
3337 //                      File file; // re-probe the asset
3338 //                      file.open_file(preferences, asset, 1, 0);
3339                 }
3340                 mainindexes->add_next_asset(0, indexable);
3341         }
3342         mainindexes->start_build();
3343 }
3344
3345
3346 void MWindow::save_backup()
3347 {
3348         FileXML file;
3349         edl->optimize();
3350         edl->set_path(session->filename);
3351         char backup_path[BCTEXTLEN], backup_path1[BCTEXTLEN];
3352         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3353                 File::get_config_path(), BACKUP_FILE);
3354         snprintf(backup_path1, sizeof(backup_path1), "%s/%s",
3355                 File::get_config_path(), BACKUP_FILE1);
3356         rename(backup_path, backup_path1);
3357         edl->save_xml(&file, backup_path);
3358         file.terminate_string();
3359         FileSystem fs;
3360         fs.complete_path(backup_path);
3361
3362         if(file.write_to_file(backup_path))
3363         {
3364                 char string2[256];
3365                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
3366                 gui->show_message(string2);
3367         }
3368 }
3369
3370 void MWindow::load_backup()
3371 {
3372         ArrayList<char*> path_list;
3373         path_list.set_array_delete();
3374         char *out_path;
3375         char backup_path[BCTEXTLEN];
3376         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3377                 File::get_config_path(), BACKUP_FILE);
3378         FileSystem fs;
3379         fs.complete_path(backup_path);
3380
3381         path_list.append(out_path = new char[strlen(backup_path) + 1]);
3382         strcpy(out_path, backup_path);
3383
3384         load_filenames(&path_list, LOADMODE_REPLACE, 0);
3385         edl->local_session->clip_title[0] = 0;
3386 // This is unique to backups since the path of the backup is different than the
3387 // path of the project.
3388         set_filename(edl->path);
3389         path_list.remove_all_objects();
3390         save_backup();
3391 }
3392
3393
3394 void MWindow::save_undo_data()
3395 {
3396         char perpetual_path[BCTEXTLEN];
3397         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
3398                 File::get_config_path(), PERPETUAL_FILE);
3399         FILE *fp = fopen(perpetual_path,"w");
3400         if( !fp ) return;
3401         undo->save(fp);
3402         fclose(fp);
3403 }
3404
3405 void MWindow::load_undo_data()
3406 {
3407         char perpetual_path[BCTEXTLEN];
3408         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
3409                 File::get_config_path(), PERPETUAL_FILE);
3410         FILE *fp = fopen(perpetual_path,"r");
3411         if( !fp ) return;
3412         undo->load(fp);
3413         fclose(fp);
3414 }
3415
3416 static inline int gcd(int m, int n)
3417 {
3418         int r;
3419         if( m < n ) { r = m;  m = n;  n = r; }
3420         while( (r = m % n) != 0 ) { m = n;  n = r; }
3421         return n;
3422 }
3423
3424 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
3425 {
3426         w = 1;  h = 1;
3427         if(!width || !height) return 1;
3428         if( width == 720 && (height == 480 || height == 576) ) {
3429                 w = 4;  h = 3;  return 0; // for NTSC and PAL
3430         }
3431         double ar = (double)width / height;
3432 // square-ish pixels
3433         if( EQUIV(ar, 1.0000) ) return 0;
3434         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
3435         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
3436         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
3437         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
3438         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
3439         int ww = width, hh = height;
3440         // numerator, denominator must be under mx
3441         int mx = 255, n = gcd(ww, hh);
3442         if( n > 1 ) { ww /= n; hh /= n; }
3443         // search near height in case extra/missing lines
3444         if( ww >= mx || hh >= mx ) {
3445                 double err = height;  // +/- 2 percent height
3446                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
3447                         int iw = width, ih = height+i;
3448                         if( (n=gcd(iw, ih)) > 1 ) {
3449                                 int u = iw/n;  if( u >= mx ) continue;
3450                                 int v = ih/n;  if( v >= mx ) continue;
3451                                 double r = (double) u/v, er = fabs(ar-r);
3452                                 if( er >= err ) continue;
3453                                 err = er;  ww = u;  hh = v;
3454                         }
3455                 }
3456         }
3457
3458         w = ww;  h = hh;
3459         return 0;
3460 }
3461
3462 void MWindow::reset_caches()
3463 {
3464         frame_cache->remove_all();
3465         wave_cache->remove_all();
3466         audio_cache->remove_all();
3467         video_cache->remove_all();
3468         if( cwindow->playback_engine ) {
3469                 if( cwindow->playback_engine->audio_cache )
3470                         cwindow->playback_engine->audio_cache->remove_all();
3471                 if( cwindow->playback_engine->video_cache )
3472                         cwindow->playback_engine->video_cache->remove_all();
3473         }
3474         for(int i = 0; i < vwindows.size(); i++) {
3475                 VWindow *vwindow = vwindows[i];
3476                 if( !vwindow->is_running() ) continue;
3477                 if( !vwindow->playback_engine ) continue;
3478                 if( vwindow->playback_engine->audio_cache )
3479                         vwindow->playback_engine->audio_cache->remove_all();
3480                 if( vwindow->playback_engine->video_cache )
3481                         vwindow->playback_engine->video_cache->remove_all();
3482         }
3483 }
3484
3485 void MWindow::remove_asset_from_caches(Asset *asset)
3486 {
3487         frame_cache->remove_asset(asset);
3488         wave_cache->remove_asset(asset);
3489         audio_cache->delete_entry(asset);
3490         video_cache->delete_entry(asset);
3491         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3492                 cwindow->playback_engine->audio_cache->delete_entry(asset);
3493         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3494                 cwindow->playback_engine->video_cache->delete_entry(asset);
3495         for(int i = 0; i < vwindows.size(); i++) {
3496                 VWindow *vwindow = vwindows[i];
3497                 if( !vwindow->is_running() ) continue;
3498                 if( !vwindow->playback_engine ) continue;
3499                 if( vwindow->playback_engine->audio_cache )
3500                         vwindow->playback_engine->audio_cache->delete_entry(asset);
3501                 if( vwindow->playback_engine->video_cache )
3502                         vwindow->playback_engine->video_cache->delete_entry(asset);
3503         }
3504 }
3505
3506
3507 void MWindow::remove_assets_from_project(int push_undo, int redraw,
3508                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
3509 {
3510         for(int i = 0; i < drag_assets->total; i++) {
3511                 Indexable *indexable = drag_assets->get(i);
3512                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
3513         }
3514
3515 // Remove from VWindow.
3516         for(int i = 0; i < session->drag_clips->total; i++) {
3517                 for(int j = 0; j < vwindows.size(); j++) {
3518                         VWindow *vwindow = vwindows[j];
3519                         if( !vwindow->is_running() ) continue;
3520                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
3521                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
3522                                 vwindow->delete_source(1, 1);
3523                                 vwindow->gui->unlock_window();
3524                         }
3525                 }
3526         }
3527
3528         for(int i = 0; i < drag_assets->size(); i++) {
3529                 for(int j = 0; j < vwindows.size(); j++) {
3530                         VWindow *vwindow = vwindows[j];
3531                         if( !vwindow->is_running() ) continue;
3532                         if(drag_assets->get(i) == vwindow->get_source()) {
3533                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
3534                                 vwindow->delete_source(1, 1);
3535                                 vwindow->gui->unlock_window();
3536                         }
3537                 }
3538         }
3539
3540         for(int i = 0; i < drag_assets->size(); i++) {
3541                 Indexable *indexable = drag_assets->get(i);
3542                 remove_indexfile(indexable);
3543         }
3544
3545 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3546         if(push_undo) undo->update_undo_before();
3547         if(drag_assets) edl->remove_from_project(drag_assets);
3548         if(drag_clips) edl->remove_from_project(drag_clips);
3549         if(redraw) save_backup();
3550         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
3551         if(redraw) {
3552                 restart_brender();
3553
3554                 gui->lock_window("MWindow::remove_assets_from_project 3");
3555                 gui->update(1, 1, 1, 1, 0, 1, 0);
3556                 gui->unlock_window();
3557
3558         // Removes from playback here
3559                 sync_parameters(CHANGE_ALL);
3560         }
3561
3562         awindow->gui->async_update_assets();
3563 }
3564
3565 void MWindow::remove_assets_from_disk()
3566 {
3567 // Remove from disk
3568         for(int i = 0; i < session->drag_assets->total; i++)
3569         {
3570                 remove(session->drag_assets->get(i)->path);
3571         }
3572
3573         remove_assets_from_project(1,
3574                 1,
3575                 session->drag_assets,
3576                 session->drag_clips);
3577 }
3578
3579 void MWindow::dump_plugins(FILE *fp)
3580 {
3581         if( !plugindb ) return;
3582         for(int i = 0; i < plugindb->total; i++)
3583         {
3584                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
3585                         " synth=%d transition=%d theme=%d %s\n",
3586                         plugindb->get(i)->plugin_type,
3587                         plugindb->get(i)->audio,
3588                         plugindb->get(i)->video,
3589                         plugindb->get(i)->realtime,
3590                         plugindb->get(i)->multichannel,
3591                         plugindb->get(i)->get_synthesis(),
3592                         plugindb->get(i)->transition,
3593                         plugindb->get(i)->theme,
3594                         plugindb->get(i)->title);
3595         }
3596 }
3597
3598 void MWindow::dump_edl(FILE *fp)
3599 {
3600         if( !edl ) return;
3601         edl->dump(fp);
3602 }
3603
3604 void MWindow::dump_undo(FILE *fp)
3605 {
3606         if( !undo ) return;
3607         undo->dump(fp);
3608 }
3609
3610 void MWindow::dump_exe(FILE *fp)
3611 {
3612         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
3613         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
3614
3615         int ret = -1, n = 100;
3616         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
3617                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
3618                 ret = 0;
3619         }
3620         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
3621
3622         struct stat st;
3623         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
3624         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
3625         struct tm *tm = localtime(&st.st_mtime);
3626         char mtime[256];
3627         strftime(mtime, sizeof(mtime), "%F %T", tm);
3628         fprintf(fp,"mtime: %s\n", mtime);
3629 #if 0
3630 // people hit ctl-c waiting for this
3631         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
3632         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
3633         uint8_t *bfr = 0;
3634         int64_t bfrsz = 0;
3635         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
3636         int64_t maxsz = 1024*pagsz;
3637         int64_t size = st.st_size, pos = 0;
3638         SHA1 sha1;
3639         while( (bfrsz = size-pos) > 0 ) {
3640                 if( bfrsz > maxsz ) bfrsz = maxsz;
3641                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
3642                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
3643                 if( bfr == MAP_FAILED ) break;
3644                 sha1.addBytes(bfr, bfrsz);
3645                 munmap(bfr, bfrsz);
3646                 pos += bfrsz;
3647         }
3648         close(fd);
3649         ret = pos < size ? EIO : 0;
3650         fprintf(fp, "SHA1: ");
3651         uint8_t digest[20];  sha1.computeHash(digest);
3652         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
3653         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
3654         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
3655 #endif
3656         fprintf(fp, "\n");
3657 }
3658
3659 void MWindow::trap_hook(FILE *fp, void *vp)
3660 {
3661         MWindow *mwindow = (MWindow *)vp;
3662 //      fprintf(fp, "\nPLUGINS:\n");
3663 //      mwindow->dump_plugins(fp);
3664         fprintf(fp, "\nEDL:\n");
3665         mwindow->dump_edl(fp);
3666         fprintf(fp, "\nUNDO:\n");
3667         mwindow->dump_undo(fp);
3668         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
3669         mwindow->dump_exe(fp);
3670 }
3671
3672
3673
3674
3675
3676
3677 int MWindow::save_defaults()
3678 {
3679         gui->save_defaults(defaults);
3680         edl->save_defaults(defaults);
3681         session->save_defaults(defaults);
3682         preferences->save_defaults(defaults);
3683
3684         for(int i = 0; i < plugin_guis->total; i++)
3685         {
3686 // Pointer comparison
3687                 plugin_guis->get(i)->save_defaults();
3688         }
3689         awindow->save_defaults(defaults);
3690
3691         defaults->save();
3692         return 0;
3693 }
3694
3695 int MWindow::run_script(FileXML *script)
3696 {
3697         int result = 0, result2 = 0;
3698         while(!result && !result2)
3699         {
3700                 result = script->read_tag();
3701                 if(!result)
3702                 {
3703                         if(script->tag.title_is("new_project"))
3704                         {
3705 // Run new in immediate mode.
3706 //                              gui->mainmenu->new_project->run_script(script);
3707                         }
3708                         else
3709                         if(script->tag.title_is("record"))
3710                         {
3711 // Run record as a thread.  It is a terminal command.
3712                                 ;
3713 // Will read the complete scipt file without letting record read it if not
3714 // terminated.
3715                                 result2 = 1;
3716                         }
3717                         else
3718                         {
3719                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
3720                         }
3721                 }
3722         }
3723         return result2;
3724 }
3725
3726 // ================================= synchronization
3727
3728
3729 int MWindow::interrupt_indexes()
3730 {
3731         mainprogress->cancelled = 1;
3732         mainindexes->interrupt_build();
3733         return 0;
3734 }
3735
3736
3737
3738 void MWindow::next_time_format()
3739 {
3740         switch(edl->session->time_format)
3741         {
3742                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
3743                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
3744                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3745                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
3746                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
3747                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
3748                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
3749         }
3750
3751         time_format_common();
3752 }
3753
3754 void MWindow::prev_time_format()
3755 {
3756         switch(edl->session->time_format)
3757         {
3758                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
3759                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
3760                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
3761                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3762                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
3763                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
3764                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
3765         }
3766
3767         time_format_common();
3768 }
3769
3770 void MWindow::time_format_common()
3771 {
3772         gui->lock_window("MWindow::next_time_format");
3773         gui->redraw_time_dependancies();
3774
3775
3776         char string[BCTEXTLEN], string2[BCTEXTLEN];
3777         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
3778         gui->show_message(string);
3779         gui->flush();
3780         gui->unlock_window();
3781 }
3782
3783
3784 int MWindow::set_filename(const char *filename)
3785 {
3786         if( filename != session->filename )
3787                 strcpy(session->filename, filename);
3788         if( filename != edl->path )
3789                 strcpy(edl->path, filename);
3790
3791         if(gui)
3792         {
3793                 if(filename[0] == 0)
3794                 {
3795                         gui->set_title(PROGRAM_NAME);
3796                 }
3797                 else
3798                 {
3799                         FileSystem dir;
3800                         char string[BCTEXTLEN], string2[BCTEXTLEN];
3801                         dir.extract_name(string, filename);
3802                         sprintf(string2, PROGRAM_NAME ": %s", string);
3803                         gui->set_title(string2);
3804                 }
3805         }
3806         return 0;
3807 }
3808
3809
3810
3811
3812
3813
3814
3815
3816 int MWindow::set_loop_boundaries()
3817 {
3818         double start = edl->local_session->get_selectionstart();
3819         double end = edl->local_session->get_selectionend();
3820
3821         if(start !=
3822                 end)
3823         {
3824                 ;
3825         }
3826         else
3827         if(edl->tracks->total_length())
3828         {
3829                 start = 0;
3830                 end = edl->tracks->total_length();
3831         }
3832         else
3833         {
3834                 start = end = 0;
3835         }
3836
3837         if(edl->local_session->loop_playback && start != end)
3838         {
3839                 edl->local_session->loop_start = start;
3840                 edl->local_session->loop_end = end;
3841         }
3842         return 0;
3843 }
3844
3845
3846
3847
3848
3849
3850
3851 int MWindow::reset_meters()
3852 {
3853         cwindow->gui->lock_window("MWindow::reset_meters 1");
3854         cwindow->gui->meters->reset_meters();
3855         cwindow->gui->unlock_window();
3856
3857         for(int j = 0; j < vwindows.size(); j++) {
3858                 VWindow *vwindow = vwindows[j];
3859                 if( !vwindow->is_running() ) continue;
3860                 vwindow->gui->lock_window("MWindow::reset_meters 2");
3861                 vwindow->gui->meters->reset_meters();
3862                 vwindow->gui->unlock_window();
3863         }
3864
3865         lwindow->gui->lock_window("MWindow::reset_meters 3");
3866         lwindow->gui->panel->reset_meters();
3867         lwindow->gui->unlock_window();
3868
3869         gui->lock_window("MWindow::reset_meters 4");
3870         gui->reset_meters();
3871         gui->unlock_window();
3872         return 0;
3873 }
3874
3875
3876 void MWindow::resync_guis()
3877 {
3878 // Update GUIs
3879         restart_brender();
3880         gui->lock_window("MWindow::resync_guis");
3881         gui->update(1, 1, 1, 1, 1, 1, 0);
3882         gui->unlock_window();
3883
3884         cwindow->gui->lock_window("MWindow::resync_guis");
3885         cwindow->gui->resize_event(cwindow->gui->get_w(),
3886                 cwindow->gui->get_h());
3887         int channels = edl->session->audio_channels;
3888         cwindow->gui->meters->set_meters(channels, 1);
3889         cwindow->gui->flush();
3890         cwindow->gui->unlock_window();
3891
3892         for(int i = 0; i < vwindows.size(); i++) {
3893                 VWindow *vwindow = vwindows[i];
3894                 if( !vwindow->is_running() ) continue;
3895                 vwindow->gui->lock_window("MWindow::resync_guis");
3896                 vwindow->gui->resize_event(vwindow->gui->get_w(),
3897                         vwindow->gui->get_h());
3898                 vwindow->gui->meters->set_meters(channels, 1);
3899                 vwindow->gui->flush();
3900                 vwindow->gui->unlock_window();
3901         }
3902
3903         lwindow->gui->lock_window("MWindow::resync_guis");
3904         lwindow->gui->panel->set_meters(channels, 1);
3905         lwindow->gui->flush();
3906         lwindow->gui->unlock_window();
3907
3908 // Warn user
3909         if(((edl->session->output_w % 4) ||
3910                 (edl->session->output_h % 4)) &&
3911                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
3912         {
3913                 MainError::show_error(
3914                         _("This project's dimensions are not multiples of 4 so\n"
3915                         "it can't be rendered by OpenGL."));
3916         }
3917
3918
3919 // Flash frame
3920         sync_parameters(CHANGE_ALL);
3921 }
3922
3923 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
3924 {
3925         File *file = new File;
3926         EDLSession *session = edl->session;
3927         double old_framerate = session->frame_rate;
3928         double old_samplerate = session->sample_rate;
3929         int old_auto_keyframes = session->auto_keyframes;
3930         session->auto_keyframes = 0;
3931         int result = file->open_file(preferences, asset, 1, 0);
3932         if( !result && delete_tracks > 0 )
3933                 undo->update_undo_before();
3934         int video_layers = asset->get_video_layers();
3935         if( !result && asset->video_data && vstream < video_layers ) {
3936                 // try to get asset up to date, may fail
3937                 file->select_video_stream(asset, vstream);
3938                 // either way use what was/is there.
3939                 double framerate = asset->get_frame_rate();
3940                 int width = asset->get_w();
3941                 int height = asset->get_h();
3942                 // must be multiple of 4 for opengl
3943                 width = (width+3) & ~3;  height = (height+3) & ~3;
3944                 int driver = session->playback_config->vconfig->driver;
3945                 int color_model = file->get_best_colormodel(asset, driver);
3946 //              color_model = BC_CModels::is_yuv(color_model) ?
3947 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
3948 //                      BC_CModels::is_float(color_model) ?
3949 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
3950 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
3951 // have alpha for now
3952                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
3953                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
3954                 session->color_model = color_model;
3955                 session->output_w = width;
3956                 session->output_h = height;
3957                 session->frame_rate = framerate;
3958                 // not, asset->actual_width/actual_height
3959                 asset->width = session->output_w;
3960                 asset->height = session->output_h;
3961                 asset->frame_rate = session->frame_rate;
3962                 create_aspect_ratio(session->aspect_w, session->aspect_h,
3963                         session->output_w, session->output_h);
3964                 Track *track = edl->tracks->first;
3965                 for( Track *next_track=0; track; track=next_track ) {
3966                         next_track = track->next;
3967                         if( track->data_type != TRACK_VIDEO ) continue;
3968                         if( delete_tracks ) {
3969                                 Edit *edit = track->edits->first;
3970                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
3971                                         next_edit = edit->next;
3972                                         if( edit->channel != vstream ||
3973                                             !edit->asset || !edit->asset->is_asset ||
3974                                             !asset->equivalent(*edit->asset,1,1,edl) )
3975                                                 delete edit;
3976                                 }
3977                         }
3978                         if( track->edits->first ) {
3979                                 track->track_w = edl->session->output_w;
3980                                 track->track_h = edl->session->output_h;
3981                         }
3982                         else if( delete_tracks )
3983                                 edl->tracks->delete_track(track);
3984                 }
3985                 edl->retrack();
3986                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
3987         }
3988         if( !result && asset->audio_data && asset->channels > 0 ) {
3989                 session->sample_rate = asset->get_sample_rate();
3990                 int64_t channel_mask = 0;
3991                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
3992                         file->get_audio_for_video(vstream, astream, channel_mask);
3993                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
3994                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
3995                 int channels = 0;
3996                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
3997                 if( channels < 1 ) channels = 1;
3998                 if( channels > 6 ) channels = 6;
3999                 session->audio_tracks = session->audio_channels = channels;
4000
4001                 int *achannel_positions = preferences->channel_positions[session->audio_channels-1];
4002                 memcpy(&session->achannel_positions, achannel_positions, sizeof(session->achannel_positions));
4003                 remap_audio(MWindow::AUDIO_1_TO_1);
4004
4005                 if( delete_tracks ) {
4006                         Track *track = edl->tracks->first;
4007                         for( Track *next_track=0; track; track=next_track ) {
4008                                 next_track = track->next;
4009                                 if( track->data_type != TRACK_AUDIO ) continue;
4010                                 Edit *edit = track->edits->first;
4011                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
4012                                         next_edit = edit->next;
4013                                         if( !((1<<edit->channel) & channel_mask) ||
4014                                             !edit->asset || !edit->asset->is_asset ||
4015                                             !asset->equivalent(*edit->asset,1,1,edl) )
4016                                                 delete edit;
4017                                 }
4018                                 if( !track->edits->first )
4019                                         edl->tracks->delete_track(track);
4020                         }
4021                 }
4022                 edl->rechannel();
4023                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
4024         }
4025         delete file;
4026         session->auto_keyframes = old_auto_keyframes;
4027         if( !result && delete_tracks > 0 ) {
4028                 save_backup();
4029                 undo->update_undo_after(_("select asset"), LOAD_ALL);
4030         }
4031         resync_guis();
4032         return result;
4033 }
4034
4035 int MWindow::select_asset(int vtrack, int delete_tracks)
4036 {
4037         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
4038         if( !track )
4039                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
4040         if( !track ) return 1;
4041         Edit *edit = track->edits->first;
4042         if( !edit ) return 1;
4043         Asset *asset = edit->asset;
4044         if( !asset || !asset->is_asset ) return 1;
4045         return select_asset(asset, edit->channel, 0, delete_tracks);
4046 }
4047
4048 void MWindow::dump_plugindb(FILE *fp)
4049 {
4050         if( !plugindb ) return;
4051         for(int i = 0; i < plugindb->total; i++)
4052                 plugindb->get(i)->dump(fp);
4053 }
4054
4055 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
4056 {
4057         Auto *current = 0;
4058         double unit_position = edl->local_session->get_selectionstart(1);
4059         unit_position = patch->track->to_units(unit_position, 0);
4060
4061         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
4062         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4063 }
4064
4065 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
4066 {
4067         Auto *current = 0;
4068         double unit_position = edl->local_session->get_selectionstart(1);
4069         unit_position = patch->track->to_units(unit_position, 0);
4070
4071         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
4072         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4073 }
4074
4075 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
4076 {
4077         Auto *current = 0;
4078         double unit_position = edl->local_session->get_selectionstart(1);
4079         unit_position = patch->track->to_units(unit_position, 0);
4080
4081         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
4082         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4083 }
4084
4085 PatchGUI *MWindow::get_patchgui(Track *track)
4086 {
4087         PatchGUI *patchgui = 0;
4088         TimelinePane **panes = gui->pane;
4089         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
4090                 if( !panes[i] ) continue;
4091                 PatchBay *patchbay = panes[i]->patchbay;
4092                 if( !patchbay ) continue;
4093                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
4094                         if( patchbay->patches.values[j]->track == track )
4095                                 patchgui = patchbay->patches.values[j];
4096                 }
4097         }
4098         return patchgui;
4099 }
4100