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