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