lock xft, plugin index builder lock, clear clip thumbnails, clear vwin clock, setpoin...
[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         zwindows_lock->lock("MWindow::close_mixers");
1311         for( int i=zwindows.size(); --i>=0; ) {
1312                 ZWindow *zwindow = zwindows[i];
1313                 if( zwindow->idx < 0 ) continue;
1314                 zwindow->destroy = destroy;
1315                 ZWindowGUI *zgui = zwindow->zgui;
1316                 zgui->lock_window("MWindow::select_zwindow 0");
1317                 zgui->set_done(0);
1318                 zgui->unlock_window();
1319         }
1320         zwindows_lock->unlock();
1321         for( int i=0; i<zwindows.size(); ++i ) {
1322                 ZWindow *zwindow = zwindows[i];
1323                 if( zwindow->idx < 0 ) continue;
1324                 zwindow->close_window();
1325         }
1326 }
1327
1328 ZWindow *MWindow::create_mixer(Indexable *indexable)
1329 {
1330         ArrayList<Indexable*> new_assets;
1331         new_assets.append(indexable);
1332         Track *track = edl->tracks->last;
1333         load_assets(&new_assets, 0, LOADMODE_NEW_TRACKS, 0, 0, 0, 0, 0, 0);
1334         track = !track ? edl->tracks->first : track->next;
1335         Mixer *mixer = 0;
1336         ZWindow *zwindow = get_mixer(mixer);
1337         while( track ) {
1338                 track->play = track->record = 0;
1339                 if( track->data_type == TRACK_VIDEO ) {
1340                         sprintf(track->title, _("Mixer %d"), zwindow->idx);
1341                 }
1342                 mixer->mixer_ids.append(track->get_mixer_id());
1343                 track = track->next;
1344         }
1345         if(  indexable->is_asset ) {
1346                 char *path = indexable->path;
1347                 char *tp = strrchr(path, '/');
1348                 if( !tp ) tp = path; else ++tp;
1349                 zwindow->set_title(tp);
1350         }
1351         else {
1352                 char *title = ((EDL*)indexable)->local_session->clip_title;
1353                 zwindow->set_title(title);
1354         }
1355         return zwindow;
1356 }
1357
1358 void MWindow::create_mixers()
1359 {
1360         if( !session->drag_assets->size() &&
1361             !session->drag_clips->size() ) return;
1362         undo->update_undo_before();
1363
1364         select_zwindow(0);
1365         ArrayList<ZWindow *>new_mixers;
1366
1367         for( int i=0; i<session->drag_assets->size(); ++i ) {
1368                 Indexable *indexable = session->drag_assets->get(i);
1369                 if( !indexable->have_video() ) continue;
1370                 ZWindow *zwindow = create_mixer(indexable);
1371                 new_mixers.append(zwindow);
1372         }
1373         for( int i=0; i<session->drag_clips->size(); ++i ) {
1374                 Indexable *indexable = (Indexable*)session->drag_clips->get(i);
1375                 if( !indexable->have_video() ) continue;
1376                 ZWindow *zwindow = create_mixer(indexable);
1377                 new_mixers.append(zwindow);
1378         }
1379
1380         tile_mixers();
1381         for( int i=0; i<new_mixers.size(); ++i )
1382                 new_mixers[i]->start();
1383
1384         refresh_mixers();
1385         save_backup();
1386         undo->update_undo_after(_("create mixers"), LOAD_ALL);
1387         restart_brender();
1388         gui->update(1, 2, 1, 1, 1, 1, 0);
1389         sync_parameters(CHANGE_ALL);
1390 }
1391
1392 void MWindow::open_mixers()
1393 {
1394         for( int i=0; i<edl->mixers.size(); ++i ) {
1395                 Mixer *mixer = edl->mixers[i];
1396                 ZWindow *zwindow = get_mixer(mixer);
1397                 zwindow->set_title(mixer->title);
1398                 zwindow->start();
1399         }
1400         refresh_mixers();
1401 }
1402
1403 int MWindow::select_zwindow(ZWindow *zwindow)
1404 {
1405         int ret = 0, n = zwindows.number_of(zwindow);
1406         if( session->selected_zwindow != n ) {
1407                 session->selected_zwindow = n;
1408                 for( int i=0; i<zwindows.size(); ++i ) {
1409                         ZWindow *zwindow = zwindows[i];
1410                         if( zwindow->idx < 0 ) continue;
1411                         ZWindowGUI *zgui = zwindow->zgui;
1412                         zgui->lock_window("MWindow::select_zwindow 0");
1413                         zwindow->highlighted = i == n ? 1 : 0;
1414                         if( zgui->draw_overlays() )
1415                                 zgui->canvas->get_canvas()->flash(1);
1416                         zgui->unlock_window();
1417                 }
1418                 ret = 1;
1419                 gui->lock_window("MWindow::select_window 1");
1420                 gui->update_mixers(0, -1);
1421                 gui->unlock_window();
1422         }
1423         return ret;
1424 }
1425
1426 void MWindow::tile_mixers()
1427 {
1428         int nz = 0;
1429         for( int i=0; i<zwindows.size(); ++i ) {
1430                 ZWindow *zwindow = zwindows[i];
1431                 if( zwindow->idx < 0 ) continue;
1432                 ++nz;
1433         }
1434         if( !nz ) return;
1435         int zn = ceil(sqrt(nz));
1436         int x1 = 1 + gui->get_x(), x2 = cwindow->gui->get_x();
1437         int y1 = 1, y2 = gui->get_y();
1438         int rw = gui->get_root_w(0), rh = gui->get_root_h(0);
1439         if( x1 < 0 ) x1 = 0;
1440         if( y1 < 0 ) y1 = 0;
1441         if( x2 > rw ) x2 = rw;
1442         if( y2 > rh ) y2 = rh;
1443         int dx = x2 - x1, dy = y2 - y1;
1444         int zw = dx / zn;
1445         int lt = BC_DisplayInfo::get_left_border();
1446         int top = BC_DisplayInfo::get_top_border();
1447         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1448         int bh = top + BC_DisplayInfo::get_bottom_border();
1449         int zx = 0, zy = 0;  // window origins
1450         int mw = 10+10, mh = 10+10; // canvas margins
1451         int rsz = 0, n = 0, dz = 0;
1452         int ow = edl->session->output_w, oh = edl->session->output_h;
1453         for( int i=0; i<zwindows.size(); ++i ) {
1454                 ZWindow *zwindow = zwindows[i];
1455                 if( zwindow->idx < 0 ) continue;
1456                 int ww = zw - bw, hh = (ww - mw) * oh / ow + mh, zh = hh + bh;
1457                 if( rsz < hh ) rsz = hh;
1458                 int xx = zx + x1, yy = zy + y1;
1459                 int mx = x2 - zw, my = y2 - zh;
1460                 if( xx > mx ) xx = mx;
1461                 if( yy > my ) yy = my;
1462                 xx += lt + dz;  yy += top + dz;
1463                 zwindow->reposition(xx,yy, ww,hh);
1464                 if( zwindow->running() ) {
1465                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1466                         gui->lock_window("MWindow::tile_mixers");
1467                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1468                         gui->unlock_window();
1469                 }
1470                 if( ++n >= zn ) {
1471                         n = 0;  rsz += bh;
1472                         if( (zy += rsz) > (dy - rsz) ) dz += 10;
1473                         rsz = 0;
1474                         zx = 0;
1475                 }
1476                 else
1477                         zx += zw;
1478         }
1479 }
1480
1481 void MWindow::init_cache()
1482 {
1483         audio_cache = new CICache(preferences);
1484         video_cache = new CICache(preferences);
1485         frame_cache = new FrameCache;
1486         wave_cache = new WaveCache;
1487 }
1488
1489 void MWindow::init_channeldb()
1490 {
1491         channeldb_buz->load("channeldb_buz");
1492         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1493 }
1494
1495 void MWindow::init_menus()
1496 {
1497         char string[BCTEXTLEN];
1498
1499         // Color Models
1500         BC_CModels::to_text(string, BC_RGB888);
1501         colormodels.append(new ColormodelItem(string, BC_RGB888));
1502         BC_CModels::to_text(string, BC_RGBA8888);
1503         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1504 //      BC_CModels::to_text(string, BC_RGB161616);
1505 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1506 //      BC_CModels::to_text(string, BC_RGBA16161616);
1507 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1508         BC_CModels::to_text(string, BC_RGB_FLOAT);
1509         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1510         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1511         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1512         BC_CModels::to_text(string, BC_YUV888);
1513         colormodels.append(new ColormodelItem(string, BC_YUV888));
1514         BC_CModels::to_text(string, BC_YUVA8888);
1515         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1516 //      BC_CModels::to_text(string, BC_YUV161616);
1517 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1518 //      BC_CModels::to_text(string, BC_YUVA16161616);
1519 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1520
1521 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1522                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1523
1524 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1525                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1526
1527 #define ILACEFIXMETHODLISTADD(x) ilacefixmethod_to_text(string, x); \
1528                            interlace_asset_fixmethods.append(new InterlacefixmethodItem(string, x));
1529
1530         // Interlacing Modes
1531         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1532
1533         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1534         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1535
1536         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1537         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1538
1539         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1540         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1541
1542         // Interlacing Fixing Methods
1543         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_NONE);
1544         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_UPONE);
1545         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_DOWNONE);
1546 }
1547
1548 void MWindow::init_indexes()
1549 {
1550         mainindexes = new MainIndexes(this);
1551         mainindexes->start_loop();
1552 }
1553
1554 void MWindow::init_gui()
1555 {
1556         gui = new MWindowGUI(this);
1557         gui->lock_window("MWindow::init_gui");
1558         gui->create_objects();
1559         gui->unlock_window();
1560         gui->load_defaults(defaults);
1561 }
1562
1563 void MWindow::init_signals()
1564 {
1565         sighandler = new SigHandler;
1566         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1567 ENABLE_BUFFER
1568 }
1569
1570 void MWindow::init_render()
1571 {
1572         render = new Render(this);
1573         create_bd = new CreateBD_Thread(this);
1574         create_dvd = new CreateDVD_Thread(this);
1575         batch_render = new BatchRenderThread(this);
1576 }
1577
1578 void MWindow::init_exportedl()
1579 {
1580         exportedl = new ExportEDL(this);
1581 }
1582
1583 void MWindow::init_brender()
1584 {
1585         if(preferences->use_brender && !brender)
1586         {
1587                 brender_lock->lock("MWindow::init_brender 1");
1588                 brender = new BRender(this);
1589                 brender->initialize();
1590                 session->brender_end = 0;
1591                 brender_lock->unlock();
1592         }
1593         else
1594         if(!preferences->use_brender && brender)
1595         {
1596                 brender_lock->lock("MWindow::init_brender 2");
1597                 delete brender;
1598                 brender = 0;
1599                 session->brender_end = 0;
1600                 brender_lock->unlock();
1601         }
1602         brender_active = 0;
1603         stop_brender();
1604 }
1605
1606 void MWindow::restart_brender()
1607 {
1608 //printf("MWindow::restart_brender 1\n");
1609         if( !brender_active || !preferences->use_brender ) return;
1610         if( !brender ) return;
1611         brender->restart(edl);
1612 }
1613
1614 void MWindow::stop_brender()
1615 {
1616         if( !brender ) return;
1617 // cannot be holding mwindow->gui display lock
1618         brender->stop();
1619 }
1620
1621 int MWindow::brender_available(int position)
1622 {
1623         int result = 0;
1624         brender_lock->lock("MWindow::brender_available 1");
1625         if(brender && brender_active)
1626         {
1627                 if(brender->map_valid)
1628                 {
1629                         brender->map_lock->lock("MWindow::brender_available 2");
1630                         if(position < brender->map_size &&
1631                                 position >= 0)
1632                         {
1633 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1634                                 if(brender->map[position] == BRender::RENDERED)
1635                                         result = 1;
1636                         }
1637                         brender->map_lock->unlock();
1638                 }
1639         }
1640         brender_lock->unlock();
1641         return result;
1642 }
1643
1644 void MWindow::set_brender_active(int v, int update)
1645 {
1646         if( !preferences->use_brender ) v = 0;
1647         brender_active = v;
1648         gui->mainmenu->brender_active->set_checked(v);
1649         if( v != 0 ) {
1650                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1651                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1652
1653                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1654                         edl->session->brender_end = edl->tracks->total_video_length();
1655                 }
1656                 restart_brender();
1657         }
1658         else {
1659                 edl->session->brender_start = edl->session->brender_end = 0;
1660                 gui->unlock_window();
1661                 stop_brender();
1662                 gui->lock_window("MWindow::set_brender_active");
1663         }
1664         if( update ) {
1665                 gui->update_timebar(0);
1666                 gui->draw_overlays(1);
1667         }
1668 }
1669
1670 int MWindow::has_commercials()
1671 {
1672 #ifdef HAVE_COMMERCIAL
1673         return theme->use_commercials;
1674 #else
1675         return 0;
1676 #endif
1677 }
1678
1679 void MWindow::init_commercials()
1680 {
1681 #ifdef HAVE_COMMERCIAL
1682         if( !commercials ) {
1683                 commercials = new Commercials(this);
1684                 commercial_active = 0;
1685         }
1686         else
1687                 commercials->add_user();
1688 #endif
1689 }
1690
1691 void MWindow::commit_commercial()
1692 {
1693 #ifdef HAVE_COMMERCIAL
1694         if( !commercial_active ) return;
1695         commercial_active = 0;
1696         if( !commercials ) return;
1697         commercials->commitDb();
1698 #endif
1699 }
1700
1701 void MWindow::undo_commercial()
1702 {
1703 #ifdef HAVE_COMMERCIAL
1704         if( !commercial_active ) return;
1705         commercial_active = 0;
1706         if( !commercials ) return;
1707         commercials->undoDb();
1708 #endif
1709 }
1710
1711 int MWindow::put_commercial()
1712 {
1713         int result = 0;
1714 #ifdef HAVE_COMMERCIAL
1715         double start = edl->local_session->get_selectionstart();
1716         double end = edl->local_session->get_selectionend();
1717         if( start >= end ) return 0;
1718
1719         const char *errmsg = 0;
1720         int count = 0;
1721         Tracks *tracks = edl->tracks;
1722         //check it
1723         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1724                 if( track->data_type != TRACK_VIDEO ) continue;
1725                 if( !track->record ) continue;
1726                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1727                 ++count;
1728                 int64_t units_start = track->to_units(start,0);
1729                 int64_t units_end = track->to_units(end,0);
1730                 Edits *edits = track->edits;
1731                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1732                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1733                 if(!edit1 && !edit2) continue;  // nothing selected
1734                 if(!edit2) {                    // edit2 beyond end of track
1735                         edit2 = edits->last;
1736                         units_end = edits->length();
1737                 }
1738                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1739                 Indexable *indexable = edit1->get_source();
1740                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1741         }
1742         //run it
1743         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1744                 if( track->data_type != TRACK_VIDEO ) continue;
1745                 if( !track->record ) continue;
1746                 int64_t units_start = track->to_units(start,0);
1747                 int64_t units_end = track->to_units(end,0);
1748                 Edits *edits = track->edits;
1749                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1750                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1751                 if(!edit1 && !edit2) continue;  // nothing selected
1752                 if(!edit2) {                    // edit2 beyond end of track
1753                         edit2 = edits->last;
1754                         units_end = edits->length();
1755                 }
1756                 Indexable *indexable = edit1->get_source();
1757                 Asset *asset = (Asset *)indexable;
1758                 File *file = video_cache->check_out(asset, edl);
1759                 if( !file ) { errmsg = _("no file"); break; }
1760                 int64_t edit_length = units_end - units_start;
1761                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1762                 result = commercials->put_clip(file, edit1->channel,
1763                         track->from_units(edit_start), track->from_units(edit_length));
1764                 video_cache->check_in(asset);
1765                 if( result ) { errmsg = _("db failed"); break; }
1766         }
1767         if( errmsg ) {
1768                 char string[BCTEXTLEN];
1769                 sprintf(string, _("put_commercial: %s"), errmsg);
1770                 MainError::show_error(string);
1771                 undo_commercial();
1772                 result = 1;
1773         }
1774 #endif
1775         return result;
1776 }
1777
1778 void MWindow::stop_playback(int wait)
1779 {
1780         gui->stop_drawing();
1781
1782         cwindow->stop_playback(wait);
1783
1784         for(int i = 0; i < vwindows.size(); i++) {
1785                 VWindow *vwindow = vwindows[i];
1786                 if( !vwindow->is_running() ) continue;
1787                 vwindow->stop_playback(wait);
1788         }
1789         for(int i = 0; i < zwindows.size(); i++) {
1790                 ZWindow *zwindow = zwindows[i];
1791                 if( zwindow->idx < 0 ) continue;
1792                 zwindow->stop_playback(wait);
1793         }
1794 }
1795
1796 void MWindow::stop_transport()
1797 {
1798         gui->stop_transport(gui->get_window_lock() ? "MWindow::stop_transport" : 0);
1799 }
1800
1801 void MWindow::beep(double freq, double secs, double gain)
1802 {
1803         if( !proxy_beep ) proxy_beep = new ProxyBeep(this);
1804         proxy_beep->tone(freq, secs, gain);
1805 }
1806
1807 int MWindow::load_filenames(ArrayList<char*> *filenames,
1808         int load_mode,
1809         int update_filename)
1810 {
1811         ArrayList<EDL*> new_edls;
1812         ArrayList<Asset*> new_assets;
1813         ArrayList<File*> new_files;
1814         const int debug = 0;
1815 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1816
1817 //      save_defaults();
1818         gui->start_hourglass();
1819
1820 // Need to stop playback since tracking depends on the EDL not getting
1821 // deleted.
1822         gui->unlock_window();
1823         stop_playback(1);
1824         gui->lock_window("MWindow::load_filenames 0");
1825
1826 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1827         undo->update_undo_before();
1828
1829
1830 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1831
1832 // Define new_edls and new_assets to load
1833         int result = 0, ftype = -1;
1834
1835         for( int i=0; i<filenames->size(); ++i ) {
1836 // Get type of file
1837                 File *new_file = new File;
1838                 Asset *new_asset = new Asset(filenames->get(i));
1839                 EDL *new_edl = new EDL;
1840                 char string[BCTEXTLEN];
1841
1842                 new_edl->create_objects();
1843                 new_edl->copy_session(edl);
1844                 new_file->set_program(edl->session->program_no);
1845
1846                 sprintf(string, _("Loading %s"), new_asset->path);
1847                 gui->show_message(string);
1848 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1849
1850                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1851 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1852
1853                 result = 1;
1854                 switch( ftype ) {
1855 // Convert media file to EDL
1856                 case FILE_OK:
1857 // Warn about odd image dimensions
1858                         if( new_asset->video_data &&
1859                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
1860                                 char string[BCTEXTLEN];
1861                                 sprintf(string, _("%s's resolution is %dx%d.\nImages with odd dimensions may not decode properly."),
1862                                         new_asset->path, new_asset->width, new_asset->height);
1863                                 MainError::show_error(string);
1864                         }
1865
1866                         if( new_asset->program >= 0 &&
1867                             edl->session->program_no != new_asset->program ) {
1868                                 char string[BCTEXTLEN];
1869                                 sprintf(string, _("%s's index was built for program number %d\n"
1870                                         "Playback preference is %d.\n  Using program %d."),
1871                                         new_asset->path, new_asset->program,
1872                                         edl->session->program_no, new_asset->program);
1873                                 MainError::show_error(string);
1874                         }
1875
1876                         if( load_mode != LOADMODE_RESOURCESONLY ) {
1877                                 RecordLabels *labels = edl->session->label_cells ?
1878                                         new RecordLabels(new_file) : 0;
1879                                 asset_to_edl(new_edl, new_asset, labels);
1880                                 new_edls.append(new_edl);
1881                                 new_edl->add_user();
1882                                 delete labels;
1883                         }
1884                         else {
1885                                 new_assets.append(new_asset);
1886                                 new_asset->add_user();
1887                         }
1888
1889 // Set filename to nothing for assets since save EDL would overwrite them.
1890                         if( load_mode == LOADMODE_REPLACE ||
1891                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
1892                                 set_filename("");
1893 // Reset timeline position
1894                                 for( int i=0; i<TOTAL_PANES; ++i ) {
1895                                         new_edl->local_session->view_start[i] = 0;
1896                                         new_edl->local_session->track_start[i] = 0;
1897                                 }
1898                         }
1899
1900                         result = 0;
1901                         break;
1902
1903 // File not found
1904                 case FILE_NOT_FOUND:
1905                         sprintf(string, _("Failed to open %s"), new_asset->path);
1906                         gui->show_message(string, theme->message_error);
1907                         gui->update_default_message();
1908                         break;
1909
1910 // Unknown format
1911                 case FILE_UNRECOGNIZED_CODEC: {
1912 // Test index file
1913                         { IndexFile indexfile(this, new_asset);
1914                         if( !(result = indexfile.open_index()) )
1915                                 indexfile.close_index(); }
1916
1917 // Test existing EDLs
1918                         for( int j=0; result && j<new_edls.total; ++j ) {
1919                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
1920                                 if( old_asset ) {
1921                                         new_asset->copy_from(old_asset,1);
1922                                         result = 0;
1923                                 }
1924                         }
1925                         if( result ) {
1926                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
1927                                 if( old_asset ) {
1928                                         new_asset->copy_from(old_asset,1);
1929                                         result = 0;
1930                                 }
1931                         }
1932
1933 // Prompt user
1934                         if( result ) {
1935                                 char string[BCTEXTLEN];
1936                                 FileSystem fs;
1937                                 fs.extract_name(string, new_asset->path);
1938
1939                                 strcat(string, _("'s format couldn't be determined."));
1940                                 new_asset->audio_data = 1;
1941                                 new_asset->format = FILE_PCM;
1942                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
1943                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
1944                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
1945                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
1946                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
1947                                 new_asset->header = defaults->get("HEADER", 0);
1948
1949                                 FileFormat fwindow(this);
1950                                 fwindow.create_objects(new_asset, string);
1951                                 result = fwindow.run_window();
1952
1953                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
1954                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
1955                                 defaults->update("AUDIO_BITS", new_asset->bits);
1956                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
1957                                 defaults->update("SIGNED_", new_asset->signed_);
1958                                 defaults->update("HEADER", new_asset->header);
1959                                 save_defaults();
1960                         }
1961
1962 // Append to list
1963                         if( !result ) {
1964 // Recalculate length
1965                                 delete new_file;
1966                                 new_file = new File;
1967                                 result = new_file->open_file(preferences, new_asset, 1, 0);
1968
1969                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
1970                                         RecordLabels *labels = edl->session->label_cells ?
1971                                                 new RecordLabels(new_file) : 0;
1972                                         asset_to_edl(new_edl, new_asset, labels);
1973                                         new_edls.append(new_edl);
1974                                         new_edl->add_user();
1975                                         delete labels;
1976                                 }
1977                                 else {
1978                                         new_assets.append(new_asset);
1979                                         new_asset->add_user();
1980                                 }
1981                         }
1982                         else {
1983                                 result = 1;
1984                         }
1985                         break; }
1986
1987                 case FILE_IS_XML: {
1988                         FileXML xml_file;
1989 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1990                         xml_file.read_from_file(filenames->get(i));
1991 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1992                         const char *cin_version = 0;
1993                         while( !xml_file.read_tag() ) {
1994                                 if( xml_file.tag.title_is("EDL") ) {
1995                                         cin_version = xml_file.tag.get_property("VERSION");
1996                                         break;
1997                                 }
1998                         }
1999                         xml_file.rewind();
2000                         if( !cin_version ) {
2001                                 eprintf(_("XML file %s\n not from cinelerra."),filenames->get(i));
2002                                 char string[BCTEXTLEN];
2003                                 sprintf(string,_("Unknown %s"), filenames->get(i));
2004                                 gui->show_message(string);
2005                                 result = 1;
2006                                 break;
2007                         }
2008                         if( strcmp(cin_version, CINELERRA_VERSION) ) {
2009                                 char string[BCTEXTLEN];
2010                                 snprintf(string, sizeof(string),
2011                                          _("Warning: XML from cinelerra version %s\n"
2012                                         "Session data may be incompatible."), cin_version);
2013                                 show_warning(&preferences->warn_version, string);
2014                         }
2015                         if( load_mode == LOADMODE_NESTED ) {
2016 // Load temporary EDL for nesting.
2017                                 EDL *nested_edl = new EDL;
2018                                 nested_edl->create_objects();
2019                                 nested_edl->load_xml(&xml_file, LOAD_ALL);
2020 //printf("MWindow::load_filenames %p %s\n", nested_edl, nested_edl->project_path);
2021                                 new_edl->create_nested(nested_edl);
2022                                 new_edl->set_path(filenames->get(i));
2023                                 nested_edl->Garbage::remove_user();
2024                         }
2025                         else {
2026 // Load EDL for pasting
2027                                 new_edl->load_xml(&xml_file, LOAD_ALL);
2028 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2029                                 test_plugins(new_edl, filenames->get(i));
2030 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2031
2032                                 if( load_mode == LOADMODE_REPLACE ||
2033                                     load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2034                                         strcpy(session->filename, filenames->get(i));
2035                                         strcpy(new_edl->local_session->clip_title,
2036                                                 filenames->get(i));
2037                                         if(update_filename)
2038                                                 set_filename(new_edl->local_session->clip_title);
2039                                 }
2040                                 else if( load_mode == LOADMODE_RESOURCESONLY ) {
2041                                         strcpy(new_edl->local_session->clip_title,
2042                                                 filenames->get(i));
2043                                         struct stat st;
2044                                         time_t t = !stat(filenames->get(i),&st) ?
2045                                                 st.st_mtime : time(&t);
2046                                         ctime_r(&t, new_edl->local_session->clip_notes);
2047                                 }
2048                         }
2049
2050                         new_edls.append(new_edl);
2051                         new_edl->add_user();
2052                         result = 0;
2053                         break; }
2054                 }
2055
2056                 new_edl->Garbage::remove_user();
2057                 new_asset->Garbage::remove_user();
2058
2059 // Store for testing index
2060                 new_files.append(new_file);
2061         }
2062
2063 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2064
2065
2066         if(!result) {
2067                 gui->reset_default_message();
2068                 gui->default_message();
2069         }
2070
2071
2072 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2073
2074 // Paste them.
2075 // Don't back up here.
2076         if(new_edls.size())
2077         {
2078 // For pasting, clear the active region
2079                 if(load_mode == LOADMODE_PASTE ||
2080                         load_mode == LOADMODE_NESTED)
2081                 {
2082                         double start = edl->local_session->get_selectionstart();
2083                         double end = edl->local_session->get_selectionend();
2084                         if(!EQUIV(start, end))
2085                                 edl->clear(start,
2086                                         end,
2087                                         edl->session->labels_follow_edits,
2088                                         edl->session->plugins_follow_edits,
2089                                         edl->session->autos_follow_edits);
2090                 }
2091
2092                 paste_edls(&new_edls, load_mode, 0, -1,
2093                         edl->session->labels_follow_edits,
2094                         edl->session->plugins_follow_edits,
2095                         edl->session->autos_follow_edits,
2096                         0); // overwrite
2097         }
2098
2099
2100
2101
2102 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2103
2104 // Add new assets to EDL and schedule assets for index building.
2105         int got_indexes = 0;
2106         for( int i=0; i<new_edls.size(); ++i ) {
2107                 EDL *new_edl = new_edls[i];
2108                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2109                         mainindexes->add_next_asset(0, new_edl->nested_edls[j]);
2110                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2111                         got_indexes = 1;
2112                 }
2113
2114         }
2115
2116 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2117         for( int i=0; i<new_assets.size(); ++i ) {
2118                 Asset *new_asset = new_assets[i];
2119
2120                 File *new_file = 0;
2121                 int got_it = 0;
2122                 for( int j=0; j<new_files.size(); ++j ) {
2123                         new_file = new_files[j];
2124                         if( !strcmp(new_file->asset->path, new_asset->path) ) {
2125                                 got_it = 1;
2126                                 break;
2127                         }
2128                 }
2129
2130                 mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
2131                 edl->assets->update(new_asset);
2132                 got_indexes = 1;
2133         }
2134 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2135
2136 // Start examining next batch of index files
2137         if(got_indexes) mainindexes->start_build();
2138 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2139
2140 // Open plugin GUIs
2141         Track *track = edl->tracks->first;
2142         while(track)
2143         {
2144                 for(int j = 0; j < track->plugin_set.size(); j++)
2145                 {
2146                         PluginSet *plugins = track->plugin_set[j];
2147                         Plugin *plugin = plugins->get_first_plugin();
2148
2149                         while(plugin)
2150                         {
2151                                 if(load_mode == LOADMODE_REPLACE ||
2152                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
2153                                 {
2154                                         if(plugin->plugin_type == PLUGIN_STANDALONE &&
2155                                                 plugin->show)
2156                                         {
2157                                                 show_plugin(plugin);
2158                                         }
2159                                 }
2160
2161                                 plugin = (Plugin*)plugin->next;
2162                         }
2163                 }
2164
2165                 track = track->next;
2166         }
2167
2168         // if just opening one new resource in replace mode
2169         if( ftype != FILE_IS_XML &&
2170             ( load_mode == LOADMODE_REPLACE ||
2171               load_mode == LOADMODE_REPLACE_CONCATENATE ) ) {
2172                 select_asset(0, 0);
2173                 edl->session->proxy_scale = 1;
2174                 edl->session->proxy_disabled_scale = 1;
2175                 edl->session->proxy_use_scaler = 0;
2176                 edl->session->proxy_auto_scale = 0;
2177                 edl->session->proxy_beep = 0;
2178                 edl->local_session->preview_start = 0;
2179                 edl->local_session->preview_end = 0;
2180                 edl->local_session->loop_playback = 0;
2181                 edl->local_session->set_selectionstart(0);
2182                 edl->local_session->set_selectionend(0);
2183                 set_brender_active(0, 0);
2184                 fit_selection();
2185                 goto_start();
2186         }
2187
2188         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
2189             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
2190                 ArrayList<Indexable *> orig_idxbls;
2191                 for( int i=0; i<new_assets.size(); ++i )
2192                         orig_idxbls.append(new_assets.get(i));
2193                 for( int i=0; i<new_edls.size(); ++i ) {
2194                         EDL *new_edl = new_edls[i];
2195                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2196                                 if( track->data_type != TRACK_VIDEO ) continue;
2197                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2198                                         Indexable *idxbl = (Indexable *)edit->asset;
2199                                         if( !idxbl ) continue;
2200                                         if( !idxbl->have_video() ) continue;
2201                                         if( edit->channel != 0 ) continue; // first layer only
2202                                         orig_idxbls.append(edit->asset);
2203                                 }
2204                         }
2205                 }
2206                 gui->unlock_window(); // to update progress bar
2207                 int ret = render_proxy(orig_idxbls);
2208                 gui->lock_window("MWindow::load_filenames");
2209                 if( ret >= 0 && edl->session->proxy_beep ) {
2210                         if( ret > 0 )
2211                                 beep(2000., 1.5, 0.5);
2212                         else
2213                                 beep(4000., 0.25, 0.5);
2214                 }
2215         }
2216
2217 // need to update undo before project, since mwindow is unlocked & a new load
2218 // can begin here.  Should really prevent loading until we're done.
2219 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2220         undo->update_undo_after(_("load"), LOAD_ALL);
2221
2222         for(int i = 0; i < new_edls.size(); i++)
2223         {
2224                 new_edls[i]->remove_user();
2225         }
2226 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2227
2228         new_edls.remove_all();
2229
2230         for(int i = 0; i < new_assets.size(); i++)
2231         {
2232                 new_assets[i]->Garbage::remove_user();
2233         }
2234
2235         new_assets.remove_all();
2236         new_files.remove_all_objects();
2237
2238
2239 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2240         if(load_mode == LOADMODE_REPLACE ||
2241                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2242         {
2243                 session->changes_made = 0;
2244         }
2245         else
2246         {
2247                 session->changes_made = 1;
2248         }
2249
2250         gui->stop_hourglass();
2251
2252
2253 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2254         update_project(load_mode);
2255
2256 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2257
2258         return 0;
2259 }
2260
2261 int MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2262 {
2263         Asset *format_asset = new Asset;
2264         format_asset->format = FILE_FFMPEG;
2265         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2266         ProxyRender proxy_render(this, format_asset);
2267         int new_scale = edl->session->proxy_scale;
2268         int use_scaler = edl->session->proxy_use_scaler;
2269
2270         for( int i=0; i<new_idxbls.size(); ++i ) {
2271                 Indexable *orig = new_idxbls.get(i);
2272                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2273                 if( !proxy ) continue;
2274                 FileSystem fs;
2275                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2276                 int got_it = exists && // if proxy exists, and is newer than orig
2277                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2278                 if( got_it ) continue;
2279                 proxy_render.add_needed(orig, proxy);
2280         }
2281
2282 // render needed proxies
2283         int result = proxy_render.create_needed_proxies(new_scale);
2284         if( !result ) {
2285                 add_proxy(use_scaler,
2286                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2287         }
2288         format_asset->remove_user();
2289         return !result ? proxy_render.needed_proxies.size() : -1;
2290 }
2291
2292 int MWindow::enable_proxy()
2293 {
2294         int ret = 0;
2295         if( edl->session->proxy_scale == 1 &&
2296             edl->session->proxy_disabled_scale != 1 ) {
2297                 int new_scale = edl->session->proxy_disabled_scale;
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);
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                 edl->session->proxy_disabled_scale = edl->session->proxy_scale;
2315                 Asset *asset = new Asset;
2316                 asset->format = FILE_FFMPEG;
2317                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2318                 to_proxy(asset, 1);
2319                 asset->remove_user();
2320         }
2321         return 1;
2322 }
2323
2324 int MWindow::to_proxy(Asset *asset, int new_scale)
2325 {
2326         ArrayList<Indexable*> orig_idxbls;
2327         ArrayList<Indexable*> proxy_assets;
2328
2329         edl->Garbage::add_user();
2330         save_backup();
2331         undo->update_undo_before(_("proxy"), this);
2332         ProxyRender proxy_render(this, asset);
2333
2334 // revert project to original size from current size
2335 // remove all session proxy assets at the at the current proxy_scale
2336         int proxy_scale = edl->session->proxy_scale;
2337         int proxy_use_scaler = edl->session->proxy_use_scaler;
2338
2339         if( proxy_scale > 1 ) {
2340                 Asset *orig_asset = edl->assets->first;
2341                 for( ; orig_asset; orig_asset=orig_asset->next ) {
2342                         char new_path[BCTEXTLEN];
2343                         proxy_render.to_proxy_path(new_path, orig_asset, proxy_scale);
2344 // test if proxy asset was already added to proxy_assets
2345                         int got_it = 0;
2346                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2347                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2348                         if( got_it ) continue;
2349                         Asset *proxy_asset = edl->assets->get_asset(new_path);
2350                         if( !proxy_asset ) continue;
2351 // add pointer to existing EDL asset if it exists
2352 // EDL won't delete it unless it's the same pointer.
2353                         proxy_assets.append(proxy_asset);
2354                         proxy_asset->add_user();
2355                         orig_idxbls.append(orig_asset);
2356                         orig_asset->add_user();
2357                 }
2358                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2359                         EDL *orig_nested = edl->nested_edls[i];
2360                         char new_path[BCTEXTLEN];
2361                         if( !ProxyRender::from_proxy_path(new_path, orig_nested, proxy_scale) )
2362                                 continue;
2363                         proxy_render.to_proxy_path(new_path, orig_nested, proxy_scale);
2364 // test if proxy asset was already added to proxy_assets
2365                         int got_it = 0;
2366                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2367                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2368                         if( got_it ) continue;
2369                         Asset *proxy_nested = edl->assets->get_asset(new_path);
2370                         if( !proxy_nested ) continue;
2371 // add pointer to existing EDL asset if it exists
2372 // EDL won't delete it unless it's the same pointer.
2373                         proxy_assets.append(proxy_nested);
2374                         proxy_nested->add_user();
2375                         orig_idxbls.append(orig_nested);
2376                         orig_nested->add_user();
2377                 }
2378
2379 // convert from the proxy assets to the original assets
2380                 edl->set_proxy(1, 0, &proxy_assets, &orig_idxbls);
2381
2382 // remove the references
2383                 for( int i=0; i<proxy_assets.size(); ++i ) {
2384                         Asset *proxy = (Asset *) proxy_assets[i];
2385                         proxy->width = proxy->actual_width;
2386                         proxy->height = proxy->actual_height;
2387                         proxy->remove_user();
2388                         edl->assets->remove_pointer(proxy);
2389                         proxy->remove_user();
2390                 }
2391                 proxy_assets.remove_all();
2392                 for( int i = 0; i < orig_idxbls.size(); i++ )
2393                         orig_idxbls[i]->remove_user();
2394                 orig_idxbls.remove_all();
2395         }
2396
2397         ArrayList<char *> confirm_paths;    // test for new files
2398         confirm_paths.set_array_delete();
2399
2400 // convert to new size if not original size
2401         if( new_scale != 1 ) {
2402                 FileSystem fs;
2403                 Asset *orig = edl->assets->first;
2404                 for( ; orig; orig=orig->next ) {
2405                         Asset *proxy = proxy_render.add_original(orig, new_scale);
2406                         if( !proxy ) continue;
2407                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2408                         int got_it = exists && // if proxy exists, and is newer than orig
2409                             fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2410                         if( !got_it ) {
2411                                 if( exists ) // prompt user to overwrite
2412                                         confirm_paths.append(cstrdup(proxy->path));
2413                                 proxy_render.add_needed(orig, proxy);
2414                         }
2415                 }
2416                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2417                         EDL *orig_nested = edl->nested_edls[i];
2418                         Asset *proxy = proxy_render.add_original(orig_nested, new_scale);
2419                         if( !proxy ) continue;
2420                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2421                         int got_it = exists && // if proxy exists, and is newer than orig_nested
2422                             fs.get_date(proxy->path) > fs.get_date(orig_nested->path) ? 1 : 0;
2423                         if( !got_it ) {
2424                                 if( exists ) // prompt user to overwrite
2425                                         confirm_paths.append(cstrdup(proxy->path));
2426                                 proxy_render.add_needed(orig_nested, proxy);
2427                         }
2428                 }
2429         }
2430
2431         int result = 0;
2432 // test for existing files
2433         if( confirm_paths.size() ) {
2434                 result = ConfirmSave::test_files(this, &confirm_paths);
2435                 confirm_paths.remove_all_objects();
2436         }
2437
2438         if( !result )
2439                 result = proxy_render.create_needed_proxies(new_scale);
2440
2441         if( !result ) // resize project
2442                 edl->set_proxy(new_scale, proxy_use_scaler,
2443                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2444
2445         undo->update_undo_after(_("proxy"), LOAD_ALL);
2446         edl->Garbage::remove_user();
2447         restart_brender();
2448
2449         gui->lock_window("MWindow::to_proxy");
2450         update_project(LOADMODE_REPLACE);
2451         gui->unlock_window();
2452
2453         return !result ? proxy_render.needed_proxies.size() : -1;
2454 }
2455
2456 void MWindow::test_plugins(EDL *new_edl, char *path)
2457 {
2458         char string[BCTEXTLEN];
2459
2460 // Do a check whether plugins exist
2461         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2462                 for( int k=0; k<track->plugin_set.total; ++k ) {
2463                         PluginSet *plugin_set = track->plugin_set[k];
2464                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2465                                         plugin; plugin = (Plugin*)plugin->next ) {
2466                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2467 // ok we need to find it in plugindb
2468                                 PluginServer *server =
2469                                         scan_plugindb(plugin->title, track->data_type);
2470                                 if( !server || server->transition ) {
2471                                         sprintf(string,
2472         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2473           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2474                                                 "effect", _(plugin->title), path);
2475                                         MainError::show_error(string);
2476                                 }
2477                         }
2478                 }
2479
2480                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2481                         if( !edit->transition ) continue;
2482 // ok we need to find transition in plugindb
2483                         PluginServer *server =
2484                                 scan_plugindb(edit->transition->title, track->data_type);
2485                         if( !server || !server->transition ) {
2486                                 sprintf(string,
2487         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2488           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2489                                         "transition", _(edit->transition->title), path);
2490                                 MainError::show_error(string);
2491                         }
2492                 }
2493         }
2494 }
2495
2496
2497 void MWindow::init_shm(const char *pfn, int64_t min)
2498 {
2499         int64_t result = 0;
2500 // Fix shared memory
2501         FILE *fd = fopen(pfn, "r");
2502         if( fd ) {
2503                 fscanf(fd, "%jd", &result);
2504                 fclose(fd);
2505                 if( result >= min ) return;
2506         }
2507
2508         fd = fopen(pfn, "w");
2509         if( !fd ) return;
2510         fprintf(fd, "0x%jx", min);
2511         fclose(fd);
2512
2513         fd = fopen(pfn, "r");
2514         if( !fd ) {
2515                 eprintf(_("MWindow::init_shm: couldn't open %s for reading.\n"), pfn);
2516                 return;
2517         }
2518
2519         fscanf(fd, "%jd", &result);
2520         fclose(fd);
2521         if( result < min ) {
2522                 eprintf(_("MWindow::init_shm: %s is %p.\n"
2523                         "you probably need to be root, or:\n"
2524                         "as root, run: echo 0x%jx > %s\n"
2525                         "before trying to start cinelerra.\n"
2526                         "It should be at least 0x%jx for Cinelerra.\n"),
2527                         pfn, (void *)result, min, pfn, min);
2528         }
2529 }
2530
2531 void MWindow::create_objects(int want_gui,
2532         int want_new,
2533         char *config_path)
2534 {
2535         const int debug = 0;
2536         if(debug) PRINT_TRACE
2537
2538 // For some reason, init_signals must come after show_splash or the signals won't
2539 // get trapped.
2540         init_signals();
2541         if(debug) PRINT_TRACE
2542         init_3d();
2543
2544         if(debug) PRINT_TRACE
2545         show_splash();
2546
2547         if(debug) PRINT_TRACE
2548         default_standard = default_std();
2549         init_defaults(defaults, config_path);
2550         check_language();
2551         init_preferences();
2552         if(splash_window)
2553                 splash_window->operation->update(_("Initializing Plugins"));
2554         init_plugins(this, preferences);
2555         if(debug) PRINT_TRACE
2556         init_ladspa_plugins(this, preferences);
2557         if(debug) PRINT_TRACE
2558         init_plugin_tips(*plugindb, cin_lang);
2559         if(splash_window)
2560                 splash_window->operation->update(_("Initializing GUI"));
2561         if(debug) PRINT_TRACE
2562         init_theme();
2563
2564         if(debug) PRINT_TRACE
2565         init_error();
2566
2567         if(splash_window)
2568                 splash_window->operation->update(_("Initializing Fonts"));
2569         char string[BCTEXTLEN];
2570         strcpy(string, preferences->plugin_dir);
2571         strcat(string, "/" FONT_SEARCHPATH);
2572         BC_Resources::init_fontconfig(string);
2573         if(debug) PRINT_TRACE
2574
2575 // Default project created here
2576         init_edl();
2577         if(debug) PRINT_TRACE
2578
2579         init_cache();
2580         if(debug) PRINT_TRACE
2581
2582         Timer timer;
2583
2584         init_awindow();
2585         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2586
2587         init_compositor();
2588         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2589
2590 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2591         if(session->show_vwindow)
2592                 get_viewer(1, DEFAULT_VWINDOW);
2593         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2594
2595         init_gui();
2596         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2597
2598         init_levelwindow();
2599         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2600
2601         init_indexes();
2602         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2603
2604         init_channeldb();
2605         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2606
2607         init_gwindow();
2608         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2609
2610         init_render();
2611         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2612
2613         init_brender();
2614         init_exportedl();
2615         init_commercials();
2616         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2617         mainprogress = new MainProgress(this, gui);
2618         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2619         undo = new MainUndo(this);
2620
2621         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2622
2623         plugin_guis = new ArrayList<PluginServer*>;
2624         dead_plugins = new ArrayList<PluginServer*>;
2625         keyframe_threads = new ArrayList<KeyFrameThread*>;
2626
2627         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2628                 __LINE__,
2629                 vwindows.size(),
2630                 session->show_vwindow);
2631
2632 // Show all vwindows
2633 //      if(session->show_vwindow) {
2634 //              for(int j = 0; j < vwindows.size(); j++) {
2635 //                      VWindow *vwindow = vwindows[j];
2636 //                      if( !vwindow->is_running() ) continue;
2637 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2638 //                              __LINE__,
2639 //                              vwindow);
2640 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2641 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2642 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2643 //                      vwindow->gui->show_window();
2644 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2645 //                      vwindow->gui->unlock_window();
2646 //              }
2647 //      }
2648
2649
2650         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2651
2652         if(session->show_cwindow)
2653         {
2654                 cwindow->gui->lock_window("MWindow::create_objects 1");
2655                 cwindow->gui->show_window();
2656                 cwindow->gui->unlock_window();
2657         }
2658
2659         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2660         if(session->show_awindow)
2661         {
2662                 awindow->gui->lock_window("MWindow::create_objects 1");
2663                 awindow->gui->show_window();
2664                 awindow->gui->unlock_window();
2665         }
2666
2667         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2668         if(session->show_lwindow)
2669         {
2670                 lwindow->gui->lock_window("MWindow::create_objects 1");
2671                 lwindow->gui->show_window();
2672                 lwindow->gui->unlock_window();
2673         }
2674
2675         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2676                 __LINE__,
2677                 (int)timer.get_difference(),
2678                 gwindow->gui);
2679         if(session->show_gwindow)
2680         {
2681                 gwindow->gui->lock_window("MWindow::create_objects 1");
2682                 gwindow->gui->show_window();
2683                 gwindow->gui->unlock_window();
2684         }
2685
2686         if(debug) PRINT_TRACE
2687
2688         gui->lock_window("MWindow::create_objects 1");
2689         gui->mainmenu->load_defaults(defaults);
2690         gui->mainmenu->update_toggles(0);
2691         gui->update_patchbay();
2692         gui->draw_canvas(0, 0);
2693         gui->draw_cursor(1);
2694         gui->show_window();
2695         gui->raise_window();
2696         gui->unlock_window();
2697
2698         if(debug) PRINT_TRACE
2699
2700         if(preferences->use_tipwindow)
2701                 init_tipwindow();
2702         if(debug) PRINT_TRACE
2703
2704         gui->add_keyboard_listener(
2705                 (int (BC_WindowBase::*)(BC_WindowBase *))
2706                 &MWindowGUI::keyboard_listener);
2707
2708         hide_splash();
2709         init_shm("/proc/sys/kernel/shmmax", 0x7fffffff);
2710         init_shm("/proc/sys/kernel/shmmni", 0x4000);
2711         if(debug) PRINT_TRACE
2712
2713         BC_WindowBase::get_resources()->vframe_shm = 1;
2714 }
2715
2716
2717 void MWindow::show_splash()
2718 {
2719 #include "data/heroine_logo9_png.h"
2720         VFrame *frame = new VFramePng(heroine_logo9_png);
2721         BC_DisplayInfo dpyi;
2722         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2723         int rr = (rw < rh ? rw : rh) / 4;
2724         splash_window = new SplashGUI(frame, rr, rr);
2725         splash_window->create_objects();
2726 }
2727
2728 void MWindow::hide_splash()
2729 {
2730         if(splash_window)
2731                 delete splash_window;
2732         splash_window = 0;
2733 }
2734
2735
2736 void MWindow::start()
2737 {
2738 ENABLE_BUFFER
2739 //PRINT_TRACE
2740 //      vwindows[DEFAULT_VWINDOW]->start();
2741         awindow->start();
2742 //PRINT_TRACE
2743         cwindow->start();
2744 //PRINT_TRACE
2745         lwindow->start();
2746 //PRINT_TRACE
2747         gwindow->start();
2748 //PRINT_TRACE
2749 //      Thread::start();
2750 //PRINT_TRACE
2751         playback_3d->start();
2752 //PRINT_TRACE
2753 }
2754
2755 void MWindow::run()
2756 {
2757         run_lock->lock("MWindow::run");
2758         gui->run_window();
2759         stop_playback(1);
2760
2761         brender_lock->lock("MWindow::run 1");
2762         delete brender;         brender = 0;
2763         brender_lock->unlock();
2764
2765         interrupt_indexes();
2766         clean_indexes();
2767         save_defaults();
2768         run_lock->unlock();
2769 }
2770
2771 void MWindow::show_vwindow()
2772 {
2773         int total_running = 0;
2774         session->show_vwindow = 1;
2775
2776 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2777 // Raise all windows which are visible
2778         for(int j = 0; j < vwindows.size(); j++) {
2779                 VWindow *vwindow = vwindows[j];
2780                 if( !vwindow->is_running() ) continue;
2781                 vwindow->gui->lock_window("MWindow::show_vwindow");
2782                 vwindow->gui->show_window(0);
2783                 vwindow->gui->raise_window();
2784                 vwindow->gui->flush();
2785                 vwindow->gui->unlock_window();
2786                 total_running++;
2787         }
2788
2789 // If no windows visible
2790         if(!total_running)
2791         {
2792                 get_viewer(1, DEFAULT_VWINDOW);
2793         }
2794
2795         gui->mainmenu->show_vwindow->set_checked(1);
2796 }
2797
2798 void MWindow::show_awindow()
2799 {
2800         session->show_awindow = 1;
2801         awindow->gui->lock_window("MWindow::show_awindow");
2802         awindow->gui->show_window();
2803         awindow->gui->raise_window();
2804         awindow->gui->flush();
2805         awindow->gui->unlock_window();
2806         gui->mainmenu->show_awindow->set_checked(1);
2807 }
2808
2809 char *MWindow::get_cwindow_display()
2810 {
2811         char *x11_host = screens < 2 || session->window_config == 0 ?
2812                 session->a_x11_host : session->b_x11_host;
2813         return *x11_host ? x11_host : 0;
2814 }
2815
2816 void MWindow::show_cwindow()
2817 {
2818         session->show_cwindow = 1;
2819         cwindow->show_window();
2820         gui->mainmenu->show_cwindow->set_checked(1);
2821 }
2822
2823 void MWindow::show_gwindow()
2824 {
2825         session->show_gwindow = 1;
2826
2827         gwindow->gui->lock_window("MWindow::show_gwindow");
2828         gwindow->gui->show_window();
2829         gwindow->gui->raise_window();
2830         gwindow->gui->flush();
2831         gwindow->gui->unlock_window();
2832
2833         gui->mainmenu->show_gwindow->set_checked(1);
2834 }
2835 void MWindow::hide_gwindow()
2836 {
2837         session->show_gwindow = 0;
2838
2839         gwindow->gui->lock_window("MWindow::show_gwindow");
2840         gwindow->gui->hide_window();
2841         gwindow->gui->unlock_window();
2842 }
2843
2844 void MWindow::show_lwindow()
2845 {
2846         session->show_lwindow = 1;
2847         lwindow->gui->lock_window("MWindow::show_lwindow");
2848         lwindow->gui->show_window();
2849         lwindow->gui->raise_window();
2850         lwindow->gui->flush();
2851         lwindow->gui->unlock_window();
2852         gui->mainmenu->show_lwindow->set_checked(1);
2853 }
2854
2855 int MWindow::tile_windows(int window_config)
2856 {
2857         int need_reload = 0;
2858         int play_config = window_config==0 ? 0 : 1;
2859         edl->session->playback_config->load_defaults(defaults, play_config);
2860         session->default_window_positions(window_config);
2861         if( screens == 1 ) {
2862                 gui->default_positions();
2863                 sync_parameters(CHANGE_ALL);
2864         }
2865         else
2866                 need_reload = 1;
2867         return need_reload;
2868 }
2869
2870 void MWindow::toggle_loop_playback()
2871 {
2872         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2873         set_loop_boundaries();
2874         save_backup();
2875
2876         gui->draw_overlays(1);
2877         sync_parameters(CHANGE_PARAMS);
2878 }
2879
2880 //void MWindow::set_titles(int value)
2881 //{
2882 //      edl->session->show_titles = value;
2883 //      trackmovement(edl->local_session->track_start);
2884 //}
2885
2886 void MWindow::set_screens(int value)
2887 {
2888         screens = value;
2889 }
2890
2891 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2892 {
2893         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2894         edl->session->auto_keyframes = value;
2895         gui->mbuttons->edit_panel->keyframe->update(value);
2896         gui->flush();
2897         if(lock_mwindow) gui->unlock_window();
2898
2899         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2900         cwindow->gui->edit_panel->keyframe->update(value);
2901         cwindow->gui->flush();
2902         if(lock_cwindow) cwindow->gui->unlock_window();
2903 }
2904
2905 void MWindow::set_auto_visibility(Autos *autos, int value)
2906 {
2907         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2908                 edl->session->auto_conf->plugins = value;
2909         else if( autos->autoidx >= 0 )
2910                 edl->session->auto_conf->autos[autos->autoidx] = value;
2911         else
2912                 return;
2913
2914         gui->update(0, 1, 0, 0, 0, 0, 0);
2915         gui->mainmenu->update_toggles(1);
2916         gui->unlock_window();
2917         gwindow->gui->update_toggles(1);
2918         gui->lock_window("MWindow::set_auto_visibility");
2919 }
2920
2921 void MWindow::set_keyframe_type(int mode)
2922 {
2923         gui->lock_window("MWindow::set_keyframe_type");
2924         edl->local_session->floatauto_type = mode;
2925         gui->mainmenu->update_toggles(0);
2926         gui->unlock_window();
2927 }
2928
2929 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
2930 {
2931         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
2932         edl->session->editing_mode = new_editing_mode;
2933         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
2934         gui->mbuttons->edit_panel->update();
2935         gui->set_editing_mode(1);
2936         if(lock_mwindow) gui->unlock_window();
2937
2938
2939         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
2940         cwindow->gui->edit_panel->update();
2941         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
2942         if(lock_cwindow) cwindow->gui->unlock_window();
2943         return 0;
2944 }
2945
2946 void MWindow::toggle_editing_mode()
2947 {
2948         int mode = edl->session->editing_mode;
2949         if( mode == EDITING_ARROW )
2950                 set_editing_mode(EDITING_IBEAM, 0, 1);
2951         else
2952                 set_editing_mode(EDITING_ARROW, 0, 1);
2953 }
2954
2955
2956 void MWindow::set_labels_follow_edits(int value)
2957 {
2958         gui->lock_window("MWindow::set_labels_follow_edits");
2959         edl->session->labels_follow_edits = value;
2960         gui->mbuttons->edit_panel->locklabels->update(value);
2961         gui->mainmenu->labels_follow_edits->set_checked(value);
2962         gui->flush();
2963         gui->unlock_window();
2964 }
2965
2966 void MWindow::sync_parameters(int change_type)
2967 {
2968         if( in_destructor ) return;
2969
2970 // Sync engines which are playing back
2971         if(cwindow->playback_engine->is_playing_back)
2972         {
2973                 if(change_type == CHANGE_PARAMS)
2974                 {
2975 // TODO: block keyframes until synchronization is done
2976                         cwindow->playback_engine->sync_parameters(edl);
2977                 }
2978                 else
2979 // Stop and restart
2980                 {
2981                         int command = cwindow->playback_engine->command->command;
2982                         cwindow->playback_engine->que->send_command(STOP,
2983                                 CHANGE_NONE,
2984                                 0,
2985                                 0);
2986 // Waiting for tracking to finish would make the restart position more
2987 // accurate but it can't lock the window to stop tracking for some reason.
2988 // Not waiting for tracking gives a faster response but restart position is
2989 // only as accurate as the last tracking update.
2990                         cwindow->playback_engine->interrupt_playback(0);
2991                         cwindow->playback_engine->que->send_command(command,
2992                                         change_type,
2993                                         edl,
2994                                         1,
2995                                         0);
2996                 }
2997         }
2998         else
2999         {
3000                 cwindow->refresh_frame(change_type);
3001         }
3002 }
3003
3004 void MWindow::age_caches()
3005 {
3006 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
3007 // __LINE__,
3008 // preferences->cache_size,
3009 // audio_cache->get_memory_usage(1),
3010 // video_cache->get_memory_usage(1),
3011 // frame_cache->get_memory_usage(),
3012 // wave_cache->get_memory_usage(),
3013 // memory_usage);
3014         frame_cache->age_cache(512);
3015         wave_cache->age_cache(8192);
3016
3017         int64_t memory_usage;
3018         int64_t prev_memory_usage = 0;
3019         int result = 0;
3020         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
3021         while( !result && prev_memory_usage !=
3022                 (memory_usage=video_cache->get_memory_usage(1)) &&
3023                 memory_usage > video_size ) {
3024                 video_cache->delete_oldest();
3025                 prev_memory_usage = memory_usage;
3026         }
3027
3028         prev_memory_usage = 0;
3029         result = 0;
3030         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
3031         while( !result && prev_memory_usage !=
3032                 (memory_usage=audio_cache->get_memory_usage(1)) &&
3033                 memory_usage > audio_size ) {
3034                 audio_cache->delete_oldest();
3035                 prev_memory_usage = memory_usage;
3036         }
3037 }
3038
3039 void MWindow::reset_android_remote()
3040 {
3041         gui->use_android_remote(preferences->android_remote);
3042 }
3043
3044
3045 void MWindow::show_keyframe_gui(Plugin *plugin)
3046 {
3047         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
3048 // Find existing thread
3049         for(int i = 0; i < keyframe_threads->size(); i++)
3050         {
3051                 if(keyframe_threads->get(i)->plugin == plugin)
3052                 {
3053                         keyframe_threads->get(i)->start_window(plugin, 0);
3054                         keyframe_gui_lock->unlock();
3055                         return;
3056                 }
3057         }
3058
3059 // Find unused thread
3060         for(int i = 0; i < keyframe_threads->size(); i++)
3061         {
3062                 if(!keyframe_threads->get(i)->plugin)
3063                 {
3064                         keyframe_threads->get(i)->start_window(plugin, 0);
3065                         keyframe_gui_lock->unlock();
3066                         return;
3067                 }
3068         }
3069
3070 // Create new thread
3071         KeyFrameThread *thread = new KeyFrameThread(this);
3072         keyframe_threads->append(thread);
3073         thread->start_window(plugin, 0);
3074
3075         keyframe_gui_lock->unlock();
3076 }
3077
3078
3079
3080
3081
3082 void MWindow::show_plugin(Plugin *plugin)
3083 {
3084         int done = 0;
3085
3086 SET_TRACE
3087 // Remove previously deleted plugin GUIs
3088         dead_plugin_lock->lock("MWindow::show_plugin");
3089         dead_plugins->remove_all_objects();
3090         dead_plugin_lock->unlock();
3091
3092 //printf("MWindow::show_plugin %d\n", __LINE__);
3093 SET_TRACE
3094
3095
3096         plugin_gui_lock->lock("MWindow::show_plugin");
3097         for(int i = 0; i < plugin_guis->total; i++)
3098         {
3099 // Pointer comparison
3100                 if(plugin_guis->get(i)->plugin == plugin)
3101                 {
3102                         plugin_guis->get(i)->raise_window();
3103                         done = 1;
3104                         break;
3105                 }
3106         }
3107 SET_TRACE
3108
3109 //printf("MWindow::show_plugin 1\n");
3110         if( !done && !plugin->track ) {
3111                 printf("MWindow::show_plugin track not defined.\n");
3112                 done = 1;
3113         }
3114         if( !done ) {
3115                 PluginServer *server = scan_plugindb(plugin->title,
3116                         plugin->track->data_type);
3117
3118 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
3119                 if(server && server->uses_gui)
3120                 {
3121                         PluginServer *gui = new PluginServer(*server);
3122                         plugin_guis->append(gui);
3123 // Needs mwindow to do GUI
3124                         gui->set_mwindow(this);
3125                         gui->open_plugin(0, preferences, edl, plugin);
3126                         plugin->show = 1;
3127                         gui->show_gui();
3128                 }
3129         }
3130         plugin_gui_lock->unlock();
3131 //printf("MWindow::show_plugin %d\n", __LINE__);
3132 SET_TRACE
3133 //sleep(1);
3134 //printf("MWindow::show_plugin 2\n");
3135 }
3136
3137 void MWindow::hide_plugin(Plugin *plugin, int lock)
3138 {
3139         plugin->show = 0;
3140 // Update the toggle
3141         gui->lock_window("MWindow::hide_plugin");
3142         gui->update(0, 1, 0, 0, 0, 0, 0);
3143         gui->unlock_window();
3144
3145         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
3146         for(int i = 0; i < plugin_guis->total; i++)
3147         {
3148                 if(plugin_guis->get(i)->plugin == plugin)
3149                 {
3150                         PluginServer *ptr = plugin_guis->get(i);
3151                         plugin_guis->remove(ptr);
3152                         if(lock) plugin_gui_lock->unlock();
3153 // Last command executed in client side close
3154 // Schedule for deletion
3155                         ptr->hide_gui();
3156                         delete_plugin(ptr);
3157 //sleep(1);
3158                         return;
3159                 }
3160         }
3161         if(lock) plugin_gui_lock->unlock();
3162 }
3163
3164 void MWindow::delete_plugin(PluginServer *plugin)
3165 {
3166         dead_plugin_lock->lock("MWindow::delete_plugin");
3167         dead_plugins->append(plugin);
3168         dead_plugin_lock->unlock();
3169 }
3170
3171 void MWindow::hide_plugins()
3172 {
3173         plugin_gui_lock->lock("MWindow::hide_plugins 1");
3174         while(plugin_guis->size())
3175         {
3176                 PluginServer *ptr = plugin_guis->get(0);
3177                 plugin_guis->remove(ptr);
3178                 plugin_gui_lock->unlock();
3179 // Last command executed in client side close
3180 // Schedule for deletion
3181                 ptr->hide_gui();
3182                 delete_plugin(ptr);
3183                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
3184         }
3185         plugin_gui_lock->unlock();
3186
3187         hide_keyframe_guis();
3188 }
3189
3190 void MWindow::hide_keyframe_guis()
3191 {
3192         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
3193         for(int i = 0; i < keyframe_threads->size(); i++)
3194         {
3195                 keyframe_threads->get(i)->close_window();
3196         }
3197         keyframe_gui_lock->unlock();
3198 }
3199
3200 void MWindow::hide_keyframe_gui(Plugin *plugin)
3201 {
3202         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
3203         for(int i = 0; i < keyframe_threads->size(); i++)
3204         {
3205                 if(keyframe_threads->get(i)->plugin == plugin)
3206                 {
3207                         keyframe_threads->get(i)->close_window();
3208                         break;
3209                 }
3210         }
3211         keyframe_gui_lock->unlock();
3212 }
3213
3214 void MWindow::update_keyframe_guis()
3215 {
3216 // Send new configuration to keyframe GUI's
3217         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
3218         for(int i = 0; i < keyframe_threads->size(); i++)
3219         {
3220                 KeyFrameThread *ptr = keyframe_threads->get(i);
3221                 if(edl->tracks->plugin_exists(ptr->plugin))
3222                         ptr->update_gui(1);
3223                 else
3224                 {
3225                         ptr->close_window();
3226                 }
3227         }
3228         keyframe_gui_lock->unlock();
3229 }
3230
3231 void MWindow::update_plugin_guis(int do_keyframe_guis)
3232 {
3233 // Send new configuration to plugin GUI's
3234         plugin_gui_lock->lock("MWindow::update_plugin_guis");
3235
3236         for(int i = 0; i < plugin_guis->size(); i++)
3237         {
3238                 PluginServer *ptr = plugin_guis->get(i);
3239                 if(edl->tracks->plugin_exists(ptr->plugin))
3240                         ptr->update_gui();
3241                 else
3242                 {
3243 // Schedule for deletion if no plugin
3244                         plugin_guis->remove_number(i);
3245                         i--;
3246
3247                         ptr->hide_gui();
3248                         delete_plugin(ptr);
3249                 }
3250         }
3251
3252
3253 // Change plugin variable if not visible
3254         Track *track = edl->tracks->first;
3255         while(track)
3256         {
3257                 for(int i = 0; i < track->plugin_set.size(); i++)
3258                 {
3259                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3260                         while(plugin)
3261                         {
3262                                 int got_it = 0;
3263                                 for(int i = 0; i < plugin_guis->size(); i++)
3264                                 {
3265                                         PluginServer *server = plugin_guis->get(i);
3266                                         if(server->plugin == plugin)
3267                                         {
3268                                                 got_it = 1;
3269                                                 break;
3270                                         }
3271                                 }
3272
3273                                 if(!got_it) plugin->show = 0;
3274
3275                                 plugin = (Plugin*)plugin->next;
3276                         }
3277                 }
3278
3279                 track = track->next;
3280         }
3281
3282         plugin_gui_lock->unlock();
3283
3284
3285         if(do_keyframe_guis) update_keyframe_guis();
3286 }
3287
3288 int MWindow::plugin_gui_open(Plugin *plugin)
3289 {
3290         int result = 0;
3291         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3292         for(int i = 0; i < plugin_guis->total; i++)
3293         {
3294                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3295                 {
3296                         result = 1;
3297                         break;
3298                 }
3299         }
3300         plugin_gui_lock->unlock();
3301         return result;
3302 }
3303
3304 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3305 {
3306         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3307         for(int i = 0; i < plugin_guis->total; i++)
3308         {
3309                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3310                 {
3311                         plugin_guis->get(i)->render_gui(data);
3312                         break;
3313                 }
3314         }
3315         plugin_gui_lock->unlock();
3316 }
3317
3318 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3319 {
3320         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3321         for(int i = 0; i < plugin_guis->total; i++)
3322         {
3323                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3324                 {
3325                         plugin_guis->get(i)->render_gui(data, size);
3326                         break;
3327                 }
3328         }
3329         plugin_gui_lock->unlock();
3330 }
3331
3332
3333 void MWindow::update_plugin_states()
3334 {
3335         plugin_gui_lock->lock("MWindow::update_plugin_states");
3336         for(int i = 0; i < plugin_guis->total; i++)
3337         {
3338                 int result = 0;
3339 // Get a plugin GUI
3340                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
3341                 PluginServer *src_plugingui = plugin_guis->get(i);
3342
3343 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
3344                 for(Track *track = edl->tracks->first;
3345                         track && !result;
3346                         track = track->next)
3347                 {
3348                         for(int j = 0;
3349                                 j < track->plugin_set.total && !result;
3350                                 j++)
3351                         {
3352                                 PluginSet *plugin_set = track->plugin_set[j];
3353                                 for(Plugin *plugin = (Plugin*)plugin_set->first;
3354                                         plugin && !result;
3355                                         plugin = (Plugin*)plugin->next)
3356                                 {
3357                                         if(plugin == src_plugin &&
3358                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
3359                                 }
3360                         }
3361                 }
3362
3363
3364 // Doesn't exist anymore
3365                 if(!result)
3366                 {
3367                         hide_plugin(src_plugin, 0);
3368                         i--;
3369                 }
3370         }
3371         plugin_gui_lock->unlock();
3372 }
3373
3374
3375 void MWindow::update_plugin_titles()
3376 {
3377         for(int i = 0; i < plugin_guis->total; i++)
3378         {
3379                 plugin_guis->get(i)->update_title();
3380         }
3381 }
3382
3383 int MWindow::asset_to_edl(EDL *new_edl,
3384         Asset *new_asset,
3385         RecordLabels *labels)
3386 {
3387 const int debug = 0;
3388 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3389 __LINE__,
3390 new_asset->layers);
3391 // Keep frame rate, sample rate, and output size unchanged.
3392 // These parameters would revert the project if VWindow displayed an asset
3393 // of different size than the project.
3394         if(new_asset->video_data)
3395         {
3396                 new_edl->session->video_tracks = new_asset->layers;
3397         }
3398         else
3399                 new_edl->session->video_tracks = 0;
3400
3401 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3402
3403
3404
3405
3406
3407         if(new_asset->audio_data)
3408         {
3409                 new_edl->session->audio_tracks = new_asset->channels;
3410         }
3411         else
3412                 new_edl->session->audio_tracks = 0;
3413 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3414
3415 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3416         new_edl->create_default_tracks();
3417 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3418 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3419
3420
3421
3422 //printf("MWindow::asset_to_edl 3\n");
3423         new_edl->insert_asset(new_asset,
3424                 0,
3425                 0,
3426                 0,
3427                 labels);
3428 //printf("MWindow::asset_to_edl 3\n");
3429 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3430
3431 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3432         if(edl->session->cursor_on_frames)
3433         {
3434                 double length = new_edl->tracks->total_length();
3435                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3436                 new_edl->tracks->clear(length, edl_length, 1, 1);
3437         }
3438
3439
3440
3441
3442         char string[BCTEXTLEN];
3443         FileSystem fs;
3444         fs.extract_name(string, new_asset->path);
3445 //printf("MWindow::asset_to_edl 3\n");
3446
3447         strcpy(new_edl->local_session->clip_title, string);
3448 //printf("MWindow::asset_to_edl 4 %s\n", string);
3449 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3450
3451         return 0;
3452 }
3453
3454
3455 // Reset everything after a load.
3456 void MWindow::update_project(int load_mode)
3457 {
3458         const int debug = 0;
3459
3460         if(debug) PRINT_TRACE
3461         edl->tracks->update_y_pixels(theme);
3462
3463         if(debug) PRINT_TRACE
3464
3465         if(load_mode == LOADMODE_REPLACE ||
3466                 load_mode == LOADMODE_REPLACE_CONCATENATE)
3467         {
3468                 gui->load_panes();
3469         }
3470
3471         gui->update(1, 1, 1, 1, 1, 1, 1);
3472         if(debug) PRINT_TRACE
3473         gui->unlock_window();
3474         init_brender();
3475
3476         cwindow->gui->lock_window("MWindow::update_project 1");
3477         cwindow->update(0, 0, 1, 1, 1);
3478         cwindow->gui->unlock_window();
3479
3480         if(debug) PRINT_TRACE
3481
3482 // Close all the vwindows
3483         if( load_mode == LOADMODE_REPLACE ||
3484             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3485                 if(debug) PRINT_TRACE
3486                 int first_vwindow = 0;
3487                 if(session->show_vwindow) first_vwindow = 1;
3488 // Change visible windows to no source
3489                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3490                         VWindow *vwindow = vwindows[i];
3491                         if( !vwindow->is_running() ) continue;
3492                         vwindow->change_source(-1);
3493                 }
3494
3495 // Close remaining windows
3496                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3497                         VWindow *vwindow = vwindows[i];
3498                         if( !vwindow->is_running() ) continue;
3499                         vwindow->close_window();
3500                 }
3501                 for( int i=0; i<edl->vwindow_edls.size(); ++i ) {
3502                         VWindow *vwindow = get_viewer(1, -1);
3503                         vwindow->change_source(i);
3504                 }
3505                 if(debug) PRINT_TRACE
3506                 select_zwindow(0);
3507                 close_mixers(0);
3508
3509                 for( int i=0; i<edl->mixers.size(); ++i ) {
3510                         Mixer *mixer = edl->mixers[i];
3511                         ZWindow *zwindow = get_mixer(mixer);
3512                         zwindow->set_title(mixer->title);
3513                         zwindow->start();
3514                 }
3515         }
3516         else {
3517                 if(vwindows.size()) {
3518                         VWindow *vwindow = vwindows[DEFAULT_VWINDOW];
3519                         if( vwindow->is_running() ) {
3520                                 vwindow->gui->lock_window("MWindow::update_project");
3521                                 vwindow->update(1);
3522                                 vwindow->gui->unlock_window();
3523                         }
3524                 }
3525         }
3526
3527         if(debug) PRINT_TRACE
3528         cwindow->gui->lock_window("MWindow::update_project 2");
3529         cwindow->gui->timebar->update(0);
3530         cwindow->gui->unlock_window();
3531
3532         if(debug) PRINT_TRACE
3533         cwindow->refresh_frame(CHANGE_ALL);
3534
3535         awindow->gui->async_update_assets();
3536         if(debug) PRINT_TRACE
3537
3538         gui->lock_window("MWindow::update_project");
3539         gui->update_mixers(0, 0);
3540         gui->flush();
3541         if(debug) PRINT_TRACE
3542 }
3543
3544 void MWindow::remove_indexfile(Indexable *indexable)
3545 {
3546         if( !indexable->is_asset ) return;
3547         Asset *asset = (Asset *)indexable;
3548 // Erase file
3549         IndexFile::delete_index(preferences, asset, ".toc");
3550         IndexFile::delete_index(preferences, asset, ".idx");
3551         IndexFile::delete_index(preferences, asset, ".mkr");
3552 }
3553
3554 void MWindow::rebuild_indices()
3555 {
3556         for(int i = 0; i < session->drag_assets->total; i++)
3557         {
3558                 Indexable *indexable = session->drag_assets->get(i);
3559 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3560                 remove_indexfile(indexable);
3561 // Schedule index build
3562                 IndexState *index_state = indexable->index_state;
3563                 index_state->index_status = INDEX_NOTTESTED;
3564                 if( indexable->is_asset ) {
3565                         Asset *asset = (Asset *)indexable;
3566                         if( asset->format != FILE_PCM ) {
3567                                 asset->format = FILE_UNKNOWN;
3568                                 asset->reset_audio();
3569                         }
3570                         asset->reset_video();
3571                         remove_asset_from_caches(asset);
3572 //                      File file; // re-probe the asset
3573 //                      file.open_file(preferences, asset, 1, 0);
3574                 }
3575                 mainindexes->add_next_asset(0, indexable);
3576         }
3577         mainindexes->start_build();
3578 }
3579
3580
3581 void MWindow::save_backup()
3582 {
3583         FileXML file;
3584         edl->optimize();
3585         edl->set_path(session->filename);
3586         char backup_path[BCTEXTLEN], backup_path1[BCTEXTLEN];
3587         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3588                 File::get_config_path(), BACKUP_FILE);
3589         snprintf(backup_path1, sizeof(backup_path1), "%s/%s",
3590                 File::get_config_path(), BACKUP_FILE1);
3591         rename(backup_path, backup_path1);
3592         edl->save_xml(&file, backup_path);
3593         file.terminate_string();
3594         FileSystem fs;
3595         fs.complete_path(backup_path);
3596
3597         if(file.write_to_file(backup_path))
3598         {
3599                 char string2[256];
3600                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
3601                 gui->show_message(string2);
3602         }
3603 }
3604
3605 void MWindow::load_backup()
3606 {
3607         ArrayList<char*> path_list;
3608         path_list.set_array_delete();
3609         char *out_path;
3610         char backup_path[BCTEXTLEN];
3611         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3612                 File::get_config_path(), BACKUP_FILE);
3613         FileSystem fs;
3614         fs.complete_path(backup_path);
3615
3616         path_list.append(out_path = new char[strlen(backup_path) + 1]);
3617         strcpy(out_path, backup_path);
3618
3619         load_filenames(&path_list, LOADMODE_REPLACE, 0);
3620         edl->local_session->clip_title[0] = 0;
3621 // This is unique to backups since the path of the backup is different than the
3622 // path of the project.
3623         set_filename(edl->path);
3624         path_list.remove_all_objects();
3625         save_backup();
3626 }
3627
3628
3629 void MWindow::save_undo_data()
3630 {
3631         char perpetual_path[BCTEXTLEN];
3632         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
3633                 File::get_config_path(), PERPETUAL_FILE);
3634         FILE *fp = fopen(perpetual_path,"w");
3635         if( !fp ) return;
3636         undo->save(fp);
3637         fclose(fp);
3638 }
3639
3640 void MWindow::load_undo_data()
3641 {
3642         char perpetual_path[BCTEXTLEN];
3643         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
3644                 File::get_config_path(), PERPETUAL_FILE);
3645         FILE *fp = fopen(perpetual_path,"r");
3646         if( !fp ) return;
3647         undo->load(fp);
3648         fclose(fp);
3649 }
3650
3651 static inline int gcd(int m, int n)
3652 {
3653         int r;
3654         if( m < n ) { r = m;  m = n;  n = r; }
3655         while( (r = m % n) != 0 ) { m = n;  n = r; }
3656         return n;
3657 }
3658
3659 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
3660 {
3661         w = 1;  h = 1;
3662         if(!width || !height) return 1;
3663         if( width == 720 && (height == 480 || height == 576) ) {
3664                 w = 4;  h = 3;  return 0; // for NTSC and PAL
3665         }
3666         double ar = (double)width / height;
3667 // square-ish pixels
3668         if( EQUIV(ar, 1.0000) ) return 0;
3669         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
3670         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
3671         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
3672         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
3673         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
3674         int ww = width, hh = height;
3675         // numerator, denominator must be under mx
3676         int mx = 255, n = gcd(ww, hh);
3677         if( n > 1 ) { ww /= n; hh /= n; }
3678         // search near height in case extra/missing lines
3679         if( ww >= mx || hh >= mx ) {
3680                 double err = height;  // +/- 2 percent height
3681                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
3682                         int iw = width, ih = height+i;
3683                         if( (n=gcd(iw, ih)) > 1 ) {
3684                                 int u = iw/n;  if( u >= mx ) continue;
3685                                 int v = ih/n;  if( v >= mx ) continue;
3686                                 double r = (double) u/v, er = fabs(ar-r);
3687                                 if( er >= err ) continue;
3688                                 err = er;  ww = u;  hh = v;
3689                         }
3690                 }
3691         }
3692
3693         w = ww;  h = hh;
3694         return 0;
3695 }
3696
3697 void MWindow::reset_caches()
3698 {
3699         frame_cache->remove_all();
3700         wave_cache->remove_all();
3701         audio_cache->remove_all();
3702         video_cache->remove_all();
3703         if( cwindow->playback_engine ) {
3704                 if( cwindow->playback_engine->audio_cache )
3705                         cwindow->playback_engine->audio_cache->remove_all();
3706                 if( cwindow->playback_engine->video_cache )
3707                         cwindow->playback_engine->video_cache->remove_all();
3708         }
3709         for(int i = 0; i < vwindows.size(); i++) {
3710                 VWindow *vwindow = vwindows[i];
3711                 if( !vwindow->is_running() ) continue;
3712                 if( !vwindow->playback_engine ) continue;
3713                 if( vwindow->playback_engine->audio_cache )
3714                         vwindow->playback_engine->audio_cache->remove_all();
3715                 if( vwindow->playback_engine->video_cache )
3716                         vwindow->playback_engine->video_cache->remove_all();
3717         }
3718 }
3719
3720 void MWindow::remove_asset_from_caches(Asset *asset)
3721 {
3722         frame_cache->remove_asset(asset);
3723         wave_cache->remove_asset(asset);
3724         audio_cache->delete_entry(asset);
3725         video_cache->delete_entry(asset);
3726         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3727                 cwindow->playback_engine->audio_cache->delete_entry(asset);
3728         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3729                 cwindow->playback_engine->video_cache->delete_entry(asset);
3730         for(int i = 0; i < vwindows.size(); i++) {
3731                 VWindow *vwindow = vwindows[i];
3732                 if( !vwindow->is_running() ) continue;
3733                 if( !vwindow->playback_engine ) continue;
3734                 if( vwindow->playback_engine->audio_cache )
3735                         vwindow->playback_engine->audio_cache->delete_entry(asset);
3736                 if( vwindow->playback_engine->video_cache )
3737                         vwindow->playback_engine->video_cache->delete_entry(asset);
3738         }
3739 }
3740
3741
3742 void MWindow::remove_assets_from_project(int push_undo, int redraw,
3743                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
3744 {
3745         for(int i = 0; i < drag_assets->total; i++) {
3746                 Indexable *indexable = drag_assets->get(i);
3747                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
3748         }
3749
3750 // Remove from VWindow.
3751         for(int i = 0; i < session->drag_clips->total; i++) {
3752                 for(int j = 0; j < vwindows.size(); j++) {
3753                         VWindow *vwindow = vwindows[j];
3754                         if( !vwindow->is_running() ) continue;
3755                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
3756                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
3757                                 vwindow->delete_source(1, 1);
3758                                 vwindow->gui->unlock_window();
3759                         }
3760                 }
3761         }
3762
3763         for(int i = 0; i < drag_assets->size(); i++) {
3764                 for(int j = 0; j < vwindows.size(); j++) {
3765                         VWindow *vwindow = vwindows[j];
3766                         if( !vwindow->is_running() ) continue;
3767                         if(drag_assets->get(i) == vwindow->get_source()) {
3768                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
3769                                 vwindow->delete_source(1, 1);
3770                                 vwindow->gui->unlock_window();
3771                         }
3772                 }
3773         }
3774
3775         for(int i = 0; i < drag_assets->size(); i++) {
3776                 Indexable *indexable = drag_assets->get(i);
3777                 remove_indexfile(indexable);
3778         }
3779
3780 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3781         if(push_undo) undo->update_undo_before();
3782         if(drag_assets) edl->remove_from_project(drag_assets);
3783         if(drag_clips) edl->remove_from_project(drag_clips);
3784         if(redraw) save_backup();
3785         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
3786         if(redraw) {
3787                 restart_brender();
3788
3789                 gui->lock_window("MWindow::remove_assets_from_project 3");
3790                 gui->update(1, 1, 1, 1, 0, 1, 0);
3791                 gui->unlock_window();
3792
3793         // Removes from playback here
3794                 sync_parameters(CHANGE_ALL);
3795         }
3796
3797         awindow->gui->async_update_assets();
3798 }
3799
3800 void MWindow::remove_assets_from_disk()
3801 {
3802 // Remove from disk
3803         for(int i = 0; i < session->drag_assets->total; i++)
3804         {
3805                 remove(session->drag_assets->get(i)->path);
3806         }
3807
3808         remove_assets_from_project(1,
3809                 1,
3810                 session->drag_assets,
3811                 session->drag_clips);
3812 }
3813
3814 void MWindow::dump_plugins(FILE *fp)
3815 {
3816         if( !plugindb ) return;
3817         for(int i = 0; i < plugindb->total; i++)
3818         {
3819                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
3820                         " synth=%d transition=%d theme=%d %s\n",
3821                         plugindb->get(i)->plugin_type,
3822                         plugindb->get(i)->audio,
3823                         plugindb->get(i)->video,
3824                         plugindb->get(i)->realtime,
3825                         plugindb->get(i)->multichannel,
3826                         plugindb->get(i)->get_synthesis(),
3827                         plugindb->get(i)->transition,
3828                         plugindb->get(i)->theme,
3829                         plugindb->get(i)->title);
3830         }
3831 }
3832
3833 void MWindow::dump_edl(FILE *fp)
3834 {
3835         if( !edl ) return;
3836         edl->dump(fp);
3837 }
3838
3839 void MWindow::dump_undo(FILE *fp)
3840 {
3841         if( !undo ) return;
3842         undo->dump(fp);
3843 }
3844
3845 void MWindow::dump_exe(FILE *fp)
3846 {
3847         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
3848         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
3849
3850         int ret = -1, n = 100;
3851         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
3852                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
3853                 ret = 0;
3854         }
3855         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
3856
3857         struct stat st;
3858         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
3859         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
3860         struct tm *tm = localtime(&st.st_mtime);
3861         char mtime[256];
3862         strftime(mtime, sizeof(mtime), "%F %T", tm);
3863         fprintf(fp,"mtime: %s\n", mtime);
3864 #if 0
3865 // people hit ctl-c waiting for this
3866         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
3867         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
3868         uint8_t *bfr = 0;
3869         int64_t bfrsz = 0;
3870         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
3871         int64_t maxsz = 1024*pagsz;
3872         int64_t size = st.st_size, pos = 0;
3873         SHA1 sha1;
3874         while( (bfrsz = size-pos) > 0 ) {
3875                 if( bfrsz > maxsz ) bfrsz = maxsz;
3876                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
3877                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
3878                 if( bfr == MAP_FAILED ) break;
3879                 sha1.addBytes(bfr, bfrsz);
3880                 munmap(bfr, bfrsz);
3881                 pos += bfrsz;
3882         }
3883         close(fd);
3884         ret = pos < size ? EIO : 0;
3885         fprintf(fp, "SHA1: ");
3886         uint8_t digest[20];  sha1.computeHash(digest);
3887         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
3888         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
3889         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
3890 #endif
3891         fprintf(fp, "\n");
3892 }
3893
3894 void MWindow::trap_hook(FILE *fp, void *vp)
3895 {
3896         MWindow *mwindow = (MWindow *)vp;
3897 //      fprintf(fp, "\nPLUGINS:\n");
3898 //      mwindow->dump_plugins(fp);
3899         fprintf(fp, "\nEDL:\n");
3900         mwindow->dump_edl(fp);
3901         fprintf(fp, "\nUNDO:\n");
3902         mwindow->dump_undo(fp);
3903         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
3904         mwindow->dump_exe(fp);
3905 }
3906
3907
3908
3909
3910
3911
3912 int MWindow::save_defaults()
3913 {
3914         gui->save_defaults(defaults);
3915         edl->save_defaults(defaults);
3916         session->save_defaults(defaults);
3917         preferences->save_defaults(defaults);
3918
3919         for(int i = 0; i < plugin_guis->total; i++)
3920         {
3921 // Pointer comparison
3922                 plugin_guis->get(i)->save_defaults();
3923         }
3924         awindow->save_defaults(defaults);
3925
3926         defaults->save();
3927         return 0;
3928 }
3929
3930 int MWindow::run_script(FileXML *script)
3931 {
3932         int result = 0, result2 = 0;
3933         while(!result && !result2)
3934         {
3935                 result = script->read_tag();
3936                 if(!result)
3937                 {
3938                         if(script->tag.title_is("new_project"))
3939                         {
3940 // Run new in immediate mode.
3941 //                              gui->mainmenu->new_project->run_script(script);
3942                         }
3943                         else
3944                         if(script->tag.title_is("record"))
3945                         {
3946 // Run record as a thread.  It is a terminal command.
3947                                 ;
3948 // Will read the complete scipt file without letting record read it if not
3949 // terminated.
3950                                 result2 = 1;
3951                         }
3952                         else
3953                         {
3954                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
3955                         }
3956                 }
3957         }
3958         return result2;
3959 }
3960
3961 // ================================= synchronization
3962
3963
3964 int MWindow::interrupt_indexes()
3965 {
3966         mainprogress->cancelled = 1;
3967         mainindexes->interrupt_build();
3968         return 0;
3969 }
3970
3971
3972
3973 void MWindow::next_time_format()
3974 {
3975         switch(edl->session->time_format)
3976         {
3977                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
3978                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
3979                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3980                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
3981                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
3982                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
3983                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
3984         }
3985
3986         time_format_common();
3987 }
3988
3989 void MWindow::prev_time_format()
3990 {
3991         switch(edl->session->time_format)
3992         {
3993                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
3994                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
3995                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
3996                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3997                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
3998                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
3999                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
4000         }
4001
4002         time_format_common();
4003 }
4004
4005 void MWindow::time_format_common()
4006 {
4007         gui->lock_window("MWindow::next_time_format");
4008         gui->redraw_time_dependancies();
4009
4010
4011         char string[BCTEXTLEN], string2[BCTEXTLEN];
4012         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
4013         gui->show_message(string);
4014         gui->flush();
4015         gui->unlock_window();
4016 }
4017
4018
4019 int MWindow::set_filename(const char *filename)
4020 {
4021         if( filename != session->filename )
4022                 strcpy(session->filename, filename);
4023         if( filename != edl->path )
4024                 strcpy(edl->path, filename);
4025
4026         if(gui)
4027         {
4028                 if(filename[0] == 0)
4029                 {
4030                         gui->set_title(PROGRAM_NAME);
4031                 }
4032                 else
4033                 {
4034                         FileSystem dir;
4035                         char string[BCTEXTLEN], string2[BCTEXTLEN];
4036                         dir.extract_name(string, filename);
4037                         sprintf(string2, PROGRAM_NAME ": %s", string);
4038                         gui->set_title(string2);
4039                 }
4040         }
4041         return 0;
4042 }
4043
4044
4045
4046
4047
4048
4049
4050
4051 int MWindow::set_loop_boundaries()
4052 {
4053         double start = edl->local_session->get_selectionstart();
4054         double end = edl->local_session->get_selectionend();
4055
4056         if(start !=
4057                 end)
4058         {
4059                 ;
4060         }
4061         else
4062         if(edl->tracks->total_length())
4063         {
4064                 start = 0;
4065                 end = edl->tracks->total_length();
4066         }
4067         else
4068         {
4069                 start = end = 0;
4070         }
4071
4072         if(edl->local_session->loop_playback && start != end)
4073         {
4074                 edl->local_session->loop_start = start;
4075                 edl->local_session->loop_end = end;
4076         }
4077         return 0;
4078 }
4079
4080
4081
4082
4083
4084
4085
4086 int MWindow::reset_meters()
4087 {
4088         cwindow->gui->lock_window("MWindow::reset_meters 1");
4089         cwindow->gui->meters->reset_meters();
4090         cwindow->gui->unlock_window();
4091
4092         for(int j = 0; j < vwindows.size(); j++) {
4093                 VWindow *vwindow = vwindows[j];
4094                 if( !vwindow->is_running() ) continue;
4095                 vwindow->gui->lock_window("MWindow::reset_meters 2");
4096                 vwindow->gui->meters->reset_meters();
4097                 vwindow->gui->unlock_window();
4098         }
4099
4100         lwindow->gui->lock_window("MWindow::reset_meters 3");
4101         lwindow->gui->panel->reset_meters();
4102         lwindow->gui->unlock_window();
4103
4104         gui->lock_window("MWindow::reset_meters 4");
4105         gui->reset_meters();
4106         gui->unlock_window();
4107         return 0;
4108 }
4109
4110
4111 void MWindow::resync_guis()
4112 {
4113 // Update GUIs
4114         restart_brender();
4115         gui->lock_window("MWindow::resync_guis");
4116         gui->update(1, 1, 1, 1, 1, 1, 0);
4117         gui->unlock_window();
4118
4119         cwindow->gui->lock_window("MWindow::resync_guis");
4120         cwindow->gui->resize_event(cwindow->gui->get_w(),
4121                 cwindow->gui->get_h());
4122         int channels = edl->session->audio_channels;
4123         cwindow->gui->meters->set_meters(channels, 1);
4124         cwindow->gui->flush();
4125         cwindow->gui->unlock_window();
4126
4127         for(int i = 0; i < vwindows.size(); i++) {
4128                 VWindow *vwindow = vwindows[i];
4129                 if( !vwindow->is_running() ) continue;
4130                 vwindow->gui->lock_window("MWindow::resync_guis");
4131                 vwindow->gui->resize_event(vwindow->gui->get_w(),
4132                         vwindow->gui->get_h());
4133                 vwindow->gui->meters->set_meters(channels, 1);
4134                 vwindow->gui->flush();
4135                 vwindow->gui->unlock_window();
4136         }
4137
4138         lwindow->gui->lock_window("MWindow::resync_guis");
4139         lwindow->gui->panel->set_meters(channels, 1);
4140         lwindow->gui->flush();
4141         lwindow->gui->unlock_window();
4142
4143 // Warn user
4144         if(((edl->session->output_w % 4) ||
4145                 (edl->session->output_h % 4)) &&
4146                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
4147         {
4148                 MainError::show_error(
4149                         _("This project's dimensions are not multiples of 4 so\n"
4150                         "it can't be rendered by OpenGL."));
4151         }
4152
4153
4154 // Flash frame
4155         sync_parameters(CHANGE_ALL);
4156 }
4157
4158 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
4159 {
4160         File *file = new File;
4161         EDLSession *session = edl->session;
4162         double old_framerate = session->frame_rate;
4163         double old_samplerate = session->sample_rate;
4164         int old_auto_keyframes = session->auto_keyframes;
4165         session->auto_keyframes = 0;
4166         int result = file->open_file(preferences, asset, 1, 0);
4167         if( !result && delete_tracks > 0 )
4168                 undo->update_undo_before();
4169         int video_layers = asset->get_video_layers();
4170         if( !result && asset->video_data && vstream < video_layers ) {
4171                 // try to get asset up to date, may fail
4172                 file->select_video_stream(asset, vstream);
4173                 // either way use what was/is there.
4174                 double framerate = asset->get_frame_rate();
4175                 int width = asset->get_w();
4176                 int height = asset->get_h();
4177                 // must be multiple of 4 for opengl
4178                 width = (width+3) & ~3;  height = (height+3) & ~3;
4179                 int driver = session->playback_config->vconfig->driver;
4180                 int color_model = file->get_best_colormodel(asset, driver);
4181 //              color_model = BC_CModels::is_yuv(color_model) ?
4182 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
4183 //                      BC_CModels::is_float(color_model) ?
4184 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
4185 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
4186 // have alpha for now
4187                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
4188                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
4189                 session->color_model = color_model;
4190                 session->output_w = width;
4191                 session->output_h = height;
4192                 session->frame_rate = framerate;
4193                 // not, asset->actual_width/actual_height
4194                 asset->width = session->output_w;
4195                 asset->height = session->output_h;
4196                 asset->frame_rate = session->frame_rate;
4197                 create_aspect_ratio(session->aspect_w, session->aspect_h,
4198                         session->output_w, session->output_h);
4199                 Track *track = edl->tracks->first;
4200                 for( Track *next_track=0; track; track=next_track ) {
4201                         next_track = track->next;
4202                         if( track->data_type != TRACK_VIDEO ) continue;
4203                         if( delete_tracks ) {
4204                                 Edit *edit = track->edits->first;
4205                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
4206                                         next_edit = edit->next;
4207                                         if( edit->channel != vstream ||
4208                                             !edit->asset || !edit->asset->is_asset ||
4209                                             !asset->equivalent(*edit->asset,1,1,edl) )
4210                                                 delete edit;
4211                                 }
4212                         }
4213                         if( track->edits->first ) {
4214                                 track->track_w = edl->session->output_w;
4215                                 track->track_h = edl->session->output_h;
4216                         }
4217                         else if( delete_tracks )
4218                                 edl->tracks->delete_track(track);
4219                 }
4220                 edl->retrack();
4221                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
4222         }
4223         if( !result && asset->audio_data && asset->channels > 0 ) {
4224                 session->sample_rate = asset->get_sample_rate();
4225                 int64_t channel_mask = 0;
4226                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
4227                         file->get_audio_for_video(vstream, astream, channel_mask);
4228                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
4229                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
4230                 int channels = 0;
4231                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
4232                 if( channels < 1 ) channels = 1;
4233                 if( channels > 6 ) channels = 6;
4234                 session->audio_tracks = session->audio_channels = channels;
4235
4236                 int *achannel_positions = preferences->channel_positions[session->audio_channels-1];
4237                 memcpy(&session->achannel_positions, achannel_positions, sizeof(session->achannel_positions));
4238                 remap_audio(MWindow::AUDIO_1_TO_1);
4239
4240                 if( delete_tracks ) {
4241                         Track *track = edl->tracks->first;
4242                         for( Track *next_track=0; track; track=next_track ) {
4243                                 next_track = track->next;
4244                                 if( track->data_type != TRACK_AUDIO ) continue;
4245                                 Edit *edit = track->edits->first;
4246                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
4247                                         next_edit = edit->next;
4248                                         if( !((1<<edit->channel) & channel_mask) ||
4249                                             !edit->asset || !edit->asset->is_asset ||
4250                                             !asset->equivalent(*edit->asset,1,1,edl) )
4251                                                 delete edit;
4252                                 }
4253                                 if( !track->edits->first )
4254                                         edl->tracks->delete_track(track);
4255                         }
4256                 }
4257                 edl->rechannel();
4258                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
4259         }
4260         delete file;
4261         session->auto_keyframes = old_auto_keyframes;
4262         if( !result && delete_tracks > 0 ) {
4263                 save_backup();
4264                 undo->update_undo_after(_("select asset"), LOAD_ALL);
4265         }
4266         resync_guis();
4267         return result;
4268 }
4269
4270 int MWindow::select_asset(int vtrack, int delete_tracks)
4271 {
4272         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
4273         if( !track )
4274                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
4275         if( !track ) return 1;
4276         Edit *edit = track->edits->first;
4277         if( !edit ) return 1;
4278         Asset *asset = edit->asset;
4279         if( !asset || !asset->is_asset ) return 1;
4280         return select_asset(asset, edit->channel, 0, delete_tracks);
4281 }
4282
4283 void MWindow::dump_plugindb(FILE *fp)
4284 {
4285         if( !plugindb ) return;
4286         for(int i = 0; i < plugindb->total; i++)
4287                 plugindb->get(i)->dump(fp);
4288 }
4289
4290 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
4291 {
4292         Auto *current = 0;
4293         double unit_position = edl->local_session->get_selectionstart(1);
4294         unit_position = patch->track->to_units(unit_position, 0);
4295
4296         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
4297         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4298 }
4299
4300 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
4301 {
4302         Auto *current = 0;
4303         double unit_position = edl->local_session->get_selectionstart(1);
4304         unit_position = patch->track->to_units(unit_position, 0);
4305
4306         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
4307         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4308 }
4309
4310 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
4311 {
4312         Auto *current = 0;
4313         double unit_position = edl->local_session->get_selectionstart(1);
4314         unit_position = patch->track->to_units(unit_position, 0);
4315
4316         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
4317         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4318 }
4319
4320 PatchGUI *MWindow::get_patchgui(Track *track)
4321 {
4322         PatchGUI *patchgui = 0;
4323         TimelinePane **panes = gui->pane;
4324         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
4325                 if( !panes[i] ) continue;
4326                 PatchBay *patchbay = panes[i]->patchbay;
4327                 if( !patchbay ) continue;
4328                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
4329                         if( patchbay->patches.values[j]->track == track )
4330                                 patchgui = patchbay->patches.values[j];
4331                 }
4332         }
4333         return patchgui;
4334 }
4335