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