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