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