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