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