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