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