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