delete mwindow before restarting for new theme
[goodguy/history.git] / cinelerra-5.0 / 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 "asset.h"
22 #include "assets.h"
23 #include "audioalsa.h"
24 #include "awindowgui.h"
25 #include "awindow.h"
26 #include "batchrender.h"
27 #include "bcdisplayinfo.h"
28 #include "bcsignals.h"
29 #include "bctimer.h"
30 #include "bdcreate.h"
31 #include "brender.h"
32 #include "cache.h"
33 #include "channel.h"
34 #include "channeldb.h"
35 #include "channelinfo.h"
36 #include "clip.h"
37 #include "bccmodels.h"
38 #include "commercials.h"
39 #include "cplayback.h"
40 #include "ctimebar.h"
41 #include "cwindowgui.h"
42 #include "cwindow.h"
43 #include "bchash.h"
44 #include "devicedvbinput.inc"
45 #include "dvdcreate.h"
46 #include "editpanel.h"
47 #include "edl.h"
48 #include "edlsession.h"
49 #include "errorbox.h"
50 #include "fileformat.h"
51 #include "file.h"
52 #include "filesystem.h"
53 #include "filexml.h"
54 #include "format.inc"
55 #include "framecache.h"
56 #include "gwindow.h"
57 #include "gwindowgui.h"
58 #include "keyframegui.h"
59 #include "indexfile.h"
60 #include "language.h"
61 #include "levelwindowgui.h"
62 #include "levelwindow.h"
63 #include "loadfile.inc"
64 #include "localsession.h"
65 #include "maincursor.h"
66 #include "mainerror.h"
67 #include "mainindexes.h"
68 #include "mainmenu.h"
69 #include "mainprogress.h"
70 #include "mainsession.h"
71 #include "mainundo.h"
72 #include "mbuttons.h"
73 #include "mutex.h"
74 #include "mwindowgui.h"
75 #include "mwindow.h"
76 #include "nestededls.h"
77 #include "new.h"
78 #include "patchbay.h"
79 #include "playback3d.h"
80 #include "playbackengine.h"
81 #include "plugin.h"
82 #include "pluginserver.h"
83 #include "pluginset.h"
84 #include "preferences.h"
85 #include "record.h"
86 #include "recordmonitor.h"
87 #include "recordlabel.h"
88 #include "removefile.h"
89 #include "render.h"
90 #include "samplescroll.h"
91 #include "sha1.h"
92 #include "sighandler.h"
93 #include "splashgui.h"
94 #include "statusbar.h"
95 #include "theme.h"
96 #include "threadloader.h"
97 #include "timebar.h"
98 #include "tipwindow.h"
99 #include "trackcanvas.h"
100 #include "track.h"
101 #include "tracking.h"
102 #include "trackscroll.h"
103 #include "tracks.h"
104 #include "transition.h"
105 #include "transportque.h"
106 #include "vframe.h"
107 #include "videodevice.inc"
108 #include "videowindow.h"
109 #include "vplayback.h"
110 #include "vwindowgui.h"
111 #include "vwindow.h"
112 #include "wavecache.h"
113 #include "wwindow.h"
114 #include "zoombar.h"
115
116 #include <string.h>
117 #include <sys/stat.h>
118
119
120 extern "C"
121 {
122
123
124
125
126 // Hack for libdv to remove glib dependancy
127
128 // void
129 // g_log (const char    *log_domain,
130 //        int  log_level,
131 //        const char    *format,
132 //        ...)
133 // {
134 // }
135 // 
136 // void
137 // g_logv (const char    *log_domain,
138 //        int  log_level,
139 //        const char    *format,
140 //        ...)
141 // {
142 // }
143 // 
144
145
146 // Hack for XFree86 4.1.0
147
148 int atexit(void (*function)(void))
149 {
150         return 0;
151 }
152
153
154
155 }
156
157
158
159 ArrayList<PluginServer*>* MWindow::plugindb = 0;
160 Commercials* MWindow::commercials = 0;
161
162
163 MWindow::MWindow()
164  : Thread(1, 0, 0)
165 {
166         plugin_gui_lock = new Mutex("MWindow::plugin_gui_lock");
167         dead_plugin_lock = new Mutex("MWindow::dead_plugin_lock");
168         vwindows_lock = new Mutex("MWindow::vwindows_lock");
169         brender_lock = new Mutex("MWindow::brender_lock");
170         keyframe_gui_lock = new Mutex("MWindow::keyframe_gui_lock");
171
172         playback_3d = 0;
173         splash_window = 0;
174         undo = 0;
175         defaults = 0;
176         assets = 0;
177         //commercials = 0;
178         commercial_active = 0;
179         audio_cache = 0;
180         video_cache = 0;
181         frame_cache = 0;
182         wave_cache = 0;
183         preferences = 0;
184         session = 0;
185         theme = 0;
186         mainindexes = 0;
187         mainprogress = 0;
188         brender = 0;
189         channeldb_buz =  new ChannelDB;
190         channeldb_v4l2jpeg =  new ChannelDB;
191         //file_server = 0;
192         plugin_guis = 0;
193         dead_plugins = 0;
194         keyframe_threads = 0;
195         create_bd = 0;
196         create_dvd = 0;
197         batch_render = 0;
198         render = 0;
199         edl = 0;
200         gui = 0;
201         cwindow = 0;
202         awindow = 0;
203         gwindow = 0;
204         twindow = 0;
205         wwindow = 0;
206         lwindow = 0;
207         sighandler = 0;
208         restart_status = 0;
209         screens = 1;
210         in_destructor = 0;
211 }
212
213
214 // Need to delete brender temporary here.
215 MWindow::~MWindow()
216 {
217         in_destructor = 1;
218 //printf("MWindow::~MWindow %d\n", __LINE__);
219         gui->stop_drawing();
220         gui->remote_control->deactivate();
221         gui->record->stop();
222         gui->channel_info->stop();
223         brender_lock->lock("MWindow::quit");
224         delete brender;         brender = 0;
225         brender_lock->unlock();
226         delete create_bd;       create_bd = 0;
227         delete create_dvd;      create_dvd = 0;
228         delete batch_render;    batch_render = 0;
229         commit_commercial();
230         if( commercials && !commercials->remove_user() ) commercials = 0;
231
232 // Save defaults for open plugins
233         plugin_gui_lock->lock("MWindow::~MWindow");
234         for(int i = 0; i < plugin_guis->size(); i++)
235         {
236                 plugin_guis->get(i)->hide_gui();
237         }
238         plugin_gui_lock->unlock();
239         hide_keyframe_guis();
240         clean_indexes();
241         save_defaults();
242 // Give up and go to a movie
243 //  cant run valgrind if this is used
244
245         gui->del_keyboard_listener(
246                 (int (BC_WindowBase::*)(BC_WindowBase *))
247                 &MWindowGUI::keyboard_listener);
248 #if 0
249 // release the hounds
250         if( awindow && awindow->gui ) awindow->gui->close(0);
251         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
252         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
253         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
254         if( twindow && twindow->is_running() ) twindow->close_window();
255         if( wwindow && wwindow->is_running() ) wwindow->close_window();
256         vwindows.remove_all_objects();
257         gui->close(0);
258         if( awindow ) awindow->join();
259         if( cwindow ) cwindow->join();
260         if( lwindow ) lwindow->join();
261         if( twindow ) twindow->join();
262         if( wwindow ) wwindow->join();
263         if( gwindow ) gwindow->join();
264         join();
265 #else
266 // one at a time, or nouveau chokes
267 #define close_gui(win) if( win ) { \
268   if( win->gui ) win->gui->close(0); \
269   win->join(); }
270         close_gui(awindow);
271         close_gui(cwindow);
272         close_gui(lwindow);
273         close_gui(gwindow);
274         close_gui(twindow);
275         close_gui(wwindow);
276         vwindows.remove_all_objects();
277         gui->close(0);
278         join();
279 #endif
280         reset_caches();
281         dead_plugins->remove_all();
282         finit_error();
283         keyframe_threads->remove_all_objects();
284         if( !edl->Garbage::remove_user() ) edl = 0;
285         colormodels.remove_all_objects();
286         delete gui;             gui = 0;
287         delete render;          render = 0;
288         delete awindow;         awindow = 0;
289         delete lwindow;         lwindow = 0;
290         delete twindow;         twindow = 0;
291         delete wwindow;         wwindow = 0;
292         delete gwindow;         gwindow = 0;
293         // must be last or nouveau chokes
294         delete cwindow;         cwindow = 0;
295         //delete file_server;  file_server = 0; // reusable
296         delete mainindexes;     mainindexes = 0;
297         delete mainprogress;    mainprogress = 0;
298         delete audio_cache;     audio_cache = 0;  // delete the cache after the assets
299         delete video_cache;     video_cache = 0;  // delete the cache after the assets
300         delete frame_cache;     frame_cache = 0;
301         delete wave_cache;      wave_cache = 0;
302         delete plugin_guis;     plugin_guis = 0;
303         delete dead_plugins;    dead_plugins = 0;
304         delete keyframe_threads;  keyframe_threads = 0;
305         delete undo;            undo = 0;
306         delete preferences;     preferences = 0;
307         delete session;         session = 0;
308         delete defaults;        defaults = 0;
309         delete assets;          assets = 0;
310         delete splash_window;   splash_window = 0;
311         delete theme;           theme = 0;
312         delete_plugins();
313         delete channeldb_buz;
314         delete channeldb_v4l2jpeg;
315 // This must be last thread to exit
316         delete playback_3d;     playback_3d = 0;
317         delete dead_plugin_lock;
318         delete plugin_gui_lock;
319         delete vwindows_lock;
320         delete brender_lock;
321         delete keyframe_gui_lock;
322         sighandler->terminate();
323         delete sighandler;
324 }
325
326
327 void MWindow::quit(int unlock)
328 {
329         stop_playback(1);
330         if(unlock) gui->unlock_window();
331
332         brender_lock->lock("MWindow::quit");
333         delete brender;         brender = 0;
334         brender_lock->unlock();
335
336         interrupt_indexes();
337         clean_indexes();
338         save_defaults();
339         gui->set_done(0);
340         if(unlock) gui->lock_window("MWindow::quit");
341 }
342
343 void MWindow::init_error()
344 {
345         MainError::init_error(this);
346 }
347
348 void MWindow::finit_error()
349 {
350         MainError::finit_error();
351 }
352
353 void MWindow::create_defaults_path(char *string, const char *config_file)
354 {
355 // set the .bcast path
356         FileSystem fs;
357
358         sprintf(string, "%s", BCASTDIR);
359         fs.complete_path(string);
360         if(!fs.is_dir(string)) 
361                 fs.create_dir(string); 
362
363 // load the defaults
364         strcat(string, config_file);
365 }
366
367 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
368 {
369         char path[BCTEXTLEN];
370 // Use user supplied path
371         if(config_path[0])
372                 strcpy(path, config_path);
373         else
374                 create_defaults_path(path, CONFIG_FILE);
375
376         defaults = new BC_Hash(path);
377         defaults->load();
378 }
379
380 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
381 {
382         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
383         if( plug_dir ) {
384                 const char *dp = plug_dir;
385                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
386                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
387         }
388         strcpy(path, bp);
389         delete [] base_path;
390 }
391
392 int MWindow::load_plugin_index(MWindow *mwindow, const char *index_path, const char *plugin_dir)
393 {
394 // load index
395         FILE *fp = fopen(index_path, "r");
396         if( !fp ) return -1;
397
398         int ret = 0;
399         char index_line[BCTEXTLEN];
400         int index_version = -1, len = strlen(plugin_dir);
401         if( !fgets(index_line, BCTEXTLEN, fp) ||
402             sscanf(index_line, "%d", &index_version) != 1 ||
403             index_version != PLUGIN_FILE_VERSION ||
404             !fgets(index_line, BCTEXTLEN, fp) ||
405             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
406             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
407
408         ArrayList<PluginServer*> plugins;
409         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
410                 if( index_line[0] == ';' ) continue;
411                 if( index_line[0] == '#' ) continue;
412                 int type = PLUGIN_TYPE_UNKNOWN;
413                 char path[BCTEXTLEN], title[BCTEXTLEN];
414                 int64_t mtime = 0;
415                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
416                         ret = 1; continue;
417                 }
418                 PluginServer *server = 0;
419                 switch( type ) {
420                 case PLUGIN_TYPE_BUILTIN:
421                 case PLUGIN_TYPE_EXECUTABLE:
422                 case PLUGIN_TYPE_LADSPA: {
423                         char plugin_path[BCTEXTLEN];  struct stat st;
424                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
425                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
426                                 ret = 1; continue;
427                         }
428                         server = new PluginServer(mwindow, plugin_path, type);
429                         break; }
430                 case PLUGIN_TYPE_FFMPEG: {
431                         server = new_ffmpeg_server(mwindow, path);
432                         break; }
433                 }
434                 if( !server ) continue;
435                 plugins.append(server);
436 // Create plugin server from index entry
437                 server->set_title(title);
438                 if( server->read_table(index_line) ) {
439                         ret = 1;  continue;
440                 }
441         }
442         fclose(fp);
443
444         if( !ret )
445                 ret = check_plugin_index(plugins, plugin_dir, ".");
446
447         if( !ret )
448                 add_plugins(plugins);
449         else
450                 plugins.remove_all_objects();
451
452         return ret;
453 }
454
455 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
456         const char *plug_dir, const char *plug_path)
457 {
458         char plugin_path[BCTEXTLEN];
459         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
460         FileSystem fs;
461         fs.set_filter( "[*.plugin][*.so]" );
462         if( fs.update(plugin_path) )
463                 return 1;
464
465         for( int i=0; i<fs.dir_list.total; ++i ) {
466                 char fs_path[BCTEXTLEN];
467                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
468                 if( fs.is_dir(fs_path) ) {
469                         get_plugin_path(plugin_path, plug_dir, fs_path);
470                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
471                                 return 1;
472                 }
473                 else if( !plugin_exists(fs_path, plugins) )
474                         return 1;
475         }
476         return 0;
477 }
478
479
480 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
481 {
482         if( !plugindb )
483                 plugindb = new ArrayList<PluginServer*>;
484         init_ffmpeg();
485         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
486         create_defaults_path(index_path, PLUGIN_FILE);
487         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
488         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
489         if( !load_plugin_index(mwindow, index_path, plugin_path) ) return 1;
490         printf("init plugin index: %s\n", plugin_path);
491         FILE *fp = fopen(index_path,"w");
492         if( !fp ) {
493                 fprintf(stderr,_("MWindow::init_plugins: "
494                         "can't create plugin index: %s\n"), index_path);
495                 return 1;
496         }
497         fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
498         fprintf(fp, "%s\n", plugin_path);
499         init_plugin_index(mwindow, preferences, fp, plugin_path);
500         init_ffmpeg_index(mwindow, preferences, fp);
501         fclose(fp);
502         return load_plugin_index(mwindow, index_path, plugin_path);
503 }
504
505 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
506 {
507         char *path = getenv("LADSPA_PATH");
508         char ladspa_path[BCTEXTLEN];
509         if( !path ) {
510                 get_exe_path(ladspa_path);
511                 strcat(ladspa_path, "/ladspa");
512                 path = ladspa_path;
513         }
514         for( int len=0; *path; path+=len ) {
515                 char *cp = strchr(path,':');
516                 len = !cp ? strlen(path) : cp-path;
517                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
518                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
519                 char *plugin_dir = FileSystem::basepath(plugin_path);
520                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
521                 create_defaults_path(index_path, LADSPA_FILE);
522                 cp = index_path + strlen(index_path);
523                 for( char *bp=plugin_path; *bp!=0; ++bp )
524                         *cp++ = *bp=='/' ? '_' : *bp;
525                 *cp = 0;
526                 if( !load_plugin_index(mwindow, index_path, plugin_path) ) continue;
527                 if( init_ladspa_index(mwindow, preferences, index_path, plugin_path) ) continue;
528                 load_plugin_index(mwindow, index_path, plugin_path);
529         }
530         return 1;
531 }
532
533 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
534         FILE *fp, const char *plugin_dir)
535 {
536         int idx = PLUGIN_IDS;
537         if( plugindb ) {
538                 for( int i=0; i<plugindb->size(); ++i ) {
539                         PluginServer *server = plugindb->get(i);
540                         if( server->dir_idx >= idx )
541                                 idx = server->dir_idx+1;
542                 }
543         }
544         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
545 }
546
547 int MWindow::init_ladspa_index(MWindow *mwindow, Preferences *preferences,
548         const char *index_path, const char *plugin_dir)
549 {
550         char plugin_path[BCTEXTLEN], *path = FileSystem::basepath(plugin_dir);
551         strcpy(plugin_path, path);  delete [] path;
552         printf("init ladspa index: %s\n", plugin_dir);
553         FILE *fp = fopen(index_path,"w");
554         if( !fp ) {
555                 fprintf(stderr,_("MWindow::init_ladspa_index: "
556                         "can't create plugin index: %s\n"), index_path);
557                 return 1;
558         }
559         fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
560         fprintf(fp, "%s\n", plugin_dir);
561         init_plugin_index(mwindow, preferences, fp, plugin_path);
562         fclose(fp);
563         return 0;
564 }
565
566 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
567         const char *plug_dir, const char *plug_path, int &idx)
568 {
569         char plugin_path[BCTEXTLEN];
570         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
571         FileSystem fs;
572         fs.set_filter( "[*.plugin][*.so]" );
573         int result = fs.update(plugin_path);
574         if( result || !fs.dir_list.total ) return;
575         int vis_id = idx++;
576
577         for( int i=0; i<fs.dir_list.total; ++i ) {
578                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
579                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
580                 get_plugin_path(path, plug_dir, fs_path);
581                 if( fs.is_dir(fs_path) ) {
582                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
583                         continue;
584                 }
585                 if( plugin_exists(path) ) continue;
586                 struct stat st;
587                 if( stat(fs_path, &st) ) continue;
588                 int64_t mtime = st.st_mtime;
589                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
590                 result = server.open_plugin(1, preferences, 0, 0);
591                 if( !result ) {
592                         server.write_table(fp, path, vis_id, mtime);
593                         server.close_plugin();
594                 }
595                 else if( result == PLUGINSERVER_IS_LAD ) {
596                         int lad_index = 0;
597                         for(;;) {
598                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
599                                 ladspa.set_lad_index(lad_index++);
600                                 result = ladspa.open_plugin(1, preferences, 0, 0);
601                                 if( result ) break;
602                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
603                                 ladspa.close_plugin();
604                         }
605                 }
606         }
607 }
608
609 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
610 {
611         for( int i=0; i<plugins.size(); ++i )
612                 plugindb->append(plugins[i]);
613         plugins.remove_all();
614 }
615
616 void MWindow::delete_plugins()
617 {
618         plugindb->remove_all_objects();
619         delete plugindb;
620         plugindb = 0;
621 }
622
623 void MWindow::search_plugindb(int do_audio, 
624                 int do_video, 
625                 int is_realtime, 
626                 int is_transition,
627                 int is_theme,
628                 ArrayList<PluginServer*> &results)
629 {
630 // Get plugins
631         for(int i = 0; i < MWindow::plugindb->total; i++)
632         {
633                 PluginServer *current = MWindow::plugindb->get(i);
634
635                 if(current->audio == do_audio &&
636                         current->video == do_video &&
637                         (current->realtime == is_realtime || is_realtime < 0) &&
638                         current->transition == is_transition &&
639                         current->theme == is_theme)
640                         results.append(current);
641         }
642
643 // Alphabetize list by title
644         int done = 0;
645         while(!done)
646         {
647                 done = 1;
648                 
649                 for(int i = 0; i < results.total - 1; i++)
650                 {
651                         PluginServer *value1 = results[i];
652                         PluginServer *value2 = results[i + 1];
653                         if(strcmp(_(value1->title), _(value2->title)) > 0)
654                         {
655                                 done = 0;
656                                 results[i] = value2;
657                                 results[i + 1] = value1;
658                         }
659                 }
660         }
661 }
662
663 PluginServer* MWindow::scan_plugindb(char *title,
664                 int data_type)
665 {
666 //      if(data_type < 0)
667 //      {
668 //              printf("MWindow::scan_plugindb data_type < 0\n");
669 //              return 0;
670 //      }
671
672         for(int i = 0; i < plugindb->total; i++)
673         {
674                 PluginServer *server = plugindb->get(i);
675                 if(server->title &&
676                         !strcasecmp(server->title, title) &&
677                         (data_type < 0 ||
678                                 (data_type == TRACK_AUDIO && server->audio) ||
679                                 (data_type == TRACK_VIDEO && server->video))) 
680                         return plugindb->get(i);
681         }
682         return 0;
683 }
684
685 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
686 {
687         for( int i=0; i<plugins.size(); ++i )
688                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
689         return 0;
690 }
691
692 int MWindow::plugin_exists(char *plugin_path)
693 {
694         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
695 }
696
697 void MWindow::init_preferences()
698 {
699         preferences = new Preferences;
700         preferences->load_defaults(defaults);
701         session = new MainSession(this);
702         session->load_defaults(defaults);
703         // set x11_host, screens, window_config
704         screens = session->set_default_x11_host();
705         BC_Signals::set_trap_path("/tmp/cinelerra_%d.dmp");
706         BC_Signals::set_trap_hook(trap_hook, this);
707         BC_Signals::set_catch_segv(preferences->trap_sigsegv);
708         BC_Signals::set_catch_intr(preferences->trap_sigintr);
709 }
710
711 void MWindow::clean_indexes()
712 {
713         FileSystem fs;
714         int total_excess;
715         long oldest = 0;
716         int oldest_item = -1;
717         int result;
718         char string[BCTEXTLEN];
719         char string2[BCTEXTLEN];
720
721 // Delete extra indexes
722         fs.set_filter("*.idx");
723         fs.complete_path(preferences->index_directory);
724         fs.update(preferences->index_directory);
725 //printf("MWindow::clean_indexes 1 %d\n", fs.dir_list.total);
726
727 // Eliminate directories
728         result = 1;
729         while(result)
730         {
731                 result = 0;
732                 for(int i = 0; i < fs.dir_list.total && !result; i++)
733                 {
734                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
735                         if(fs.is_dir(string))
736                         {
737                                 delete fs.dir_list[i];
738                                 fs.dir_list.remove_number(i);
739                                 result = 1;
740                         }
741                 }
742         }
743         total_excess = fs.dir_list.total - preferences->index_count;
744
745 //printf("MWindow::clean_indexes 2 %d\n", fs.dir_list.total);
746         while(total_excess > 0)
747         {
748 // Get oldest
749                 for(int i = 0; i < fs.dir_list.total; i++)
750                 {
751                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
752
753                         if(i == 0 || fs.get_date(string) <= oldest)
754                         {
755                                 oldest = fs.get_date(string);
756                                 oldest_item = i;
757                         }
758                 }
759
760                 if(oldest_item >= 0)
761                 {
762 // Remove index file
763                         fs.join_names(string, 
764                                 preferences->index_directory, 
765                                 fs.dir_list[oldest_item]->name);
766 //printf("MWindow::clean_indexes 1 %s\n", string);
767                         if(remove(string))
768                                 perror("delete_indexes");
769                         delete fs.dir_list[oldest_item];
770                         fs.dir_list.remove_number(oldest_item);
771
772 // Remove table of contents if it exists
773                         strcpy(string2, string);
774                         char *ptr = strrchr(string2, '.');
775                         if(ptr)
776                         {
777 //printf("MWindow::clean_indexes 2 %s\n", string2);
778                                 sprintf(ptr, ".toc");
779                                 remove(string2);
780                                 sprintf(ptr, ".mkr");
781                                 remove(string2);
782                         }
783                 }
784
785                 total_excess--;
786         }
787 }
788
789 void MWindow::init_awindow()
790 {
791         awindow = new AWindow(this);
792         awindow->create_objects();
793 }
794
795 void MWindow::init_gwindow()
796 {
797         gwindow = new GWindow(this);
798         gwindow->create_objects();
799 }
800
801 void MWindow::init_tipwindow()
802 {
803         if( !twindow )
804                 twindow = new TipWindow(this);
805         twindow->start();
806 }
807
808 void MWindow::show_warning(int *do_warning, const char *text)
809 {
810         if( do_warning && !*do_warning ) return;
811         if( !wwindow )
812                 wwindow = new WWindow(this);
813         wwindow->show_warning(do_warning, text);
814 }
815
816 void MWindow::init_theme()
817 {
818         Timer timer;
819         theme = 0;
820
821         PluginServer *theme_plugin = 0;
822         for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
823                 if( plugindb->get(i)->theme &&
824                     !strcasecmp(preferences->theme, plugindb->get(i)->title) )
825                         theme_plugin = plugindb->get(i);
826         }
827
828         if( !theme_plugin )
829                 fprintf(stderr, _("MWindow::init_theme: prefered theme %s not found.\n"),
830                          preferences->theme);
831
832         if( !theme_plugin && strcasecmp(preferences->theme, DEFAULT_THEME) ) {
833                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
834                         DEFAULT_THEME);
835                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
836                         if( plugindb->get(i)->theme &&
837                             !strcasecmp(DEFAULT_THEME, plugindb->get(i)->title) )
838                                 theme_plugin = plugindb->get(i);
839                 }
840         }
841
842         if(!theme_plugin) {
843                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
844                 exit(1);
845         }
846
847         PluginServer *plugin = new PluginServer(*theme_plugin);
848         if( plugin->open_plugin(0, preferences, 0, 0) ) {
849                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
850                         theme_plugin->title);
851                 exit(1);
852         }
853
854         theme = plugin->new_theme();
855         theme->mwindow = this;
856         strcpy(theme->path, plugin->path);
857         delete plugin;
858
859 // Load default images & settings
860         theme->Theme::initialize();
861 // Load user images & settings
862         theme->initialize();
863 // Create menus with user colors
864         theme->build_menus();
865         init_menus();
866
867         theme->check_used();
868
869 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
870 }
871
872 void MWindow::init_3d()
873 {
874         playback_3d = new Playback3D(this);
875         playback_3d->create_objects();
876 }
877
878 void MWindow::init_edl()
879 {
880         edl = new EDL;
881         edl->create_objects();
882         edl->load_defaults(defaults);
883         edl->create_default_tracks();
884         edl->tracks->update_y_pixels(theme);
885 }
886
887 void MWindow::init_compositor()
888 {
889         cwindow = new CWindow(this);
890         cwindow->create_objects();
891 }
892
893 void MWindow::init_levelwindow()
894 {
895         lwindow = new LevelWindow(this);
896         lwindow->create_objects();
897 }
898
899 VWindow *MWindow::get_viewer(int start_it, int idx)
900 {
901         vwindows_lock->lock("MWindow::get_viewer");
902         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
903         if( !vwindow ) idx = vwindows.size();
904         while( !vwindow && --idx >= 0 ) {
905                 VWindow *vwin = vwindows[idx];
906                 if( !vwin->is_running() || !vwin->get_edl() )
907                         vwindow = vwin;
908         }
909         if( !vwindow ) {
910                 vwindow = new VWindow(this);
911                 vwindow->load_defaults();
912                 vwindow->create_objects();
913                 vwindows.append(vwindow);
914         }
915         vwindows_lock->unlock();
916         if( start_it ) vwindow->start();
917         return vwindow;
918 }
919
920 void MWindow::init_cache()
921 {
922         audio_cache = new CICache(preferences);
923         video_cache = new CICache(preferences);
924         frame_cache = new FrameCache;
925         wave_cache = new WaveCache;
926 }
927
928 void MWindow::init_channeldb()
929 {
930         channeldb_buz->load("channeldb_buz");
931         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
932 }
933
934 void MWindow::init_menus()
935 {
936         char string[BCTEXTLEN];
937         BC_CModels::to_text(string, BC_RGB888);
938         colormodels.append(new ColormodelItem(string, BC_RGB888));
939         BC_CModels::to_text(string, BC_RGBA8888);
940         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
941 //      BC_CModels::to_text(string, BC_RGB161616);
942 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
943 //      BC_CModels::to_text(string, BC_RGBA16161616);
944 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
945         BC_CModels::to_text(string, BC_RGB_FLOAT);
946         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
947         BC_CModels::to_text(string, BC_RGBA_FLOAT);
948         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
949         BC_CModels::to_text(string, BC_YUV888);
950         colormodels.append(new ColormodelItem(string, BC_YUV888));
951         BC_CModels::to_text(string, BC_YUVA8888);
952         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
953 //      BC_CModels::to_text(string, BC_YUV161616);
954 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
955 //      BC_CModels::to_text(string, BC_YUVA16161616);
956 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
957 }
958
959 void MWindow::init_indexes()
960 {
961         mainindexes = new MainIndexes(this);
962         mainindexes->start_loop();
963 }
964
965 void MWindow::init_gui()
966 {
967         gui = new MWindowGUI(this);
968         gui->lock_window("MWindow::init_gui");
969         gui->create_objects();
970         gui->unlock_window();
971         gui->load_defaults(defaults);
972 }
973
974 void MWindow::init_signals()
975 {
976         sighandler = new SigHandler;
977         sighandler->initialize();
978 ENABLE_BUFFER
979 }
980
981 void MWindow::init_render()
982 {
983         render = new Render(this);
984         create_bd = new CreateBD_Thread(this);
985         create_dvd = new CreateDVD_Thread(this);
986         batch_render = new BatchRenderThread(this);
987 }
988
989 void MWindow::init_brender()
990 {
991         if(preferences->use_brender && !brender)
992         {
993                 brender_lock->lock("MWindow::init_brender 1");
994                 brender = new BRender(this);
995                 brender->initialize();
996                 session->brender_end = 0;
997                 brender_lock->unlock();
998         }
999         else
1000         if(!preferences->use_brender && brender)
1001         {
1002                 brender_lock->lock("MWindow::init_brender 2");
1003                 delete brender;
1004                 brender = 0;
1005                 session->brender_end = 0;
1006                 brender_lock->unlock();
1007         }
1008         if(brender) brender->restart(edl);
1009 }
1010
1011 void MWindow::restart_brender()
1012 {
1013 //printf("MWindow::restart_brender 1\n");
1014         if(brender) brender->restart(edl);
1015 }
1016
1017 void MWindow::stop_brender()
1018 {
1019         if(brender) brender->stop();
1020 }
1021
1022 int MWindow::brender_available(int position)
1023 {
1024         int result = 0;
1025         brender_lock->lock("MWindow::brender_available 1");
1026         if(brender)
1027         {
1028                 if(brender->map_valid)
1029                 {
1030                         brender->map_lock->lock("MWindow::brender_available 2");
1031                         if(position < brender->map_size &&
1032                                 position >= 0)
1033                         {
1034 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1035                                 if(brender->map[position] == BRender::RENDERED)
1036                                         result = 1;
1037                         }
1038                         brender->map_lock->unlock();
1039                 }
1040         }
1041         brender_lock->unlock();
1042         return result;
1043 }
1044
1045 void MWindow::set_brender_start()
1046 {
1047         edl->session->brender_start = edl->local_session->get_selectionstart(1);
1048         restart_brender();
1049         gui->draw_overlays(1);
1050 }
1051
1052
1053 int MWindow::has_commercials()
1054 {
1055         return theme->use_commercials;
1056 }
1057
1058 void MWindow::init_commercials()
1059 {
1060         if( !commercials ) {
1061                 commercials = new Commercials(this);
1062                 commercial_active = 0;
1063         }
1064         else
1065                 commercials->add_user();
1066 }
1067
1068 void MWindow::commit_commercial()
1069 {
1070         if( !commercial_active ) return;
1071         commercial_active = 0;
1072         if( !commercials ) return;
1073         commercials->commitDb();
1074 }
1075
1076 void MWindow::undo_commercial()
1077 {
1078         if( !commercial_active ) return;
1079         commercial_active = 0;
1080         if( !commercials ) return;
1081         commercials->undoDb();
1082 }
1083
1084 int MWindow::put_commercial()
1085 {
1086         double start = edl->local_session->get_selectionstart();
1087         double end = edl->local_session->get_selectionend();
1088         if( start >= end ) return 0;
1089
1090         const char *errmsg = 0;
1091         int count = 0;
1092         Tracks *tracks = edl->tracks;
1093         int result = 0;
1094         //check it
1095         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1096                 if( track->data_type != TRACK_VIDEO ) continue;
1097                 if( !track->record ) continue;
1098                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1099                 ++count;
1100                 int64_t units_start = track->to_units(start,0);
1101                 int64_t units_end = track->to_units(end,0);
1102                 Edits *edits = track->edits;
1103                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1104                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1105                 if(!edit1 && !edit2) continue;  // nothing selected
1106                 if(!edit2) {                    // edit2 beyond end of track
1107                         edit2 = edits->last;
1108                         units_end = edits->length();
1109                 }
1110                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1111                 Indexable *indexable = edit1->get_source();
1112                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1113         }
1114         //run it
1115         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1116                 if( track->data_type != TRACK_VIDEO ) continue;
1117                 if( !track->record ) continue;
1118                 int64_t units_start = track->to_units(start,0);
1119                 int64_t units_end = track->to_units(end,0);
1120                 Edits *edits = track->edits;
1121                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1122                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1123                 if(!edit1 && !edit2) continue;  // nothing selected
1124                 if(!edit2) {                    // edit2 beyond end of track
1125                         edit2 = edits->last;
1126                         units_end = edits->length();
1127                 }
1128                 Indexable *indexable = edit1->get_source();
1129                 Asset *asset = (Asset *)indexable;
1130                 File *file = video_cache->check_out(asset, edl);
1131                 if( !file ) { errmsg = _("no file"); break; }
1132                 int64_t edit_length = units_end - units_start;
1133                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1134                 result = commercials->put_clip(file, edit1->channel,
1135                         track->from_units(edit_start), track->from_units(edit_length));
1136                 video_cache->check_in(asset);
1137                 if( result ) { errmsg = _("db failed"); break; }
1138         }
1139         if( errmsg ) {
1140                 char string[BCTEXTLEN];
1141                 sprintf(string, _("put_commercial: %s"), errmsg);
1142                 MainError::show_error(string);
1143                 undo_commercial();
1144                 result = 1;
1145         }
1146         return result;
1147 }
1148
1149 void MWindow::stop_playback(int wait)
1150 {
1151         int locked  = gui->get_window_lock();
1152         if( locked ) gui->unlock_window();
1153
1154         cwindow->playback_engine->que->send_command(STOP,
1155                 CHANGE_NONE, 
1156                 0,
1157                 0);
1158         cwindow->playback_engine->interrupt_playback(wait);
1159
1160         for(int i = 0; i < vwindows.size(); i++) {
1161                 VWindow *vwindow = vwindows[i];
1162                 if( !vwindow->is_running() ) continue;
1163                 vwindow->playback_engine->que->send_command(STOP, CHANGE_NONE, 0, 0);
1164                 vwindow->playback_engine->interrupt_playback(wait);
1165         }
1166         if( locked ) gui->lock_window("MWindow::stop_playback");
1167 }
1168
1169 int MWindow::load_filenames(ArrayList<char*> *filenames, 
1170         int load_mode,
1171         int update_filename)
1172 {
1173         ArrayList<EDL*> new_edls;
1174         ArrayList<Asset*> new_assets;
1175         ArrayList<File*> new_files;
1176         const int debug = 0;
1177 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1178
1179 //      save_defaults();
1180         gui->start_hourglass();
1181
1182 // Need to stop playback since tracking depends on the EDL not getting
1183 // deleted.
1184         stop_playback(1);
1185
1186 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1187         undo->update_undo_before();
1188
1189
1190 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1191
1192 // Define new_edls and new_assets to load
1193         int result = 0, ftype = -1;
1194         for(int i = 0; i < filenames->size(); i++)
1195         {
1196 // Get type of file
1197                 File *new_file = new File;
1198                 Asset *new_asset = new Asset(filenames->get(i));
1199                 EDL *new_edl = new EDL;
1200                 char string[BCTEXTLEN];
1201
1202                 new_edl->create_objects();
1203                 new_edl->copy_session(edl);
1204                 new_file->set_program(edl->session->program_no);
1205
1206                 sprintf(string, _("Loading %s"), new_asset->path);
1207                 gui->show_message(string);
1208 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1209
1210                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1211 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1212
1213                 result = 1;
1214                 switch(ftype)
1215                 {
1216 // Convert media file to EDL
1217                         case FILE_OK:
1218 // Warn about odd image dimensions
1219                                 if(new_asset->video_data &&
1220                                         ((new_asset->width % 2) ||
1221                                         (new_asset->height % 2)))
1222                                 {
1223                                         char string[BCTEXTLEN];
1224                                         sprintf(string, _("%s's resolution is %dx%d.\nImages with odd dimensions may not decode properly."),
1225                                                 new_asset->path,
1226                                                 new_asset->width,
1227                                                 new_asset->height);
1228                                         MainError::show_error(string);
1229                                 }
1230
1231                                 if(new_asset->program >= 0 &&
1232                                         edl->session->program_no != new_asset->program)
1233                                 {
1234                                         char string[BCTEXTLEN];
1235                                         sprintf(string, _("%s's index was built for program number %d\n"
1236                                                 "Playback preference is %d.\n  Using program %d."),
1237                                                 new_asset->path, new_asset->program,
1238                                                 edl->session->program_no, new_asset->program);
1239                                         MainError::show_error(string);
1240                                 }
1241
1242
1243                                 if(load_mode != LOADMODE_RESOURCESONLY)
1244                                 {
1245 SET_TRACE
1246                                         RecordLabels *labels = edl->session->label_cells ?
1247                                                 new RecordLabels(new_file) : 0;
1248 SET_TRACE
1249                                         asset_to_edl(new_edl, new_asset, labels);
1250 SET_TRACE
1251                                         new_edls.append(new_edl);
1252 SET_TRACE
1253                                         new_asset->Garbage::remove_user();
1254                                         delete labels;
1255                                         new_asset = 0;
1256                                 }
1257                                 else
1258                                 {
1259                                         new_assets.append(new_asset);
1260                                         new_asset = 0;
1261                                 }
1262
1263 // Set filename to nothing for assets since save EDL would overwrite them.
1264                                 if(load_mode == LOADMODE_REPLACE || 
1265                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
1266                                 {
1267                                         set_filename("");
1268 // Reset timeline position
1269                                         for(int i = 0; i < TOTAL_PANES; i++)
1270                                         {
1271                                                 new_edl->local_session->view_start[i] = 0;
1272                                                 new_edl->local_session->track_start[i] = 0;
1273                                         }
1274                                 }
1275
1276                                 result = 0;
1277                                 break;
1278
1279 // File not found
1280                         case FILE_NOT_FOUND:
1281                                 sprintf(string, _("Failed to open %s"), new_asset->path);
1282                                 gui->show_message(string, theme->message_error);
1283                                 break;
1284
1285 // Unknown format
1286                         case FILE_UNRECOGNIZED_CODEC:
1287                         {
1288 // Test index file
1289                                 IndexFile indexfile(this, new_asset);
1290                                 result = indexfile.open_index();
1291                                 if(!result)
1292                                 {
1293                                         indexfile.close_index();
1294                                 }
1295
1296 // Test existing EDLs
1297                                 if(result)
1298                                 {
1299                                         for(int j = 0; j < new_edls.total + 1; j++)
1300                                         {
1301                                                 Asset *old_asset;
1302                                                 if(j == new_edls.total)
1303                                                 {
1304                                                         old_asset = edl->assets->get_asset(new_asset->path);
1305                                                         if( old_asset )
1306                                                         {
1307                                                                 *new_asset = *old_asset;
1308                                                                 result = 0;
1309                                                         }
1310                                                 }
1311                                                 else
1312                                                 {
1313                                                         old_asset = new_edls[j]->assets->get_asset(new_asset->path);
1314                                                         if( old_asset )
1315                                                         {
1316                                                                 *new_asset = *old_asset;
1317                                                                 result = 0;
1318                                                         }
1319                                                 }
1320                                         }
1321                                 }
1322
1323 // Prompt user
1324                                 if(result)
1325                                 {
1326                                         char string[BCTEXTLEN];
1327                                         FileSystem fs;
1328                                         fs.extract_name(string, new_asset->path);
1329
1330                                         strcat(string, _("'s format couldn't be determined."));
1331                                         new_asset->audio_data = 1;
1332                                         new_asset->format = FILE_PCM;
1333                                         new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
1334                                         new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
1335                                         new_asset->bits = defaults->get("AUDIO_BITS", 16);
1336                                         new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
1337                                         new_asset->signed_ = defaults->get("SIGNED_", 1);
1338                                         new_asset->header = defaults->get("HEADER", 0);
1339
1340                                         FileFormat fwindow(this);
1341                                         fwindow.create_objects(new_asset, string);
1342                                         result = fwindow.run_window();
1343
1344
1345                                         defaults->update("AUDIO_CHANNELS", new_asset->channels);
1346                                         defaults->update("SAMPLE_RATE", new_asset->sample_rate);
1347                                         defaults->update("AUDIO_BITS", new_asset->bits);
1348                                         defaults->update("BYTE_ORDER", new_asset->byte_order);
1349                                         defaults->update("SIGNED_", new_asset->signed_);
1350                                         defaults->update("HEADER", new_asset->header);
1351                                         save_defaults();
1352                                 }
1353
1354 // Append to list
1355                                 if(!result)
1356                                 {
1357 // Recalculate length
1358                                         delete new_file;
1359                                         new_file = new File;
1360                                         result = new_file->open_file(preferences, new_asset, 1, 0);
1361
1362                                         if(load_mode != LOADMODE_RESOURCESONLY)
1363                                         {
1364                                                 RecordLabels *labels = edl->session->label_cells ?
1365                                                         new RecordLabels(new_file) : 0;
1366                                                 asset_to_edl(new_edl, new_asset, labels);
1367                                                 new_edls.append(new_edl);
1368                                                 new_asset->Garbage::remove_user();
1369                                                 delete labels;
1370                                                 new_asset = 0;
1371                                         }
1372                                         else
1373                                         {
1374                                                 new_assets.append(new_asset);
1375                                                 new_asset = 0;
1376                                         }
1377                                 }
1378                                 else
1379                                 {
1380                                         result = 1;
1381                                 }
1382                                 break;
1383                         }
1384
1385                         case FILE_IS_XML:
1386                         {
1387                                 FileXML xml_file;
1388 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1389                                 xml_file.read_from_file(filenames->get(i));
1390 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1391
1392                                 if(load_mode == LOADMODE_NESTED)
1393                                 {
1394 // Load temporary EDL for nesting.
1395                                         EDL *nested_edl = new EDL;
1396                                         nested_edl->create_objects();
1397                                         nested_edl->set_path(filenames->get(i));
1398                                         nested_edl->load_xml(&xml_file, LOAD_ALL);
1399 //printf("MWindow::load_filenames %p %s\n", nested_edl, nested_edl->project_path);
1400                                         edl_to_nested(new_edl, nested_edl);
1401                                         nested_edl->Garbage::remove_user();
1402                                 }
1403                                 else
1404                                 {
1405 // Load EDL for pasting
1406                                         new_edl->load_xml(&xml_file, LOAD_ALL);
1407 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1408                                         test_plugins(new_edl, filenames->get(i));
1409 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1410
1411                                         if(load_mode == LOADMODE_REPLACE || 
1412                                                 load_mode == LOADMODE_REPLACE_CONCATENATE)
1413                                         {
1414                                                 strcpy(session->filename, filenames->get(i));
1415                                                 strcpy(new_edl->local_session->clip_title, 
1416                                                         filenames->get(i));
1417                                                 if(update_filename)
1418                                                         set_filename(new_edl->local_session->clip_title);
1419                                         }
1420                                 }               
1421
1422                                 new_edls.append(new_edl);
1423                                 result = 0;
1424                                 break;
1425                         }
1426                 }
1427
1428 // edls are in new_edls
1429                 if( result && new_edl ) new_edl->Garbage::remove_user();
1430 // assets are copied
1431                 if( new_asset ) new_asset->Garbage::remove_user();
1432
1433 // Store for testing index
1434                 new_files.append(new_file);
1435         }
1436
1437 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1438
1439
1440         if(!result) gui->statusbar->default_message();
1441
1442
1443
1444
1445
1446
1447
1448 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1449
1450 // Paste them.
1451 // Don't back up here.
1452         if(new_edls.size())
1453         {
1454 // For pasting, clear the active region
1455                 if(load_mode == LOADMODE_PASTE ||
1456                         load_mode == LOADMODE_NESTED)
1457                 {
1458                         double start = edl->local_session->get_selectionstart();
1459                         double end = edl->local_session->get_selectionend();
1460                         if(!EQUIV(start, end))
1461                                 edl->clear(start, 
1462                                         end,
1463                                         edl->session->labels_follow_edits,
1464                                         edl->session->plugins_follow_edits,
1465                                         edl->session->autos_follow_edits);
1466                 }
1467
1468                 paste_edls(&new_edls, 
1469                         load_mode,
1470                         0,
1471                         -1,
1472                         edl->session->labels_follow_edits, 
1473                         edl->session->plugins_follow_edits,
1474                         edl->session->autos_follow_edits);
1475         }
1476
1477
1478
1479
1480 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1481
1482 // Add new assets to EDL and schedule assets for index building.
1483         int got_indexes = 0;
1484         for(int i = 0; i < new_edls.size(); i++)
1485         {
1486                 EDL *new_edl = new_edls[i];
1487                 for(int j = 0; j < new_edl->nested_edls->size(); j++)
1488                 {
1489                         mainindexes->add_next_asset(0, 
1490                                 new_edl->nested_edls->get(j));
1491                         got_indexes = 1;
1492                         edl->nested_edls->update_index(new_edl->nested_edls->get(j));
1493                 }
1494
1495         }
1496
1497 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1498         if(new_assets.size())
1499         {
1500                 for(int i = 0; i < new_assets.size(); i++)
1501                 {
1502                         Asset *new_asset = new_assets[i];
1503
1504                         File *new_file = 0;
1505                         int got_it = 0;
1506                         for(int j = 0; j < new_files.size(); j++)
1507                         {
1508                                 new_file = new_files[j];
1509                                 if(!strcmp(new_file->asset->path,
1510                                         new_asset->path))
1511                                 {
1512                                         got_it = 1;
1513                                         break;
1514                                 }
1515                         }
1516
1517                         mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
1518                         got_indexes = 1;
1519                         edl->assets->update(new_asset);
1520
1521                 }
1522
1523
1524         }
1525 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1526
1527 // Start examining next batch of index files
1528         if(got_indexes) mainindexes->start_build();
1529 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1530
1531 // Open plugin GUIs
1532         Track *track = edl->tracks->first;
1533         while(track)
1534         {
1535                 for(int j = 0; j < track->plugin_set.size(); j++)
1536                 {
1537                         PluginSet *plugins = track->plugin_set[j];
1538                         Plugin *plugin = plugins->get_first_plugin();
1539
1540                         while(plugin)
1541                         {
1542                                 if(load_mode == LOADMODE_REPLACE ||
1543                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
1544                                 {
1545                                         if(plugin->plugin_type == PLUGIN_STANDALONE &&
1546                                                 plugin->show)
1547                                         {
1548                                                 show_plugin(plugin);
1549                                         }
1550                                 }
1551                                 else
1552                                 {
1553                                         plugin->show = 0;
1554                                 }
1555
1556                                 plugin = (Plugin*)plugin->next;
1557                         }
1558                 }
1559
1560                 track = track->next;
1561         }
1562
1563         // if just opening one new resource in replace mode
1564         if( load_mode == LOADMODE_REPLACE && new_edls.size() == 1 &&
1565                 ftype != FILE_IS_XML )
1566         {
1567                 select_asset(0, 0);
1568                 edl->local_session->preview_start = 0;
1569                 edl->local_session->preview_end = edl->tracks->total_playable_length();
1570                 edl->local_session->loop_playback = 0;
1571                 edl->local_session->set_selectionstart(0);
1572                 edl->local_session->set_selectionend(0);
1573                 fit_selection();
1574                 goto_start();
1575         }
1576
1577 // need to update undo before project, since mwindow is unlocked & a new load
1578 // can begin here.  Should really prevent loading until we're done.
1579 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1580         undo->update_undo_after(_("load"), LOAD_ALL);
1581
1582         for(int i = 0; i < new_edls.size(); i++)
1583         {
1584                 new_edls[i]->remove_user();
1585         }
1586 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1587
1588         new_edls.remove_all();
1589
1590         for(int i = 0; i < new_assets.size(); i++)
1591         {
1592                 new_assets[i]->Garbage::remove_user();
1593         }
1594
1595         new_assets.remove_all();
1596         new_files.remove_all_objects();
1597
1598
1599 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1600         if(load_mode == LOADMODE_REPLACE ||
1601                 load_mode == LOADMODE_REPLACE_CONCATENATE)
1602         {
1603                 session->changes_made = 0;
1604         }
1605         else
1606         {
1607                 session->changes_made = 1;
1608         }
1609
1610         gui->stop_hourglass();
1611
1612
1613 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1614         update_project(load_mode);
1615
1616 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1617
1618         return 0;
1619 }
1620
1621
1622
1623
1624 void MWindow::test_plugins(EDL *new_edl, char *path)
1625 {
1626         char string[BCTEXTLEN];
1627
1628 // Do a check weather plugins exist
1629         for(Track *track = new_edl->tracks->first; track; track = track->next)
1630         {
1631                 for(int k = 0; k < track->plugin_set.total; k++)
1632                 {
1633                         PluginSet *plugin_set = track->plugin_set[k];
1634                         for(Plugin *plugin = (Plugin*)plugin_set->first; 
1635                                 plugin; 
1636                                 plugin = (Plugin*)plugin->next)
1637                         {
1638                                 if(plugin->plugin_type == PLUGIN_STANDALONE)
1639                                 {
1640 // ok we need to find it in plugindb
1641                                         int plugin_found = 0;
1642
1643                                         for(int j = 0; j < plugindb->size(); j++)
1644                                         {
1645                                                 PluginServer *server = plugindb->get(j);
1646                                                 if(server->title &&
1647                                                         !strcasecmp(server->title, plugin->title) &&
1648                                                         ((track->data_type == TRACK_AUDIO && server->audio) ||
1649                                                         (track->data_type == TRACK_VIDEO && server->video)) &&
1650                                                         (!server->transition))
1651                                                         plugin_found = 1;
1652                                         }
1653
1654                                         if (!plugin_found) 
1655                                         {
1656                                                 sprintf(string, 
1657         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
1658           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
1659                                                         "effect", plugin->title, 
1660                                                         path); 
1661                                                 MainError::show_error(string);
1662                                         }
1663                                 }
1664                         }
1665                 }
1666
1667                 for(Edit *edit = (Edit*)track->edits->first; 
1668                         edit; 
1669                         edit = (Edit*)edit->next)
1670                 {
1671                         if (edit->transition)
1672                         {
1673 // ok we need to find transition in plugindb
1674
1675                                 int transition_found = 0;
1676                                 for(int j = 0; j < plugindb->size(); j++)
1677                                 {
1678                                         PluginServer *server = plugindb->get(j);
1679                                         if(server->title &&
1680                                                 !strcasecmp(server->title, edit->transition->title) &&
1681                                                 ((track->data_type == TRACK_AUDIO && server->audio) ||
1682                                                 (track->data_type == TRACK_VIDEO && server->video)) &&
1683                                                 (server->transition))
1684                                                 transition_found = 1;
1685                                 }
1686
1687                                 if (!transition_found) 
1688                                 {
1689                                         sprintf(string, 
1690         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
1691           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
1692                                                 "transition", edit->transition->title, 
1693                                                 path); 
1694                                         MainError::show_error(string);
1695                                 }
1696                         }
1697                 }
1698         }
1699 }
1700
1701
1702 void MWindow::init_shm()
1703 {
1704 // Fix shared memory
1705         FILE *fd = fopen("/proc/sys/kernel/shmmax", "w");
1706         if(fd) {
1707                 fprintf(fd, "0x7fffffff");
1708                 fclose(fd);
1709         }
1710         fd = 0;
1711
1712         fd = fopen("/proc/sys/kernel/shmmax", "r");
1713         if(!fd) {
1714                 MainError::show_error("MWindow::init_shm: couldn't open /proc/sys/kernel/shmmax for reading.\n");
1715                 return;
1716         }
1717
1718         int64_t result = 0;
1719         fscanf(fd, _LD, &result);
1720         fclose(fd);
1721         fd = 0;
1722         if(result < 0x7fffffff) {
1723                 char string[BCTEXTLEN];
1724                 sprintf(string, _("MWindow::init_shm: /proc/sys/kernel/shmmax is 0x" _LX ".\n"
1725                         "you probably need to be root, or:\n"
1726                         "as root, run: echo 0x7fffffff > /proc/sys/kernel/shmmax\n"
1727                         "before trying to start cinelerra.\n"
1728                         "It should be at least 0x7fffffff for Cinelerra.\n"), result);
1729                 MainError::show_error(string);
1730         }
1731 }
1732
1733
1734 void MWindow::create_objects(int want_gui, 
1735         int want_new,
1736         char *config_path)
1737 {
1738         FileSystem fs;
1739         const int debug = 0;
1740         if(debug) PRINT_TRACE
1741
1742 // For some reason, init_signals must come after show_splash or the signals won't
1743 // get trapped.
1744         init_signals();
1745         if(debug) PRINT_TRACE
1746         init_3d();
1747
1748         if(debug) PRINT_TRACE
1749         show_splash();
1750
1751         if(debug) PRINT_TRACE
1752         init_defaults(defaults, config_path);
1753         init_preferences();
1754         if(splash_window)
1755                 splash_window->operation->update(_("Initializing Plugins"));
1756         init_plugins(this, preferences);
1757         if(debug) PRINT_TRACE
1758         init_ladspa_plugins(this, preferences);
1759         if(debug) PRINT_TRACE
1760         if(splash_window)
1761                 splash_window->operation->update(_("Initializing GUI"));
1762         if(debug) PRINT_TRACE
1763         init_theme();
1764         if(debug) PRINT_TRACE
1765         init_error();
1766
1767         if(splash_window)
1768                 splash_window->operation->update(_("Initializing Fonts"));
1769         char string[BCTEXTLEN];
1770         strcpy(string, preferences->plugin_dir);
1771         strcat(string, "/fonts");
1772         BC_Resources::init_fontconfig(string);
1773         if(debug) PRINT_TRACE
1774
1775 // Initialize before too much else is running
1776 // Preferences & theme are required for building MPEG table of contents
1777
1778 // Default project created here
1779         init_edl();
1780         if(debug) PRINT_TRACE
1781
1782         init_cache();
1783         if(debug) PRINT_TRACE
1784
1785         Timer timer;
1786
1787         init_compositor();
1788         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1789
1790 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
1791         if(session->show_vwindow)
1792                 get_viewer(1, DEFAULT_VWINDOW);
1793         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1794
1795         init_gui();
1796         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1797
1798         init_awindow();
1799         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1800
1801         init_levelwindow();
1802         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1803
1804         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1805
1806         init_indexes();
1807         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1808
1809         init_channeldb();
1810
1811         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1812         init_gwindow();
1813         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1814         init_render();
1815         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1816         init_brender();
1817         init_commercials();
1818         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1819         mainprogress = new MainProgress(this, gui);
1820         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1821         undo = new MainUndo(this);
1822
1823         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1824
1825         plugin_guis = new ArrayList<PluginServer*>;
1826         dead_plugins = new ArrayList<PluginServer*>;
1827         keyframe_threads = new ArrayList<KeyFrameThread*>;
1828
1829         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n", 
1830                 __LINE__, 
1831                 vwindows.size(),
1832                 session->show_vwindow);
1833
1834 // Show all vwindows
1835 //      if(session->show_vwindow) {
1836 //              for(int j = 0; j < vwindows.size(); j++) {
1837 //                      VWindow *vwindow = vwindows[j];
1838 //                      if( !vwindow->is_running() ) continue;
1839 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n", 
1840 //                              __LINE__, 
1841 //                              vwindow);
1842 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1843 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
1844 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1845 //                      vwindow->gui->show_window();
1846 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1847 //                      vwindow->gui->unlock_window();
1848 //              }
1849 //      }
1850
1851
1852         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1853
1854         if(session->show_cwindow) 
1855         {
1856                 cwindow->gui->lock_window("MWindow::create_objects 1");
1857                 cwindow->gui->show_window();
1858                 cwindow->gui->unlock_window();
1859         }
1860
1861         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1862         if(session->show_awindow)
1863         {
1864                 awindow->gui->lock_window("MWindow::create_objects 1");
1865                 awindow->gui->show_window();
1866                 awindow->gui->unlock_window();
1867         }
1868
1869         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1870         if(session->show_lwindow)
1871         {
1872                 lwindow->gui->lock_window("MWindow::create_objects 1");
1873                 lwindow->gui->show_window();
1874                 lwindow->gui->unlock_window();
1875         }
1876
1877         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n", 
1878                 __LINE__, 
1879                 (int)timer.get_difference(),
1880                 gwindow->gui);
1881         if(session->show_gwindow)
1882         {
1883                 gwindow->gui->lock_window("MWindow::create_objects 1");
1884                 gwindow->gui->show_window();
1885                 gwindow->gui->unlock_window();
1886         }
1887
1888         if(debug) PRINT_TRACE
1889
1890         gui->lock_window("MWindow::create_objects 1");
1891         gui->mainmenu->load_defaults(defaults);
1892         gui->mainmenu->update_toggles(0);
1893         gui->update_patchbay();
1894         gui->draw_canvas(0, 0);
1895         gui->draw_cursor(1);
1896         gui->show_window();
1897         gui->raise_window();
1898         gui->unlock_window();
1899
1900         if(debug) PRINT_TRACE
1901
1902
1903
1904         if(preferences->use_tipwindow)
1905                 init_tipwindow();
1906         if(debug) PRINT_TRACE
1907
1908         gui->add_keyboard_listener(
1909                 (int (BC_WindowBase::*)(BC_WindowBase *))
1910                 &MWindowGUI::keyboard_listener);
1911
1912         hide_splash();
1913         init_shm();
1914         if(debug) PRINT_TRACE
1915
1916         BC_WindowBase::get_resources()->vframe_shm = 1;
1917
1918 }
1919
1920
1921 void MWindow::show_splash()
1922 {
1923 #include "data/heroine_logo9_png.h"
1924         VFrame *frame = new VFramePng(heroine_logo9_png);
1925         BC_DisplayInfo dpyi;
1926         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
1927         int rr = (rw < rh ? rw : rh) / 4;
1928         splash_window = new SplashGUI(frame, rr, rr);
1929         splash_window->create_objects();
1930 }
1931
1932 void MWindow::hide_splash()
1933 {
1934         if(splash_window)
1935                 delete splash_window;
1936         splash_window = 0;
1937 }
1938
1939
1940 void MWindow::start()
1941 {
1942 ENABLE_BUFFER
1943 //PRINT_TRACE
1944 //      vwindows[DEFAULT_VWINDOW]->start();
1945         awindow->start();
1946 //PRINT_TRACE
1947         cwindow->start();
1948 //PRINT_TRACE
1949         lwindow->start();
1950 //PRINT_TRACE
1951         gwindow->start();
1952 //PRINT_TRACE
1953 //      Thread::start();
1954 //PRINT_TRACE
1955         playback_3d->start();
1956 //PRINT_TRACE
1957 }
1958
1959 void MWindow::run()
1960 {
1961         gui->run_window();
1962 }
1963
1964 void MWindow::show_vwindow()
1965 {
1966         int total_running = 0;
1967         session->show_vwindow = 1;
1968
1969 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
1970 // Raise all windows which are visible
1971         for(int j = 0; j < vwindows.size(); j++) {
1972                 VWindow *vwindow = vwindows[j];
1973                 if( !vwindow->is_running() ) continue;
1974                 vwindow->gui->lock_window("MWindow::show_vwindow");
1975                 vwindow->gui->show_window(0);
1976                 vwindow->gui->raise_window();
1977                 vwindow->gui->flush();
1978                 vwindow->gui->unlock_window();
1979                 total_running++;
1980         }
1981
1982 // If no windows visible
1983         if(!total_running)
1984         {
1985                 get_viewer(1, DEFAULT_VWINDOW);
1986         }
1987
1988         gui->mainmenu->show_vwindow->set_checked(1);
1989 }
1990
1991 void MWindow::show_awindow()
1992 {
1993         session->show_awindow = 1;
1994         awindow->gui->lock_window("MWindow::show_awindow");
1995         awindow->gui->show_window();
1996         awindow->gui->raise_window();
1997         awindow->gui->flush();
1998         awindow->gui->unlock_window();
1999         gui->mainmenu->show_awindow->set_checked(1);
2000 }
2001
2002 char *MWindow::get_cwindow_display()
2003 {
2004         char *x11_host = screens < 2 || session->window_config == 0 ?
2005                 session->a_x11_host : session->b_x11_host;
2006         return *x11_host ? x11_host : 0;
2007 }
2008
2009 void MWindow::show_cwindow()
2010 {
2011         session->show_cwindow = 1;
2012         cwindow->show_window();
2013         gui->mainmenu->show_cwindow->set_checked(1);
2014 }
2015
2016 void MWindow::show_gwindow()
2017 {
2018         session->show_gwindow = 1;
2019
2020         gwindow->gui->lock_window("MWindow::show_gwindow");
2021         gwindow->gui->show_window();
2022         gwindow->gui->raise_window();
2023         gwindow->gui->flush();
2024         gwindow->gui->unlock_window();
2025
2026         gui->mainmenu->show_gwindow->set_checked(1);
2027 }
2028
2029 void MWindow::show_lwindow()
2030 {
2031         session->show_lwindow = 1;
2032         lwindow->gui->lock_window("MWindow::show_lwindow");
2033         lwindow->gui->show_window();
2034         lwindow->gui->raise_window();
2035         lwindow->gui->flush();
2036         lwindow->gui->unlock_window();
2037         gui->mainmenu->show_lwindow->set_checked(1);
2038 }
2039
2040 int MWindow::tile_windows(int window_config)
2041 {
2042         int need_reload = 0;
2043         int play_config = window_config==0 ? 0 : 1;
2044         edl->session->playback_config->load_defaults(defaults, play_config);
2045         session->default_window_positions(window_config);
2046         if( screens == 1 ) {
2047                 gui->default_positions();
2048                 sync_parameters(CHANGE_ALL);
2049         }
2050         else
2051                 need_reload = 1;
2052         return need_reload;
2053 }
2054
2055 void MWindow::toggle_loop_playback()
2056 {
2057         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2058         set_loop_boundaries();
2059         save_backup();
2060
2061         gui->draw_overlays(1);
2062         sync_parameters(CHANGE_PARAMS);
2063 }
2064
2065 //void MWindow::set_titles(int value)
2066 //{
2067 //      edl->session->show_titles = value;
2068 //      trackmovement(edl->local_session->track_start);
2069 //}
2070
2071 void MWindow::set_screens(int value)
2072 {
2073         screens = value;
2074 }
2075
2076 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2077 {
2078         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2079         edl->session->auto_keyframes = value;
2080         gui->mbuttons->edit_panel->keyframe->update(value);
2081         gui->flush();
2082         if(lock_mwindow) gui->unlock_window();
2083
2084         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2085         cwindow->gui->edit_panel->keyframe->update(value);
2086         cwindow->gui->flush();
2087         if(lock_cwindow) cwindow->gui->unlock_window();
2088 }
2089
2090 void MWindow::set_keyframe_type(int mode)
2091 {
2092         gui->lock_window("MWindow::set_keyframe_type");
2093         edl->local_session->floatauto_type = mode;
2094         gui->mainmenu->update_toggles(0);
2095         gui->unlock_window();
2096 }
2097
2098 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
2099 {
2100         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
2101         edl->session->editing_mode = new_editing_mode;
2102         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
2103         gui->mbuttons->edit_panel->update();
2104         gui->set_editing_mode(1);
2105         if(lock_mwindow) gui->unlock_window();
2106
2107
2108         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
2109         cwindow->gui->edit_panel->update();
2110         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
2111         if(lock_cwindow) cwindow->gui->unlock_window();
2112         return 0;
2113 }
2114
2115
2116 void MWindow::sync_parameters(int change_type)
2117 {
2118         if( in_destructor ) return;
2119
2120 // Sync engines which are playing back
2121         if(cwindow->playback_engine->is_playing_back)
2122         {
2123                 if(change_type == CHANGE_PARAMS)
2124                 {
2125 // TODO: block keyframes until synchronization is done
2126                         cwindow->playback_engine->sync_parameters(edl);
2127                 }
2128                 else
2129 // Stop and restart
2130                 {
2131                         int command = cwindow->playback_engine->command->command;
2132                         cwindow->playback_engine->que->send_command(STOP,
2133                                 CHANGE_NONE, 
2134                                 0,
2135                                 0);
2136 // Waiting for tracking to finish would make the restart position more
2137 // accurate but it can't lock the window to stop tracking for some reason.
2138 // Not waiting for tracking gives a faster response but restart position is
2139 // only as accurate as the last tracking update.
2140                         cwindow->playback_engine->interrupt_playback(0);
2141                         cwindow->playback_engine->que->send_command(command,
2142                                         change_type, 
2143                                         edl,
2144                                         1,
2145                                         0);
2146                 }
2147         }
2148         else
2149         {
2150                 cwindow->playback_engine->que->send_command(CURRENT_FRAME, 
2151                                                         change_type,
2152                                                         edl,
2153                                                         1);
2154         }
2155 }
2156
2157 void MWindow::age_caches()
2158 {
2159 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n", 
2160 // __LINE__, 
2161 // preferences->cache_size,
2162 // audio_cache->get_memory_usage(1),
2163 // video_cache->get_memory_usage(1),
2164 // frame_cache->get_memory_usage(), 
2165 // wave_cache->get_memory_usage(),
2166 // memory_usage);
2167         frame_cache->age_cache(512);
2168         wave_cache->age_cache(8192);
2169
2170         int64_t memory_usage;
2171         int64_t prev_memory_usage = 0;
2172         int result = 0;
2173         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
2174         while( !result && prev_memory_usage !=
2175                 (memory_usage=video_cache->get_memory_usage(1)) &&
2176                 memory_usage > video_size ) {
2177                 video_cache->delete_oldest();
2178                 prev_memory_usage = memory_usage;
2179         }
2180
2181         prev_memory_usage = 0;
2182         result = 0;
2183         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
2184         while( !result && prev_memory_usage !=
2185                 (memory_usage=audio_cache->get_memory_usage(1)) &&
2186                 memory_usage > audio_size ) {
2187                 audio_cache->delete_oldest();
2188                 prev_memory_usage = memory_usage;
2189         }
2190 }
2191
2192 void MWindow::reset_android_remote()
2193 {
2194         gui->use_android_remote(preferences->android_remote);
2195 }
2196
2197
2198 void MWindow::show_keyframe_gui(Plugin *plugin)
2199 {
2200         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
2201 // Find existing thread
2202         for(int i = 0; i < keyframe_threads->size(); i++)
2203         {
2204                 if(keyframe_threads->get(i)->plugin == plugin)
2205                 {
2206                         keyframe_threads->get(i)->start_window(plugin, 0);
2207                         keyframe_gui_lock->unlock();
2208                         return;
2209                 }
2210         }
2211
2212 // Find unused thread
2213         for(int i = 0; i < keyframe_threads->size(); i++)
2214         {
2215                 if(!keyframe_threads->get(i)->plugin)
2216                 {
2217                         keyframe_threads->get(i)->start_window(plugin, 0);
2218                         keyframe_gui_lock->unlock();
2219                         return;
2220                 }
2221         }
2222
2223 // Create new thread
2224         KeyFrameThread *thread = new KeyFrameThread(this);
2225         keyframe_threads->append(thread);
2226         thread->start_window(plugin, 0);
2227
2228         keyframe_gui_lock->unlock();
2229 }
2230
2231
2232
2233
2234
2235 void MWindow::show_plugin(Plugin *plugin)
2236 {
2237         int done = 0;
2238
2239 SET_TRACE
2240 // Remove previously deleted plugin GUIs
2241         dead_plugin_lock->lock("MWindow::delete_plugin");
2242         for(int i = 0; i < dead_plugins->size(); i++)
2243         {
2244                 delete dead_plugins->get(i);
2245         }
2246         dead_plugins->remove_all();
2247         dead_plugin_lock->unlock();
2248
2249 //printf("MWindow::show_plugin %d\n", __LINE__);
2250 SET_TRACE
2251
2252
2253         plugin_gui_lock->lock("MWindow::show_plugin");
2254         for(int i = 0; i < plugin_guis->total; i++)
2255         {
2256 // Pointer comparison
2257                 if(plugin_guis->get(i)->plugin == plugin)
2258                 {
2259                         plugin_guis->get(i)->raise_window();
2260                         done = 1;
2261                         break;
2262                 }
2263         }
2264 SET_TRACE
2265
2266 //printf("MWindow::show_plugin 1\n");
2267         if(!done)
2268         {
2269                 if(!plugin->track)
2270                 {
2271                         printf("MWindow::show_plugin track not defined.\n");
2272                 }
2273                 PluginServer *server = scan_plugindb(plugin->title,
2274                         plugin->track->data_type);
2275
2276 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
2277                 if(server && server->uses_gui)
2278                 {
2279                         PluginServer *gui = plugin_guis->append(new PluginServer(*server));
2280 // Needs mwindow to do GUI
2281                         gui->set_mwindow(this);
2282                         gui->open_plugin(0, preferences, edl, plugin);
2283                         gui->show_gui();
2284                         plugin->show = 1;
2285                 }
2286         }
2287         plugin_gui_lock->unlock();
2288 //printf("MWindow::show_plugin %d\n", __LINE__);
2289 SET_TRACE
2290 //sleep(1);
2291 //printf("MWindow::show_plugin 2\n");
2292 }
2293
2294 void MWindow::hide_plugin(Plugin *plugin, int lock)
2295 {
2296         plugin->show = 0;
2297 // Update the toggle
2298         gui->lock_window("MWindow::hide_plugin");
2299         gui->update(0, 1, 0, 0, 0, 0, 0);
2300         gui->unlock_window();
2301
2302         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
2303         for(int i = 0; i < plugin_guis->total; i++)
2304         {
2305                 if(plugin_guis->get(i)->plugin == plugin)
2306                 {
2307                         PluginServer *ptr = plugin_guis->get(i);
2308                         plugin_guis->remove(ptr);
2309                         if(lock) plugin_gui_lock->unlock();
2310 // Last command executed in client side close
2311 // Schedule for deletion
2312                         ptr->hide_gui();
2313                         delete_plugin(ptr);
2314 //sleep(1);
2315 //                      return;
2316                 }
2317         }
2318         if(lock) plugin_gui_lock->unlock();
2319 }
2320
2321 void MWindow::delete_plugin(PluginServer *plugin)
2322 {
2323         dead_plugin_lock->lock("MWindow::delete_plugin");
2324         dead_plugins->append(plugin);
2325         dead_plugin_lock->unlock();
2326 }
2327
2328 void MWindow::hide_plugins()
2329 {
2330         plugin_gui_lock->lock("MWindow::hide_plugins 1");
2331         while(plugin_guis->size())
2332         {
2333                 PluginServer *ptr = plugin_guis->get(0);
2334                 plugin_guis->remove(ptr);
2335                 plugin_gui_lock->unlock();
2336 // Last command executed in client side close
2337 // Schedule for deletion
2338                 ptr->hide_gui();
2339                 delete_plugin(ptr);
2340                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
2341         }
2342         plugin_gui_lock->unlock();
2343
2344         hide_keyframe_guis();
2345 }
2346
2347 void MWindow::hide_keyframe_guis()
2348 {
2349         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
2350         for(int i = 0; i < keyframe_threads->size(); i++)
2351         {
2352                 keyframe_threads->get(i)->close_window();
2353         }
2354         keyframe_gui_lock->unlock();
2355 }
2356
2357 void MWindow::hide_keyframe_gui(Plugin *plugin)
2358 {
2359         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
2360         for(int i = 0; i < keyframe_threads->size(); i++)
2361         {
2362                 if(keyframe_threads->get(i)->plugin == plugin)
2363                 {
2364                         keyframe_threads->get(i)->close_window();
2365                         break;
2366                 }
2367         }
2368         keyframe_gui_lock->unlock();
2369 }
2370
2371 void MWindow::update_keyframe_guis()
2372 {
2373 // Send new configuration to keyframe GUI's
2374         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
2375         for(int i = 0; i < keyframe_threads->size(); i++)
2376         {
2377                 KeyFrameThread *ptr = keyframe_threads->get(i);
2378                 if(edl->tracks->plugin_exists(ptr->plugin))
2379                         ptr->update_gui(1);
2380                 else
2381                 {
2382                         ptr->close_window();
2383                 }
2384         }
2385         keyframe_gui_lock->unlock();
2386 }
2387
2388 void MWindow::update_plugin_guis(int do_keyframe_guis)
2389 {
2390 // Send new configuration to plugin GUI's
2391         plugin_gui_lock->lock("MWindow::update_plugin_guis");
2392
2393         for(int i = 0; i < plugin_guis->size(); i++)
2394         {
2395                 PluginServer *ptr = plugin_guis->get(i);
2396                 if(edl->tracks->plugin_exists(ptr->plugin))
2397                         ptr->update_gui();
2398                 else
2399                 {
2400 // Schedule for deletion if no plugin
2401                         plugin_guis->remove_number(i);
2402                         i--;
2403                         
2404                         ptr->hide_gui();
2405                         delete_plugin(ptr);
2406                 }
2407         }
2408
2409
2410 // Change plugin variable if not visible
2411         Track *track = edl->tracks->first;
2412         while(track)
2413         {
2414                 for(int i = 0; i < track->plugin_set.size(); i++)
2415                 {
2416                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
2417                         while(plugin)
2418                         {
2419                                 int got_it = 0;
2420                                 for(int i = 0; i < plugin_guis->size(); i++)
2421                                 {
2422                                         PluginServer *server = plugin_guis->get(i);
2423                                         if(server->plugin == plugin) 
2424                                         {
2425                                                 got_it = 1;
2426                                                 break;
2427                                         }
2428                                 }
2429                                 
2430                                 if(!got_it) plugin->show = 0;
2431
2432                                 plugin = (Plugin*)plugin->next;
2433                         }
2434                 }
2435                 
2436                 track = track->next;
2437         }
2438
2439         plugin_gui_lock->unlock();
2440
2441
2442         if(do_keyframe_guis) update_keyframe_guis();
2443 }
2444
2445 int MWindow::plugin_gui_open(Plugin *plugin)
2446 {
2447         int result = 0;
2448         plugin_gui_lock->lock("MWindow::plugin_gui_open");
2449         for(int i = 0; i < plugin_guis->total; i++)
2450         {
2451                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2452                 {
2453                         result = 1;
2454                         break;
2455                 }
2456         }
2457         plugin_gui_lock->unlock();
2458         return result;
2459 }
2460
2461 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
2462 {
2463         plugin_gui_lock->lock("MWindow::render_plugin_gui");
2464         for(int i = 0; i < plugin_guis->total; i++)
2465         {
2466                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2467                 {
2468                         plugin_guis->get(i)->render_gui(data);
2469                         break;
2470                 }
2471         }
2472         plugin_gui_lock->unlock();
2473 }
2474
2475 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
2476 {
2477         plugin_gui_lock->lock("MWindow::render_plugin_gui");
2478         for(int i = 0; i < plugin_guis->total; i++)
2479         {
2480                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2481                 {
2482                         plugin_guis->get(i)->render_gui(data, size);
2483                         break;
2484                 }
2485         }
2486         plugin_gui_lock->unlock();
2487 }
2488
2489
2490 void MWindow::update_plugin_states()
2491 {
2492         plugin_gui_lock->lock("MWindow::update_plugin_states");
2493         for(int i = 0; i < plugin_guis->total; i++)
2494         {
2495                 int result = 0;
2496 // Get a plugin GUI
2497                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
2498                 PluginServer *src_plugingui = plugin_guis->get(i);
2499
2500 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
2501                 for(Track *track = edl->tracks->first; 
2502                         track && !result; 
2503                         track = track->next)
2504                 {
2505                         for(int j = 0; 
2506                                 j < track->plugin_set.total && !result; 
2507                                 j++)
2508                         {
2509                                 PluginSet *plugin_set = track->plugin_set[j];
2510                                 for(Plugin *plugin = (Plugin*)plugin_set->first; 
2511                                         plugin && !result; 
2512                                         plugin = (Plugin*)plugin->next)
2513                                 {
2514                                         if(plugin == src_plugin &&
2515                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
2516                                 }
2517                         }
2518                 }
2519
2520
2521 // Doesn't exist anymore
2522                 if(!result)
2523                 {
2524                         hide_plugin(src_plugin, 0);
2525                         i--;
2526                 }
2527         }
2528         plugin_gui_lock->unlock();
2529 }
2530
2531
2532 void MWindow::update_plugin_titles()
2533 {
2534         for(int i = 0; i < plugin_guis->total; i++)
2535         {
2536                 plugin_guis->get(i)->update_title();
2537         }
2538 }
2539
2540 int MWindow::asset_to_edl(EDL *new_edl, 
2541         Asset *new_asset, 
2542         RecordLabels *labels)
2543 {
2544 const int debug = 0;
2545 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n", 
2546 __LINE__,
2547 new_asset->layers);
2548 // Keep frame rate, sample rate, and output size unchanged.
2549 // These parameters would revert the project if VWindow displayed an asset
2550 // of different size than the project.
2551         if(new_asset->video_data)
2552         {
2553                 new_edl->session->video_tracks = new_asset->layers;
2554         }
2555         else
2556                 new_edl->session->video_tracks = 0;
2557
2558 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2559
2560
2561
2562
2563
2564         if(new_asset->audio_data)
2565         {
2566                 new_edl->session->audio_tracks = new_asset->channels;
2567         }
2568         else
2569                 new_edl->session->audio_tracks = 0;
2570 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
2571
2572 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2573         new_edl->create_default_tracks();
2574 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
2575 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2576
2577
2578
2579 //printf("MWindow::asset_to_edl 3\n");
2580         new_edl->insert_asset(new_asset,
2581                 0,
2582                 0, 
2583                 0, 
2584                 labels);
2585 //printf("MWindow::asset_to_edl 3\n");
2586 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2587
2588
2589
2590
2591
2592         char string[BCTEXTLEN];
2593         FileSystem fs;
2594         fs.extract_name(string, new_asset->path);
2595 //printf("MWindow::asset_to_edl 3\n");
2596
2597         strcpy(new_edl->local_session->clip_title, string);
2598 //printf("MWindow::asset_to_edl 4 %s\n", string);
2599 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2600
2601         return 0;
2602 }
2603
2604 int MWindow::edl_to_nested(EDL *new_edl, 
2605         EDL *nested_edl)
2606 {
2607
2608 // Keep frame rate, sample rate, and output size unchanged.
2609 // These parameters would revert the project if VWindow displayed an asset
2610 // of different size than the project.
2611
2612
2613
2614 // Nest all video & audio outputs
2615         new_edl->session->video_tracks = 1;
2616         new_edl->session->audio_tracks = nested_edl->session->audio_channels;
2617         new_edl->create_default_tracks();
2618
2619
2620
2621         new_edl->insert_asset(0,
2622                 nested_edl,
2623                 0, 
2624                 0, 
2625                 0);
2626
2627         char string[BCTEXTLEN];
2628         FileSystem fs;
2629         fs.extract_name(string, nested_edl->path);
2630 //printf("MWindow::edl_to_nested %p %s\n", nested_edl, nested_edl->path);
2631
2632         strcpy(new_edl->local_session->clip_title, string);
2633
2634         return 0;
2635 }
2636
2637 // Reset everything after a load.
2638 void MWindow::update_project(int load_mode)
2639 {
2640         const int debug = 0;
2641         
2642         if(debug) PRINT_TRACE
2643         restart_brender();
2644         edl->tracks->update_y_pixels(theme);
2645
2646         if(debug) PRINT_TRACE
2647
2648         if(load_mode == LOADMODE_REPLACE ||
2649                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2650         {
2651                 gui->load_panes();
2652         }
2653
2654         gui->update(1, 1, 1, 1, 1, 1, 1);
2655         if(debug) PRINT_TRACE
2656         gui->unlock_window();
2657
2658         cwindow->gui->lock_window("MWindow::update_project 1");
2659         cwindow->update(0, 0, 1, 1, 1);
2660         cwindow->gui->unlock_window();
2661
2662         if(debug) PRINT_TRACE
2663
2664 // Close all the vwindows
2665         if(load_mode == LOADMODE_REPLACE ||
2666                 load_mode == LOADMODE_REPLACE_CONCATENATE) {
2667                 if(debug) PRINT_TRACE
2668                 int first_vwindow = 0;
2669                 if(session->show_vwindow) first_vwindow = 1;
2670 // Change visible windows to no source
2671                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
2672                         VWindow *vwindow = vwindows[i];
2673                         if( !vwindow->is_running() ) continue;
2674                         vwindow->change_source(-1);
2675                 }
2676
2677 // Close remaining windows
2678                 for(int i = first_vwindow; i < vwindows.size(); i++) {
2679                         VWindow *vwindow = vwindows[i];
2680                         if( !vwindow->is_running() ) continue;
2681                         vwindow->close_window();
2682                 }
2683                 if(debug) PRINT_TRACE
2684         }
2685         else if(vwindows.size()) {
2686                 VWindow *vwindow = vwindows[DEFAULT_VWINDOW];
2687                 if( vwindow->is_running() ) {
2688                         vwindow->gui->lock_window("MWindow::update_project");
2689                         vwindow->update(1);
2690                         vwindow->gui->unlock_window();
2691                 }
2692         }
2693
2694         if(debug) PRINT_TRACE
2695         cwindow->gui->lock_window("MWindow::update_project 2");
2696         cwindow->gui->timebar->update(0);
2697         cwindow->gui->unlock_window();
2698
2699         if(debug) PRINT_TRACE
2700         cwindow->playback_engine->que->send_command(CURRENT_FRAME, 
2701                 CHANGE_ALL,
2702                 edl,
2703                 1);
2704
2705         if(debug) PRINT_TRACE
2706
2707         awindow->gui->lock_window("MWindow::update_project");
2708         awindow->gui->update_assets();
2709         awindow->gui->flush();
2710         awindow->gui->unlock_window();
2711
2712         if(debug) PRINT_TRACE
2713
2714         gui->lock_window("MWindow::update_project");
2715         gui->flush();
2716         if(debug) PRINT_TRACE
2717 }
2718
2719 void MWindow::remove_indexfile(Indexable *indexable)
2720 {
2721         if( !indexable->is_asset ) return;
2722         Asset *asset = (Asset *)indexable;
2723 // Erase file
2724         IndexFile::delete_index(preferences, asset, ".toc");
2725         IndexFile::delete_index(preferences, asset, ".idx");
2726         IndexFile::delete_index(preferences, asset, ".mkr");
2727 }
2728
2729 void MWindow::rebuild_indices()
2730 {
2731         for(int i = 0; i < session->drag_assets->total; i++)
2732         {
2733                 Indexable *indexable = session->drag_assets->get(i);
2734 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
2735                 remove_indexfile(indexable);
2736 // Schedule index build
2737                 IndexState *index_state = indexable->index_state;
2738                 index_state->index_status = INDEX_NOTTESTED;
2739                 if( indexable->is_asset ) {
2740                         Asset *asset = (Asset *)indexable;
2741                         if( asset->format != FILE_PCM )
2742                                 asset->reset_audio();
2743                         asset->reset_video();
2744                 }
2745                 mainindexes->add_next_asset(0, indexable);
2746         }
2747         mainindexes->start_build();
2748 }
2749
2750
2751 void MWindow::save_backup()
2752 {
2753         FileXML file;
2754         edl->set_path(session->filename);
2755         edl->save_xml(&file, 
2756                 BACKUP_PATH,
2757                 0,
2758                 0);
2759         file.terminate_string();
2760         char path[BCTEXTLEN];
2761         FileSystem fs;
2762         strcpy(path, BACKUP_PATH);
2763         fs.complete_path(path);
2764
2765         if(file.write_to_file(path))
2766         {
2767                 char string2[256];
2768                 sprintf(string2, _("Couldn't open %s for writing."), BACKUP_PATH);
2769                 gui->show_message(string2);
2770         }
2771 }
2772
2773 void MWindow::load_backup()
2774 {
2775         ArrayList<char*> path_list;
2776         path_list.set_array_delete();
2777         char *out_path;
2778         char string[BCTEXTLEN];
2779         strcpy(string, BACKUP_PATH);
2780         FileSystem fs;
2781         fs.complete_path(string);
2782         
2783         path_list.append(out_path = new char[strlen(string) + 1]);
2784         strcpy(out_path, string);
2785         
2786         load_filenames(&path_list, LOADMODE_REPLACE, 0);
2787         edl->local_session->clip_title[0] = 0;
2788 // This is unique to backups since the path of the backup is different than the
2789 // path of the project.
2790         set_filename(edl->path);
2791         path_list.remove_all_objects();
2792         save_backup();
2793 }
2794
2795 static inline int gcd(int m, int n)
2796 {
2797         int r;
2798         if( m < n ) { r = m;  m = n;  n = r; }
2799         while( (r = m % n) != 0 ) { m = n;  n = r; }
2800         return n;
2801 }
2802
2803 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
2804 {
2805         w = 1;  h = 1;
2806         if(!width || !height) return 1;
2807         double ar = (double)width / height;
2808 // square-ish pixels
2809         if( EQUIV(ar, 1.0000) ) return 0;
2810         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
2811         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
2812         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
2813         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
2814         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
2815         int ww = width, hh = height;
2816         // numerator, denominator must be under mx
2817         int mx = 255, n = gcd(ww, hh);
2818         if( n > 1 ) { ww /= n; hh /= n; }
2819         // search near height in case extra/missing lines
2820         if( ww >= mx || hh >= mx ) {
2821                 double err = height;  // +/- 2 percent height
2822                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
2823                         int iw = width, ih = height+i;
2824                         if( (n=gcd(iw, ih)) > 1 ) {
2825                                 int u = iw/n;  if( u >= mx ) continue;
2826                                 int v = ih/n;  if( v >= mx ) continue;
2827                                 double r = (double) u/v, er = fabs(ar-r);
2828                                 if( er >= err ) continue;
2829                                 err = er;  ww = u;  hh = v;
2830                         }
2831                 }
2832         }
2833
2834         w = ww;  h = hh;
2835         return 0;
2836 }
2837
2838 void MWindow::reset_caches()
2839 {
2840         frame_cache->remove_all();
2841         wave_cache->remove_all();
2842         audio_cache->remove_all();
2843         video_cache->remove_all();
2844         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
2845                 cwindow->playback_engine->audio_cache->remove_all();
2846         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
2847                 cwindow->playback_engine->video_cache->remove_all();
2848         
2849         for(int i = 0; i < vwindows.size(); i++) {
2850                 VWindow *vwindow = vwindows[i];
2851                 if( !vwindow->is_running() ) continue;
2852                 if(vwindow->playback_engine && vwindow->playback_engine->audio_cache)
2853                         vwindow->playback_engine->audio_cache->remove_all();
2854                 if(vwindow->playback_engine && vwindow->playback_engine->video_cache)
2855                         vwindow->playback_engine->video_cache->remove_all();
2856         }
2857 }
2858
2859 void MWindow::remove_asset_from_caches(Asset *asset)
2860 {
2861         frame_cache->remove_asset(asset);
2862         wave_cache->remove_asset(asset);
2863         audio_cache->delete_entry(asset);
2864         video_cache->delete_entry(asset);
2865         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
2866                 cwindow->playback_engine->audio_cache->delete_entry(asset);
2867         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
2868                 cwindow->playback_engine->video_cache->delete_entry(asset);
2869         for(int i = 0; i < vwindows.size(); i++) {
2870                 VWindow *vwindow = vwindows[i];
2871                 if( !vwindow->is_running() ) continue;
2872                 if(vwindow->playback_engine && vwindow->playback_engine->audio_cache)
2873                         vwindow->playback_engine->audio_cache->delete_entry(asset);
2874                 if(vwindow->playback_engine && vwindow->playback_engine->video_cache)
2875                         vwindow->playback_engine->video_cache->delete_entry(asset);
2876         }
2877 }
2878
2879
2880 void MWindow::remove_assets_from_project(int push_undo, int redraw,
2881                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
2882 {
2883         for(int i = 0; i < session->drag_assets->total; i++) {
2884                 Indexable *indexable = session->drag_assets->get(i);
2885                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
2886         }
2887
2888 // Remove from VWindow.
2889         for(int i = 0; i < session->drag_clips->total; i++) {
2890                 for(int j = 0; j < vwindows.size(); j++) {
2891                         VWindow *vwindow = vwindows[j];
2892                         if( !vwindow->is_running() ) continue;
2893                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
2894                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
2895                                 vwindow->delete_source(1, 1);
2896                                 vwindow->gui->unlock_window();
2897                         }
2898                 }
2899         }
2900         
2901         for(int i = 0; i < session->drag_assets->size(); i++) {
2902                 for(int j = 0; j < vwindows.size(); j++) {
2903                         VWindow *vwindow = vwindows[j];
2904                         if( !vwindow->is_running() ) continue;
2905                         if(session->drag_assets->get(i) == vwindow->get_source()) {
2906                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
2907                                 vwindow->delete_source(1, 1);
2908                                 vwindow->gui->unlock_window();
2909                         }
2910                 }
2911         }
2912         
2913         for(int i = 0; i < session->drag_assets->size(); i++) {
2914                 Indexable *indexable = session->drag_assets->get(i);
2915                 remove_indexfile(indexable);
2916         }
2917
2918 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
2919         if(push_undo) undo->update_undo_before();
2920         if(drag_assets) edl->remove_from_project(drag_assets);
2921         if(drag_clips) edl->remove_from_project(session->drag_clips);
2922         if(redraw) save_backup();
2923         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
2924         if(redraw) 
2925         {
2926                 restart_brender();
2927
2928                 gui->lock_window("MWindow::remove_assets_from_project 3");
2929                 gui->update(1,
2930                         1,
2931                         1,
2932                         1,
2933                         0, 
2934                         1,
2935                         0);
2936                 gui->unlock_window();
2937
2938                 awindow->gui->lock_window("MWindow::remove_assets_from_project 4");
2939                 awindow->gui->update_assets();
2940                 awindow->gui->flush();
2941                 awindow->gui->unlock_window();
2942
2943         // Removes from playback here
2944                 sync_parameters(CHANGE_ALL);
2945         }
2946 }
2947
2948 void MWindow::remove_assets_from_disk()
2949 {
2950 // Remove from disk
2951         for(int i = 0; i < session->drag_assets->total; i++)
2952         {
2953                 remove(session->drag_assets->get(i)->path);
2954         }
2955
2956         remove_assets_from_project(1, 
2957                 1, 
2958                 session->drag_assets,
2959                 session->drag_clips);
2960 }
2961
2962 void MWindow::dump_plugins(FILE *fp)
2963 {
2964         if( !plugindb ) return;
2965         for(int i = 0; i < plugindb->total; i++)
2966         {
2967                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
2968                         " synth=%d transition=%d theme=%d %s\n",
2969                         plugindb->get(i)->plugin_type,
2970                         plugindb->get(i)->audio,
2971                         plugindb->get(i)->video,
2972                         plugindb->get(i)->realtime,
2973                         plugindb->get(i)->multichannel,
2974                         plugindb->get(i)->get_synthesis(),
2975                         plugindb->get(i)->transition,
2976                         plugindb->get(i)->theme,
2977                         plugindb->get(i)->title);
2978         }
2979 }
2980
2981 void MWindow::dump_edl(FILE *fp)
2982 {
2983         if( !edl ) return;
2984         edl->dump(fp);
2985 }
2986
2987 void MWindow::dump_undo(FILE *fp)
2988 {
2989         if( !undo ) return;
2990         undo->dump(fp);
2991 }
2992
2993 void MWindow::dump_exe(FILE *fp)
2994 {
2995         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
2996         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
2997         int len = readlink(proc_path, exe_path, sizeof(exe_path));
2998         if( len < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
2999         exe_path[len] = 0;
3000         struct stat st;
3001         if( stat(exe_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
3002         fprintf(fp, "path: %s = %9jd bytes\n",exe_path,st.st_size);
3003         int fd = open(exe_path,O_RDONLY);
3004         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
3005         uint8_t buf[65536];  SHA1 sha1;
3006         while( (len=read(fd,buf,sizeof(buf))) > 0 ) {
3007                 sha1.addBytes(buf, len);
3008         }
3009         close(fd);
3010         fprintf(fp, "SHA1: ");
3011         uint8_t digest[20];  sha1.computeHash(digest);
3012         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
3013         fprintf(fp, "\n");
3014 }
3015
3016
3017 void MWindow::trap_hook(FILE *fp, void *vp)
3018 {
3019         MWindow *mwindow = (MWindow *)vp;
3020         fprintf(fp, "\nEXE:\n");
3021         mwindow->dump_exe(fp);
3022         fprintf(fp, "\nPLUGINS:\n");
3023         mwindow->dump_plugins(fp);
3024         fprintf(fp, "\nEDL:\n");
3025         mwindow->dump_edl(fp);
3026         fprintf(fp, "\nUNDO:\n");
3027         mwindow->dump_undo(fp);
3028 }
3029
3030
3031
3032
3033
3034
3035 int MWindow::save_defaults()
3036 {
3037         gui->save_defaults(defaults);
3038         edl->save_defaults(defaults);
3039         session->save_defaults(defaults);
3040         preferences->save_defaults(defaults);
3041
3042         for(int i = 0; i < plugin_guis->total; i++)
3043         {
3044 // Pointer comparison
3045                 plugin_guis->get(i)->save_defaults();
3046         }
3047         awindow->save_defaults(defaults);
3048
3049         defaults->save();
3050         return 0;
3051 }
3052
3053 int MWindow::run_script(FileXML *script)
3054 {
3055         int result = 0, result2 = 0;
3056         while(!result && !result2)
3057         {
3058                 result = script->read_tag();
3059                 if(!result)
3060                 {
3061                         if(script->tag.title_is("new_project"))
3062                         {
3063 // Run new in immediate mode.
3064 //                              gui->mainmenu->new_project->run_script(script);
3065                         }
3066                         else
3067                         if(script->tag.title_is("record"))
3068                         {
3069 // Run record as a thread.  It is a terminal command.
3070                                 ;
3071 // Will read the complete scipt file without letting record read it if not
3072 // terminated.
3073                                 result2 = 1;
3074                         }
3075                         else
3076                         {
3077                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
3078                         }
3079                 }
3080         }
3081         return result2;
3082 }
3083
3084 // ================================= synchronization
3085
3086
3087 int MWindow::interrupt_indexes()
3088 {
3089         mainindexes->interrupt_build();
3090         return 0; 
3091 }
3092
3093
3094
3095 void MWindow::next_time_format()
3096 {
3097         switch(edl->session->time_format)
3098         {
3099                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
3100                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
3101                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3102                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
3103                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
3104                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
3105                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
3106         }
3107
3108         time_format_common();
3109 }
3110
3111 void MWindow::prev_time_format()
3112 {
3113         switch(edl->session->time_format)
3114         {
3115                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
3116                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
3117                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
3118                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3119                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
3120                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
3121                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
3122         }
3123
3124         time_format_common();
3125 }
3126
3127 void MWindow::time_format_common()
3128 {
3129         gui->lock_window("MWindow::next_time_format");
3130         gui->redraw_time_dependancies();
3131
3132
3133         char string[BCTEXTLEN], string2[BCTEXTLEN];
3134         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
3135         gui->show_message(string);
3136         gui->flush();
3137         gui->unlock_window();
3138 }
3139
3140
3141 int MWindow::set_filename(const char *filename)
3142 {
3143         if( filename != session->filename )
3144                 strcpy(session->filename, filename);
3145         if( filename != edl->path )
3146                 strcpy(edl->path, filename);
3147
3148         if(gui)
3149         {
3150                 if(filename[0] == 0)
3151                 {
3152                         gui->set_title(PROGRAM_NAME);
3153                 }
3154                 else
3155                 {
3156                         FileSystem dir;
3157                         char string[BCTEXTLEN], string2[BCTEXTLEN];
3158                         dir.extract_name(string, filename);
3159                         sprintf(string2, PROGRAM_NAME ": %s", string);
3160                         gui->set_title(string2);
3161                 }
3162         }
3163         return 0; 
3164 }
3165
3166
3167
3168
3169
3170
3171
3172
3173 int MWindow::set_loop_boundaries()
3174 {
3175         double start = edl->local_session->get_selectionstart();
3176         double end = edl->local_session->get_selectionend();
3177         
3178         if(start != 
3179                 end) 
3180         {
3181                 ;
3182         }
3183         else
3184         if(edl->tracks->total_length())
3185         {
3186                 start = 0;
3187                 end = edl->tracks->total_length();
3188         }
3189         else
3190         {
3191                 start = end = 0;
3192         }
3193
3194         if(edl->local_session->loop_playback && start != end)
3195         {
3196                 edl->local_session->loop_start = start;
3197                 edl->local_session->loop_end = end;
3198         }
3199         return 0; 
3200 }
3201
3202
3203
3204
3205
3206
3207
3208 int MWindow::reset_meters()
3209 {
3210         cwindow->gui->lock_window("MWindow::reset_meters 1");
3211         cwindow->gui->meters->reset_meters();
3212         cwindow->gui->unlock_window();
3213
3214         for(int j = 0; j < vwindows.size(); j++) {
3215                 VWindow *vwindow = vwindows[j];
3216                 if( !vwindow->is_running() ) continue;
3217                 vwindow->gui->lock_window("MWindow::reset_meters 2");
3218                 vwindow->gui->meters->reset_meters();
3219                 vwindow->gui->unlock_window();
3220         }
3221
3222         lwindow->gui->lock_window("MWindow::reset_meters 3");
3223         lwindow->gui->panel->reset_meters();
3224         lwindow->gui->unlock_window();
3225
3226         gui->lock_window("MWindow::reset_meters 4");
3227         gui->reset_meters();
3228         gui->unlock_window();
3229         return 0; 
3230 }
3231
3232
3233 void MWindow::resync_guis()
3234 {
3235 // Update GUIs
3236         restart_brender();
3237         gui->lock_window("MWindow::resync_guis");
3238         gui->update(1, 1, 1, 1, 1, 1, 0);
3239         gui->unlock_window();
3240
3241         cwindow->gui->lock_window("MWindow::resync_guis");
3242         cwindow->gui->resize_event(cwindow->gui->get_w(), 
3243                 cwindow->gui->get_h());
3244         int channels = edl->session->audio_channels;
3245         cwindow->gui->meters->set_meters(channels, 1);
3246         cwindow->gui->flush();
3247         cwindow->gui->unlock_window();
3248
3249         for(int i = 0; i < vwindows.size(); i++) {
3250                 VWindow *vwindow = vwindows[i];
3251                 if( !vwindow->is_running() ) continue;
3252                 vwindow->gui->lock_window("MWindow::resync_guis");
3253                 vwindow->gui->resize_event(vwindow->gui->get_w(), 
3254                         vwindow->gui->get_h());
3255                 vwindow->gui->meters->set_meters(channels, 1);
3256                 vwindow->gui->flush();
3257                 vwindow->gui->unlock_window();
3258         }
3259
3260         lwindow->gui->lock_window("MWindow::resync_guis");
3261         lwindow->gui->panel->set_meters(channels, 1);
3262         lwindow->gui->flush();
3263         lwindow->gui->unlock_window();
3264
3265 // Warn user
3266         if(((edl->session->output_w % 4) ||
3267                 (edl->session->output_h % 4)) &&
3268                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
3269         {
3270                 MainError::show_error(
3271                         _("This project's dimensions are not multiples of 4 so\n"
3272                         "it can't be rendered by OpenGL."));
3273         }
3274
3275
3276 // Flash frame
3277         sync_parameters(CHANGE_ALL);
3278 }
3279
3280 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
3281 {
3282         File *file = new File;
3283         EDLSession *session = edl->session;
3284         double old_framerate = session->frame_rate;
3285         double old_samplerate = session->sample_rate;
3286         int result = file->open_file(preferences, asset, 1, 0);
3287         if( !result && delete_tracks > 0 )
3288                 undo->update_undo_before();
3289         if( !result && asset->get_video_layers() > 0 ) {
3290                 // try to get asset up to date, may fail
3291                 file->select_video_stream(asset, vstream);
3292                 // either way use what was/is there.
3293                 double framerate = asset->get_frame_rate();
3294                 int width = asset->get_w();
3295                 int height = asset->get_h();
3296                 // must be multiple of 4 for opengl
3297                 width = (width+3) & ~3;  height = (height+3) & ~3;
3298                 int driver = session->playback_config->vconfig->driver;
3299                 int color_model = file->get_best_colormodel(asset, driver);
3300                 color_model = BC_CModels::is_yuv(color_model) ?
3301                                 BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
3302                         BC_CModels::is_float(color_model) ?
3303                                 BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
3304                                 BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
3305                 session->color_model = color_model;
3306                 session->output_w = width;
3307                 session->output_h = height;
3308                 session->frame_rate = framerate;
3309                 // not, asset->actual_width/actual_height
3310                 asset->width = session->output_w;
3311                 asset->height = session->output_h;
3312                 asset->frame_rate = session->frame_rate;
3313                 create_aspect_ratio(session->aspect_w, session->aspect_h,
3314                         session->output_w, session->output_h);
3315                 Track *track = edl->tracks->first;
3316                 for( Track *next_track=0; track; track=next_track ) {
3317                         next_track = track->next;
3318                         if( track->data_type != TRACK_VIDEO ) continue;
3319                         if( delete_tracks ) {
3320                                 Edit *edit = track->edits->first;
3321                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
3322                                         next_edit = edit->next;
3323                                         if( edit->channel != vstream ||
3324                                             !edit->asset || !edit->asset->is_asset ||
3325                                             *asset != *edit->asset )
3326                                                 delete edit;
3327                                 }
3328                         }
3329                         if( track->edits->first ) {
3330                                 track->track_w = edl->session->output_w;
3331                                 track->track_h = edl->session->output_h;
3332                         }
3333                         else if( delete_tracks )
3334                                 edl->tracks->delete_track(track);
3335                 }
3336                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
3337         }
3338         if( !result && asset->channels > 0 ) {
3339                 session->sample_rate = asset->get_sample_rate();
3340                 int64_t channel_mask = 0;
3341                 int astrm = file->get_audio_for_video(vstream, astream, channel_mask);
3342                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
3343                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
3344                 int channels = 0;
3345                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
3346                 if( channels > 6 ) channels = 6;
3347                 session->audio_tracks = session->audio_channels = channels;
3348                 switch( channels ) {
3349                 case 6:
3350                         session->achannel_positions[0] = 90;
3351                         session->achannel_positions[1] = 150;
3352                         session->achannel_positions[2] = 30;
3353                         session->achannel_positions[3] = 210;
3354                         session->achannel_positions[4] = 330;
3355                         session->achannel_positions[5] = 270;
3356                         break;
3357                 case 2:
3358                         session->achannel_positions[0] = 180;
3359                         session->achannel_positions[1] = 0;
3360                         break;
3361                 }
3362                 remap_audio(MWindow::AUDIO_1_TO_1);
3363
3364                 if( delete_tracks ) {
3365                         Track *track = edl->tracks->first;
3366                         for( Track *next_track=0; track; track=next_track ) {
3367                                 next_track = track->next;
3368                                 if( track->data_type != TRACK_AUDIO ) continue;
3369                                 Edit *edit = track->edits->first;
3370                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
3371                                         next_edit = edit->next;
3372                                         if( !((1<<edit->channel) & channel_mask) ||
3373                                             !edit->asset || !edit->asset->is_asset ||
3374                                             *asset != *edit->asset )
3375                                                 delete edit;
3376                                 }
3377                                 if( !track->edits->first )
3378                                         edl->tracks->delete_track(track);
3379                         }
3380                 }
3381                 edl->rechannel();
3382                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
3383         }
3384         delete file;
3385         if( !result && delete_tracks > 0 ) {
3386                 save_backup();
3387                 undo->update_undo_after(_("select asset"), LOAD_ALL);
3388         }
3389         resync_guis();
3390         return result;
3391 }
3392
3393 int MWindow::select_asset(int vtrack, int delete_tracks)
3394 {
3395         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
3396         if( !track ) return 1;
3397         Edit *edit = track->edits->first;
3398         if( !edit ) return 1;
3399         Asset *asset = edit->asset;
3400         if( !asset || !asset->is_asset ) return 1;
3401         return select_asset(asset, edit->channel, -1, delete_tracks);
3402 }
3403
3404 void MWindow::dump_plugindb(FILE *fp)
3405 {
3406         if( !plugindb ) return;
3407         for(int i = 0; i < plugindb->total; i++)
3408                 plugindb->get(i)->dump(fp);
3409 }
3410