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