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