Credit Andrew - improve in-tree documentation
[goodguy/cinelerra.git] / 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                                 int groups = nested_edl->regroup(session->group_number);
2025                                 session->group_number += groups;
2026 //printf("MWindow::load_filenames %p %s\n", nested_edl, nested_edl->project_path);
2027                                 new_edl->create_nested(nested_edl);
2028                                 new_edl->set_path(filenames->get(i));
2029                                 nested_edl->Garbage::remove_user();
2030                         }
2031                         else {
2032 // Load EDL for pasting
2033                                 new_edl->load_xml(&xml_file, LOAD_ALL);
2034                                 int groups = new_edl->regroup(session->group_number);
2035                                 session->group_number += groups;
2036 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2037                                 test_plugins(new_edl, filenames->get(i));
2038 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2039
2040                                 if( load_mode == LOADMODE_REPLACE ||
2041                                     load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2042                                         strcpy(session->filename, filenames->get(i));
2043                                         strcpy(new_edl->local_session->clip_title,
2044                                                 filenames->get(i));
2045                                         if(update_filename)
2046                                                 set_filename(new_edl->local_session->clip_title);
2047                                 }
2048                                 else if( load_mode == LOADMODE_RESOURCESONLY ) {
2049                                         strcpy(new_edl->local_session->clip_title,
2050                                                 filenames->get(i));
2051                                         struct stat st;
2052                                         time_t t = !stat(filenames->get(i),&st) ?
2053                                                 st.st_mtime : time(&t);
2054                                         ctime_r(&t, new_edl->local_session->clip_notes);
2055                                 }
2056                         }
2057
2058                         new_edls.append(new_edl);
2059                         new_edl->add_user();
2060                         result = 0;
2061                         break; }
2062                 }
2063
2064                 new_edl->Garbage::remove_user();
2065                 new_asset->Garbage::remove_user();
2066
2067 // Store for testing index
2068                 new_files.append(new_file);
2069         }
2070
2071 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2072
2073
2074         if(!result) {
2075                 gui->reset_default_message();
2076                 gui->default_message();
2077         }
2078
2079
2080 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2081
2082 // Paste them.
2083 // Don't back up here.
2084         if(new_edls.size())
2085         {
2086 // For pasting, clear the active region
2087                 if(load_mode == LOADMODE_PASTE ||
2088                         load_mode == LOADMODE_NESTED)
2089                 {
2090                         double start = edl->local_session->get_selectionstart();
2091                         double end = edl->local_session->get_selectionend();
2092                         if(!EQUIV(start, end))
2093                                 edl->clear(start,
2094                                         end,
2095                                         edl->session->labels_follow_edits,
2096                                         edl->session->plugins_follow_edits,
2097                                         edl->session->autos_follow_edits);
2098                 }
2099
2100                 paste_edls(&new_edls, load_mode, 0, -1,
2101                         edl->session->labels_follow_edits,
2102                         edl->session->plugins_follow_edits,
2103                         edl->session->autos_follow_edits,
2104                         0); // overwrite
2105         }
2106
2107
2108
2109
2110 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2111
2112 // Add new assets to EDL and schedule assets for index building.
2113         int got_indexes = 0;
2114         for( int i=0; i<new_edls.size(); ++i ) {
2115                 EDL *new_edl = new_edls[i];
2116                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2117                         mainindexes->add_next_asset(0, new_edl->nested_edls[j]);
2118                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2119                         got_indexes = 1;
2120                 }
2121
2122         }
2123
2124 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2125         for( int i=0; i<new_assets.size(); ++i ) {
2126                 Asset *new_asset = new_assets[i];
2127
2128                 File *new_file = 0;
2129                 int got_it = 0;
2130                 for( int j=0; j<new_files.size(); ++j ) {
2131                         new_file = new_files[j];
2132                         if( !strcmp(new_file->asset->path, new_asset->path) ) {
2133                                 got_it = 1;
2134                                 break;
2135                         }
2136                 }
2137
2138                 mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
2139                 edl->assets->update(new_asset);
2140                 got_indexes = 1;
2141         }
2142 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2143
2144 // Start examining next batch of index files
2145         if(got_indexes) mainindexes->start_build();
2146 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2147
2148 // Open plugin GUIs
2149         Track *track = edl->tracks->first;
2150         while(track)
2151         {
2152                 for(int j = 0; j < track->plugin_set.size(); j++)
2153                 {
2154                         PluginSet *plugins = track->plugin_set[j];
2155                         Plugin *plugin = plugins->get_first_plugin();
2156
2157                         while(plugin)
2158                         {
2159                                 if(load_mode == LOADMODE_REPLACE ||
2160                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
2161                                 {
2162                                         if(plugin->plugin_type == PLUGIN_STANDALONE &&
2163                                                 plugin->show)
2164                                         {
2165                                                 show_plugin(plugin);
2166                                         }
2167                                 }
2168
2169                                 plugin = (Plugin*)plugin->next;
2170                         }
2171                 }
2172
2173                 track = track->next;
2174         }
2175
2176         // if just opening one new resource in replace mode
2177         if( ftype != FILE_IS_XML &&
2178             ( load_mode == LOADMODE_REPLACE ||
2179               load_mode == LOADMODE_REPLACE_CONCATENATE ) ) {
2180                 select_asset(0, 0);
2181                 edl->session->proxy_scale = 1;
2182                 edl->session->proxy_disabled_scale = 1;
2183                 edl->session->proxy_use_scaler = 0;
2184                 edl->session->proxy_auto_scale = 0;
2185                 edl->session->proxy_beep = 0;
2186                 edl->local_session->preview_start = 0;
2187                 edl->local_session->preview_end = -1;
2188                 edl->local_session->loop_playback = 0;
2189                 edl->local_session->set_selectionstart(0);
2190                 edl->local_session->set_selectionend(0);
2191                 set_brender_active(0, 0);
2192                 fit_selection();
2193                 goto_start();
2194         }
2195
2196         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
2197             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
2198                 ArrayList<Indexable *> orig_idxbls;
2199                 for( int i=0; i<new_assets.size(); ++i )
2200                         orig_idxbls.append(new_assets.get(i));
2201                 for( int i=0; i<new_edls.size(); ++i ) {
2202                         EDL *new_edl = new_edls[i];
2203                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2204                                 if( track->data_type != TRACK_VIDEO ) continue;
2205                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2206                                         Indexable *idxbl = (Indexable *)edit->asset;
2207                                         if( !idxbl ) continue;
2208                                         if( !idxbl->have_video() ) continue;
2209                                         if( edit->channel != 0 ) continue; // first layer only
2210                                         orig_idxbls.append(edit->asset);
2211                                 }
2212                         }
2213                 }
2214                 gui->unlock_window(); // to update progress bar
2215                 int ret = render_proxy(orig_idxbls);
2216                 gui->lock_window("MWindow::load_filenames");
2217                 if( ret >= 0 && edl->session->proxy_beep ) {
2218                         if( ret > 0 )
2219                                 beep(2000., 1.5, 0.5);
2220                         else
2221                                 beep(4000., 0.25, 0.5);
2222                 }
2223         }
2224
2225 // need to update undo before project, since mwindow is unlocked & a new load
2226 // can begin here.  Should really prevent loading until we're done.
2227 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2228         undo->update_undo_after(_("load"), LOAD_ALL);
2229
2230         for(int i = 0; i < new_edls.size(); i++)
2231         {
2232                 new_edls[i]->remove_user();
2233         }
2234 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2235
2236         new_edls.remove_all();
2237
2238         for(int i = 0; i < new_assets.size(); i++)
2239         {
2240                 new_assets[i]->Garbage::remove_user();
2241         }
2242
2243         new_assets.remove_all();
2244         new_files.remove_all_objects();
2245
2246
2247 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2248         if(load_mode == LOADMODE_REPLACE ||
2249                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2250         {
2251                 session->changes_made = 0;
2252         }
2253         else
2254         {
2255                 session->changes_made = 1;
2256         }
2257
2258         gui->stop_hourglass();
2259
2260
2261 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2262         update_project(load_mode);
2263
2264 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2265
2266         return 0;
2267 }
2268
2269 int MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2270 {
2271         Asset *format_asset = new Asset;
2272         format_asset->format = FILE_FFMPEG;
2273         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2274         ProxyRender proxy_render(this, format_asset);
2275         int new_scale = edl->session->proxy_scale;
2276         int use_scaler = edl->session->proxy_use_scaler;
2277
2278         for( int i=0; i<new_idxbls.size(); ++i ) {
2279                 Indexable *orig = new_idxbls.get(i);
2280                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2281                 if( !proxy ) continue;
2282                 FileSystem fs;
2283                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2284                 int got_it = exists && // if proxy exists, and is newer than orig
2285                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2286                 if( got_it ) continue;
2287                 proxy_render.add_needed(orig, proxy);
2288         }
2289
2290 // render needed proxies
2291         int result = proxy_render.create_needed_proxies(new_scale);
2292         if( !result ) {
2293                 add_proxy(use_scaler,
2294                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2295         }
2296         format_asset->remove_user();
2297         return !result ? proxy_render.needed_proxies.size() : -1;
2298 }
2299
2300 int MWindow::enable_proxy()
2301 {
2302         int ret = 0;
2303         if( edl->session->proxy_scale == 1 &&
2304             edl->session->proxy_disabled_scale != 1 ) {
2305                 int new_scale = edl->session->proxy_disabled_scale;
2306                 int new_use_scaler = edl->session->proxy_use_scaler;
2307                 edl->session->proxy_disabled_scale = 1;
2308                 Asset *asset = new Asset;
2309                 asset->format = FILE_FFMPEG;
2310                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2311                 ret = to_proxy(asset, new_scale, new_use_scaler);
2312                 asset->remove_user();
2313                 if( ret > 0 )
2314                         beep(2000., 1.5, 0.5);
2315         }
2316         return 1;
2317 }
2318
2319 int MWindow::disable_proxy()
2320 {
2321         if( edl->session->proxy_scale != 1 &&
2322             edl->session->proxy_disabled_scale == 1 ) {
2323                 int new_scale = 1;
2324                 int new_use_scaler = edl->session->proxy_use_scaler;
2325                 edl->session->proxy_disabled_scale = edl->session->proxy_scale;
2326                 Asset *asset = new Asset;
2327                 asset->format = FILE_FFMPEG;
2328                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2329                 to_proxy(asset, new_scale, new_use_scaler);
2330                 asset->remove_user();
2331         }
2332         return 1;
2333 }
2334
2335 int MWindow::to_proxy(Asset *asset, int new_scale, int new_use_scaler)
2336 {
2337         ArrayList<Indexable*> orig_idxbls;
2338         ArrayList<Indexable*> proxy_assets;
2339
2340         edl->Garbage::add_user();
2341         save_backup();
2342         undo->update_undo_before(_("proxy"), this);
2343         ProxyRender proxy_render(this, asset);
2344
2345 // revert project to original size from current size
2346 // remove all session proxy assets at the at the current proxy_scale
2347         int proxy_scale = edl->session->proxy_scale;
2348
2349         if( proxy_scale > 1 ) {
2350                 Asset *orig_asset = edl->assets->first;
2351                 for( ; orig_asset; orig_asset=orig_asset->next ) {
2352                         char new_path[BCTEXTLEN];
2353                         proxy_render.to_proxy_path(new_path, orig_asset, proxy_scale);
2354 // test if proxy asset was already added to proxy_assets
2355                         int got_it = 0;
2356                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2357                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2358                         if( got_it ) continue;
2359                         Asset *proxy_asset = edl->assets->get_asset(new_path);
2360                         if( !proxy_asset ) continue;
2361 // add pointer to existing EDL asset if it exists
2362 // EDL won't delete it unless it's the same pointer.
2363                         proxy_assets.append(proxy_asset);
2364                         proxy_asset->add_user();
2365                         orig_idxbls.append(orig_asset);
2366                         orig_asset->add_user();
2367                 }
2368                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2369                         EDL *orig_nested = edl->nested_edls[i];
2370                         char new_path[BCTEXTLEN];
2371                         if( !ProxyRender::from_proxy_path(new_path, orig_nested, proxy_scale) )
2372                                 continue;
2373                         proxy_render.to_proxy_path(new_path, orig_nested, proxy_scale);
2374 // test if proxy asset was already added to proxy_assets
2375                         int got_it = 0;
2376                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2377                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2378                         if( got_it ) continue;
2379                         Asset *proxy_nested = edl->assets->get_asset(new_path);
2380                         if( !proxy_nested ) continue;
2381 // add pointer to existing EDL asset if it exists
2382 // EDL won't delete it unless it's the same pointer.
2383                         proxy_assets.append(proxy_nested);
2384                         proxy_nested->add_user();
2385                         orig_idxbls.append(orig_nested);
2386                         orig_nested->add_user();
2387                 }
2388
2389 // convert from the proxy assets to the original assets
2390                 edl->set_proxy(1, 0, &proxy_assets, &orig_idxbls);
2391
2392 // remove the references
2393                 for( int i=0; i<proxy_assets.size(); ++i ) {
2394                         Asset *proxy = (Asset *) proxy_assets[i];
2395                         proxy->width = proxy->actual_width;
2396                         proxy->height = proxy->actual_height;
2397                         proxy->remove_user();
2398                         edl->assets->remove_pointer(proxy);
2399                         proxy->remove_user();
2400                 }
2401                 proxy_assets.remove_all();
2402                 for( int i = 0; i < orig_idxbls.size(); i++ )
2403                         orig_idxbls[i]->remove_user();
2404                 orig_idxbls.remove_all();
2405         }
2406
2407         ArrayList<char *> confirm_paths;    // test for new files
2408         confirm_paths.set_array_delete();
2409
2410 // convert to new size if not original size
2411         if( new_scale != 1 ) {
2412                 FileSystem fs;
2413                 Asset *orig = edl->assets->first;
2414                 for( ; orig; orig=orig->next ) {
2415                         Asset *proxy = proxy_render.add_original(orig, new_scale);
2416                         if( !proxy ) continue;
2417                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2418                         int got_it = exists && // if proxy exists, and is newer than orig
2419                             fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2420                         if( !got_it ) {
2421                                 if( exists ) // prompt user to overwrite
2422                                         confirm_paths.append(cstrdup(proxy->path));
2423                                 proxy_render.add_needed(orig, proxy);
2424                         }
2425                 }
2426                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2427                         EDL *orig_nested = edl->nested_edls[i];
2428                         Asset *proxy = proxy_render.add_original(orig_nested, new_scale);
2429                         if( !proxy ) continue;
2430                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2431                         int got_it = exists && // if proxy exists, and is newer than orig_nested
2432                             fs.get_date(proxy->path) > fs.get_date(orig_nested->path) ? 1 : 0;
2433                         if( !got_it ) {
2434                                 if( exists ) // prompt user to overwrite
2435                                         confirm_paths.append(cstrdup(proxy->path));
2436                                 proxy_render.add_needed(orig_nested, proxy);
2437                         }
2438                 }
2439         }
2440
2441         int result = 0;
2442 // test for existing files
2443         if( confirm_paths.size() ) {
2444                 result = ConfirmSave::test_files(this, &confirm_paths);
2445                 confirm_paths.remove_all_objects();
2446         }
2447
2448         if( !result )
2449                 result = proxy_render.create_needed_proxies(new_scale);
2450
2451         if( !result ) // resize project
2452                 edl->set_proxy(new_scale, new_use_scaler,
2453                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2454
2455         undo->update_undo_after(_("proxy"), LOAD_ALL);
2456         edl->Garbage::remove_user();
2457         restart_brender();
2458
2459         gui->lock_window("MWindow::to_proxy");
2460         update_project(LOADMODE_REPLACE);
2461         gui->unlock_window();
2462
2463         return !result ? proxy_render.needed_proxies.size() : -1;
2464 }
2465
2466 void MWindow::test_plugins(EDL *new_edl, char *path)
2467 {
2468         char string[BCTEXTLEN];
2469
2470 // Do a check whether plugins exist
2471         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2472                 for( int k=0; k<track->plugin_set.total; ++k ) {
2473                         PluginSet *plugin_set = track->plugin_set[k];
2474                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2475                                         plugin; plugin = (Plugin*)plugin->next ) {
2476                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2477 // ok we need to find it in plugindb
2478                                 PluginServer *server =
2479                                         scan_plugindb(plugin->title, track->data_type);
2480                                 if( !server || server->transition ) {
2481                                         sprintf(string,
2482         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2483           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2484                                                 "effect", _(plugin->title), path);
2485                                         MainError::show_error(string);
2486                                 }
2487                         }
2488                 }
2489
2490                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2491                         if( !edit->transition ) continue;
2492 // ok we need to find transition in plugindb
2493                         PluginServer *server =
2494                                 scan_plugindb(edit->transition->title, track->data_type);
2495                         if( !server || !server->transition ) {
2496                                 sprintf(string,
2497         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2498           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2499                                         "transition", _(edit->transition->title), path);
2500                                 MainError::show_error(string);
2501                         }
2502                 }
2503         }
2504 }
2505
2506
2507 void MWindow::init_shm(const char *pfn, int64_t min)
2508 {
2509         int64_t result = 0;
2510 // Fix shared memory
2511         FILE *fd = fopen(pfn, "r");
2512         if( fd ) {
2513                 fscanf(fd, "%jd", &result);
2514                 fclose(fd);
2515                 if( result >= min ) return;
2516         }
2517
2518         fd = fopen(pfn, "w");
2519         if( !fd ) return;
2520         fprintf(fd, "0x%jx", min);
2521         fclose(fd);
2522
2523         fd = fopen(pfn, "r");
2524         if( !fd ) {
2525                 eprintf(_("MWindow::init_shm: couldn't open %s for reading.\n"), pfn);
2526                 return;
2527         }
2528
2529         fscanf(fd, "%jd", &result);
2530         fclose(fd);
2531         if( result < min ) {
2532                 eprintf(_("MWindow::init_shm: %s is %p.\n"
2533                         "you probably need to be root, or:\n"
2534                         "as root, run: echo 0x%jx > %s\n"
2535                         "before trying to start cinelerra.\n"
2536                         "It should be at least 0x%jx for Cinelerra.\n"),
2537                         pfn, (void *)result, min, pfn, min);
2538         }
2539 }
2540
2541 void MWindow::create_objects(int want_gui,
2542         int want_new,
2543         char *config_path)
2544 {
2545         const int debug = 0;
2546         if(debug) PRINT_TRACE
2547
2548 // For some reason, init_signals must come after show_splash or the signals won't
2549 // get trapped.
2550         init_signals();
2551         if(debug) PRINT_TRACE
2552         init_3d();
2553
2554         if(debug) PRINT_TRACE
2555         show_splash();
2556
2557         if(debug) PRINT_TRACE
2558         default_standard = default_std();
2559         init_defaults(defaults, config_path);
2560         check_language();
2561         init_preferences();
2562         if(splash_window)
2563                 splash_window->update_status(_("Initializing Plugins"));
2564         init_plugins(this, preferences);
2565         if(debug) PRINT_TRACE
2566         init_ladspa_plugins(this, preferences);
2567         if(debug) PRINT_TRACE
2568         init_plugin_tips(*plugindb, cin_lang);
2569         if(splash_window)
2570                 splash_window->update_status(_("Initializing GUI"));
2571         if(debug) PRINT_TRACE
2572         init_theme();
2573
2574         if(debug) PRINT_TRACE
2575         init_error();
2576
2577         if(splash_window)
2578                 splash_window->update_status(_("Initializing Fonts"));
2579         char string[BCTEXTLEN];
2580         strcpy(string, preferences->plugin_dir);
2581         strcat(string, "/" FONT_SEARCHPATH);
2582         BC_Resources::init_fontconfig(string);
2583         if(debug) PRINT_TRACE
2584
2585 // Default project created here
2586         init_edl();
2587         if(debug) PRINT_TRACE
2588
2589         init_cache();
2590         if(debug) PRINT_TRACE
2591
2592         Timer timer;
2593
2594         init_awindow();
2595         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2596
2597         init_compositor();
2598         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2599
2600 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2601         if(session->show_vwindow)
2602                 get_viewer(1, DEFAULT_VWINDOW);
2603         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2604
2605         init_gui();
2606         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2607
2608         init_levelwindow();
2609         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2610
2611         init_indexes();
2612         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2613
2614         init_channeldb();
2615         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2616
2617         init_gwindow();
2618         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2619
2620         init_render();
2621         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2622
2623         init_brender();
2624         init_exportedl();
2625         init_commercials();
2626         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2627         mainprogress = new MainProgress(this, gui);
2628         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2629         undo = new MainUndo(this);
2630
2631         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2632
2633         plugin_guis = new ArrayList<PluginServer*>;
2634         dead_plugins = new ArrayList<PluginServer*>;
2635         keyframe_threads = new ArrayList<KeyFrameThread*>;
2636
2637         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2638                 __LINE__,
2639                 vwindows.size(),
2640                 session->show_vwindow);
2641
2642 // Show all vwindows
2643 //      if(session->show_vwindow) {
2644 //              for(int j = 0; j < vwindows.size(); j++) {
2645 //                      VWindow *vwindow = vwindows[j];
2646 //                      if( !vwindow->is_running() ) continue;
2647 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2648 //                              __LINE__,
2649 //                              vwindow);
2650 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2651 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2652 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2653 //                      vwindow->gui->show_window();
2654 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2655 //                      vwindow->gui->unlock_window();
2656 //              }
2657 //      }
2658
2659
2660         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2661
2662         if(session->show_cwindow)
2663         {
2664                 cwindow->gui->lock_window("MWindow::create_objects 1");
2665                 cwindow->gui->show_window();
2666                 cwindow->gui->unlock_window();
2667         }
2668
2669         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2670         if(session->show_awindow)
2671         {
2672                 awindow->gui->lock_window("MWindow::create_objects 1");
2673                 awindow->gui->show_window();
2674                 awindow->gui->unlock_window();
2675         }
2676
2677         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2678         if(session->show_lwindow)
2679         {
2680                 lwindow->gui->lock_window("MWindow::create_objects 1");
2681                 lwindow->gui->show_window();
2682                 lwindow->gui->unlock_window();
2683         }
2684
2685         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2686                 __LINE__,
2687                 (int)timer.get_difference(),
2688                 gwindow->gui);
2689         if(session->show_gwindow)
2690         {
2691                 gwindow->gui->lock_window("MWindow::create_objects 1");
2692                 gwindow->gui->show_window();
2693                 gwindow->gui->unlock_window();
2694         }
2695
2696         if(debug) PRINT_TRACE
2697
2698         gui->lock_window("MWindow::create_objects 1");
2699         gui->mainmenu->load_defaults(defaults);
2700         gui->mainmenu->update_toggles(0);
2701         gui->update_patchbay();
2702         gui->draw_canvas(0, 0);
2703         gui->draw_cursor(1);
2704         gui->show_window();
2705         gui->raise_window();
2706         gui->unlock_window();
2707
2708         if(debug) PRINT_TRACE
2709
2710         if(preferences->use_tipwindow)
2711                 init_tipwindow();
2712         if(debug) PRINT_TRACE
2713
2714         gui->add_keyboard_listener(
2715                 (int (BC_WindowBase::*)(BC_WindowBase *))
2716                 &MWindowGUI::keyboard_listener);
2717
2718         hide_splash();
2719         init_shm("/proc/sys/kernel/shmmax", 0x7fffffff);
2720         init_shm("/proc/sys/kernel/shmmni", 0x4000);
2721         if(debug) PRINT_TRACE
2722
2723         BC_WindowBase::get_resources()->vframe_shm = 1;
2724 }
2725
2726
2727 void MWindow::show_splash()
2728 {
2729 #include "data/heroine_logo9_png.h"
2730         VFrame *frame = new VFramePng(heroine_logo9_png);
2731         BC_DisplayInfo dpyi;
2732         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2733         int rr = (rw < rh ? rw : rh) / 4;
2734         splash_window = new SplashGUI(frame, rr, rr);
2735         splash_window->create_objects();
2736 }
2737
2738 void MWindow::hide_splash()
2739 {
2740         if(splash_window)
2741                 delete splash_window;
2742         splash_window = 0;
2743 }
2744
2745
2746 void MWindow::start()
2747 {
2748 ENABLE_BUFFER
2749 //PRINT_TRACE
2750 //      vwindows[DEFAULT_VWINDOW]->start();
2751         awindow->start();
2752 //PRINT_TRACE
2753         cwindow->start();
2754 //PRINT_TRACE
2755         lwindow->start();
2756 //PRINT_TRACE
2757         gwindow->start();
2758 //PRINT_TRACE
2759 //      Thread::start();
2760 //PRINT_TRACE
2761         playback_3d->start();
2762 //PRINT_TRACE
2763 }
2764
2765 void MWindow::run()
2766 {
2767         run_lock->lock("MWindow::run");
2768         gui->run_window();
2769         stop_playback(1);
2770
2771         brender_lock->lock("MWindow::run 1");
2772         delete brender;         brender = 0;
2773         brender_lock->unlock();
2774
2775         interrupt_indexes();
2776         clean_indexes();
2777         save_defaults();
2778         run_lock->unlock();
2779 }
2780
2781 void MWindow::show_vwindow()
2782 {
2783         int total_running = 0;
2784         session->show_vwindow = 1;
2785
2786 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2787 // Raise all windows which are visible
2788         for(int j = 0; j < vwindows.size(); j++) {
2789                 VWindow *vwindow = vwindows[j];
2790                 if( !vwindow->is_running() ) continue;
2791                 vwindow->gui->lock_window("MWindow::show_vwindow");
2792                 vwindow->gui->show_window(0);
2793                 vwindow->gui->raise_window();
2794                 vwindow->gui->flush();
2795                 vwindow->gui->unlock_window();
2796                 total_running++;
2797         }
2798
2799 // If no windows visible
2800         if(!total_running)
2801         {
2802                 get_viewer(1, DEFAULT_VWINDOW);
2803         }
2804
2805         gui->mainmenu->show_vwindow->set_checked(1);
2806 }
2807
2808 void MWindow::show_awindow()
2809 {
2810         session->show_awindow = 1;
2811         awindow->gui->lock_window("MWindow::show_awindow");
2812         awindow->gui->show_window();
2813         awindow->gui->raise_window();
2814         awindow->gui->flush();
2815         awindow->gui->unlock_window();
2816         gui->mainmenu->show_awindow->set_checked(1);
2817 }
2818
2819 char *MWindow::get_cwindow_display()
2820 {
2821         char *x11_host = screens < 2 || session->window_config == 0 ?
2822                 session->a_x11_host : session->b_x11_host;
2823         return *x11_host ? x11_host : 0;
2824 }
2825
2826 void MWindow::show_cwindow()
2827 {
2828         session->show_cwindow = 1;
2829         cwindow->show_window();
2830         gui->mainmenu->show_cwindow->set_checked(1);
2831 }
2832
2833 void MWindow::show_gwindow()
2834 {
2835         session->show_gwindow = 1;
2836
2837         gwindow->gui->lock_window("MWindow::show_gwindow");
2838         gwindow->gui->show_window();
2839         gwindow->gui->raise_window();
2840         gwindow->gui->flush();
2841         gwindow->gui->unlock_window();
2842
2843         gui->mainmenu->show_gwindow->set_checked(1);
2844 }
2845 void MWindow::hide_gwindow()
2846 {
2847         session->show_gwindow = 0;
2848
2849         gwindow->gui->lock_window("MWindow::show_gwindow");
2850         gwindow->gui->hide_window();
2851         gwindow->gui->unlock_window();
2852 }
2853
2854 void MWindow::show_lwindow()
2855 {
2856         session->show_lwindow = 1;
2857         lwindow->gui->lock_window("MWindow::show_lwindow");
2858         lwindow->gui->show_window();
2859         lwindow->gui->raise_window();
2860         lwindow->gui->flush();
2861         lwindow->gui->unlock_window();
2862         gui->mainmenu->show_lwindow->set_checked(1);
2863 }
2864
2865 void MWindow::restore_windows()
2866 {
2867         if( !session->show_vwindow ) {
2868                 for( int i=0, n=vwindows.size(); i<n; ++i ) {
2869                         VWindow *vwindow = vwindows[i];
2870                         if( !vwindow || !vwindow->is_running() ) continue;
2871                         vwindow->gui->lock_window("MWindow::restore_windows");
2872                         vwindow->gui->close(1);
2873                         vwindow->gui->unlock_window();
2874                 }
2875         }
2876         else
2877                 show_vwindow();
2878
2879         if( !session->show_awindow && !awindow->gui->is_hidden() ) {
2880                 awindow->gui->lock_window("MWindow::restore_windows");
2881                 awindow->gui->close_event();
2882                 awindow->gui->unlock_window();
2883         }
2884         else if( session->show_awindow && awindow->gui->is_hidden() )
2885                 show_awindow();
2886
2887         if( !session->show_cwindow && !cwindow->gui->is_hidden() ) {
2888                 cwindow->gui->lock_window("MWindow::restore_windows");
2889                 cwindow->hide_window();
2890                 cwindow->gui->unlock_window();
2891         }
2892         else if( session->show_cwindow && cwindow->gui->is_hidden() )
2893                 cwindow->show_window();
2894
2895         if( !session->show_gwindow && !gwindow->gui->is_hidden() ) {
2896                 gwindow->gui->lock_window("MWindow::restore_windows");
2897                 gwindow->gui->close_event();
2898                 gwindow->gui->unlock_window();
2899         }
2900         else if( session->show_gwindow && gwindow->gui->is_hidden() )
2901                 show_gwindow();
2902
2903         if( !session->show_lwindow && !lwindow->gui->is_hidden() ) {
2904                 lwindow->gui->lock_window("MWindow::restore_windows");
2905                 lwindow->gui->close_event();
2906                 lwindow->gui->unlock_window();
2907         }
2908         else if( session->show_lwindow && lwindow->gui->is_hidden() )
2909                 show_lwindow();
2910
2911         gui->focus();
2912 }
2913
2914 void MWindow::save_layout(int no)
2915 {
2916         char layout_path[BCTEXTLEN];
2917         snprintf(layout_path, sizeof(layout_path), "%s/" LAYOUT_FILE,
2918                 File::get_config_path(), no);
2919         session->save_file(layout_path);
2920 }
2921
2922 void MWindow::load_layout(int no)
2923 {
2924         char layout_path[BCTEXTLEN];
2925         snprintf(layout_path, sizeof(layout_path), "%s/" LAYOUT_FILE,
2926                 File::get_config_path(), no);
2927         session->load_file(layout_path);
2928         restore_windows();
2929         gui->default_positions();
2930         save_defaults();
2931 }
2932
2933 int MWindow::tile_windows(int window_config)
2934 {
2935         int need_reload = 0;
2936         int play_config = window_config==0 ? 0 : 1;
2937         edl->session->playback_config->load_defaults(defaults, play_config);
2938         session->default_window_positions(window_config);
2939         if( screens == 1 ) {
2940                 gui->default_positions();
2941                 sync_parameters(CHANGE_ALL);
2942         }
2943         else
2944                 need_reload = 1;
2945         return need_reload;
2946 }
2947
2948 void MWindow::toggle_loop_playback()
2949 {
2950         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2951         set_loop_boundaries();
2952         save_backup();
2953
2954         gui->draw_overlays(1);
2955         sync_parameters(CHANGE_PARAMS);
2956 }
2957
2958 void MWindow::set_screens(int value)
2959 {
2960         screens = value;
2961 }
2962
2963 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2964 {
2965         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2966         edl->session->auto_keyframes = value;
2967         gui->mbuttons->edit_panel->keyframe->update(value);
2968         gui->flush();
2969         if(lock_mwindow) gui->unlock_window();
2970
2971         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2972         cwindow->gui->edit_panel->keyframe->update(value);
2973         cwindow->gui->flush();
2974         if(lock_cwindow) cwindow->gui->unlock_window();
2975 }
2976
2977 void MWindow::set_auto_visibility(Autos *autos, int value)
2978 {
2979         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2980                 edl->session->auto_conf->plugins = value;
2981         else if( autos->autoidx >= 0 )
2982                 edl->session->auto_conf->autos[autos->autoidx] = value;
2983         else
2984                 return;
2985
2986         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
2987         gui->mainmenu->update_toggles(1);
2988         gui->unlock_window();
2989         gwindow->gui->update_toggles(1);
2990         gui->lock_window("MWindow::set_auto_visibility");
2991 }
2992
2993 void MWindow::set_keyframe_type(int mode)
2994 {
2995         gui->lock_window("MWindow::set_keyframe_type");
2996         edl->local_session->floatauto_type = mode;
2997         gui->mainmenu->update_toggles(0);
2998         gui->unlock_window();
2999 }
3000
3001 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
3002 {
3003         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
3004         edl->session->editing_mode = new_editing_mode;
3005         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
3006         gui->mbuttons->edit_panel->update();
3007         gui->set_editing_mode(1);
3008         if(lock_mwindow) gui->unlock_window();
3009
3010
3011         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
3012         cwindow->gui->edit_panel->update();
3013         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
3014         if(lock_cwindow) cwindow->gui->unlock_window();
3015         return 0;
3016 }
3017
3018 void MWindow::toggle_editing_mode()
3019 {
3020         int mode = edl->session->editing_mode;
3021         if( mode == EDITING_ARROW )
3022                 set_editing_mode(EDITING_IBEAM, 0, 1);
3023         else
3024                 set_editing_mode(EDITING_ARROW, 0, 1);
3025 }
3026
3027 void MWindow::toggle_camera_xyz()
3028 {
3029         gwindow->gui->lock_window("MWindow::toggle_camera_xyz");
3030         gwindow->gui->toggle_camera_xyz();
3031         gwindow->gui->unlock_window();
3032 }
3033
3034 void MWindow::toggle_projector_xyz()
3035 {
3036         gwindow->gui->lock_window("MWindow::toggle_projector_xyz");
3037         gwindow->gui->toggle_projector_xyz();
3038         gwindow->gui->unlock_window();
3039 }
3040
3041 void MWindow::set_labels_follow_edits(int value)
3042 {
3043         gui->lock_window("MWindow::set_labels_follow_edits");
3044         edl->session->labels_follow_edits = value;
3045         gui->mbuttons->edit_panel->locklabels->update(value);
3046         gui->mainmenu->labels_follow_edits->set_checked(value);
3047         gui->flush();
3048         gui->unlock_window();
3049 }
3050
3051 void MWindow::sync_parameters(int change_type)
3052 {
3053         if( in_destructor ) return;
3054
3055 // Sync engines which are playing back
3056         if(cwindow->playback_engine->is_playing_back)
3057         {
3058                 if(change_type == CHANGE_PARAMS)
3059                 {
3060 // TODO: block keyframes until synchronization is done
3061                         cwindow->playback_engine->sync_parameters(edl);
3062                 }
3063                 else
3064 // Stop and restart
3065                 {
3066                         int command = cwindow->playback_engine->command->command;
3067                         cwindow->playback_engine->que->send_command(STOP,
3068                                 CHANGE_NONE,
3069                                 0,
3070                                 0);
3071 // Waiting for tracking to finish would make the restart position more
3072 // accurate but it can't lock the window to stop tracking for some reason.
3073 // Not waiting for tracking gives a faster response but restart position is
3074 // only as accurate as the last tracking update.
3075                         cwindow->playback_engine->interrupt_playback(0);
3076                         cwindow->playback_engine->que->send_command(command,
3077                                         change_type,
3078                                         edl,
3079                                         1,
3080                                         0);
3081                 }
3082         }
3083         else
3084         {
3085                 cwindow->refresh_frame(change_type);
3086         }
3087 }
3088
3089 void MWindow::age_caches()
3090 {
3091 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
3092 // __LINE__,
3093 // preferences->cache_size,
3094 // audio_cache->get_memory_usage(1),
3095 // video_cache->get_memory_usage(1),
3096 // frame_cache->get_memory_usage(),
3097 // wave_cache->get_memory_usage(),
3098 // memory_usage);
3099         frame_cache->age_cache(512);
3100         wave_cache->age_cache(8192);
3101
3102         int64_t memory_usage;
3103         int64_t prev_memory_usage = 0;
3104         int result = 0;
3105         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
3106         while( !result && prev_memory_usage !=
3107                 (memory_usage=video_cache->get_memory_usage(1)) &&
3108                 memory_usage > video_size ) {
3109                 video_cache->delete_oldest();
3110                 prev_memory_usage = memory_usage;
3111         }
3112
3113         prev_memory_usage = 0;
3114         result = 0;
3115         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
3116         while( !result && prev_memory_usage !=
3117                 (memory_usage=audio_cache->get_memory_usage(1)) &&
3118                 memory_usage > audio_size ) {
3119                 audio_cache->delete_oldest();
3120                 prev_memory_usage = memory_usage;
3121         }
3122 }
3123
3124 void MWindow::reset_android_remote()
3125 {
3126         gui->use_android_remote(preferences->android_remote);
3127 }
3128
3129
3130 void MWindow::show_keyframe_gui(Plugin *plugin)
3131 {
3132         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
3133 // Find existing thread
3134         for(int i = 0; i < keyframe_threads->size(); i++)
3135         {
3136                 if(keyframe_threads->get(i)->plugin == plugin)
3137                 {
3138                         keyframe_threads->get(i)->start_window(plugin, 0);
3139                         keyframe_gui_lock->unlock();
3140                         return;
3141                 }
3142         }
3143
3144 // Find unused thread
3145         for(int i = 0; i < keyframe_threads->size(); i++)
3146         {
3147                 if(!keyframe_threads->get(i)->plugin)
3148                 {
3149                         keyframe_threads->get(i)->start_window(plugin, 0);
3150                         keyframe_gui_lock->unlock();
3151                         return;
3152                 }
3153         }
3154
3155 // Create new thread
3156         KeyFrameThread *thread = new KeyFrameThread(this);
3157         keyframe_threads->append(thread);
3158         thread->start_window(plugin, 0);
3159
3160         keyframe_gui_lock->unlock();
3161 }
3162
3163
3164
3165
3166
3167 void MWindow::show_plugin(Plugin *plugin)
3168 {
3169         int done = 0;
3170
3171 SET_TRACE
3172 // Remove previously deleted plugin GUIs
3173         dead_plugin_lock->lock("MWindow::show_plugin");
3174         dead_plugins->remove_all_objects();
3175         dead_plugin_lock->unlock();
3176
3177 //printf("MWindow::show_plugin %d\n", __LINE__);
3178 SET_TRACE
3179
3180
3181         plugin_gui_lock->lock("MWindow::show_plugin");
3182         for(int i = 0; i < plugin_guis->total; i++)
3183         {
3184 // Pointer comparison
3185                 if(plugin_guis->get(i)->plugin == plugin)
3186                 {
3187                         plugin_guis->get(i)->raise_window();
3188                         done = 1;
3189                         break;
3190                 }
3191         }
3192 SET_TRACE
3193
3194 //printf("MWindow::show_plugin 1\n");
3195         if( !done && !plugin->track ) {
3196                 printf("MWindow::show_plugin track not defined.\n");
3197                 done = 1;
3198         }
3199         if( !done ) {
3200                 PluginServer *server = scan_plugindb(plugin->title,
3201                         plugin->track->data_type);
3202
3203 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
3204                 if(server && server->uses_gui)
3205                 {
3206                         PluginServer *gui = new PluginServer(*server);
3207                         plugin_guis->append(gui);
3208 // Needs mwindow to do GUI
3209                         gui->set_mwindow(this);
3210                         gui->open_plugin(0, preferences, edl, plugin);
3211                         plugin->show = 1;
3212                         gui->show_gui();
3213                 }
3214         }
3215         plugin_gui_lock->unlock();
3216 //printf("MWindow::show_plugin %d\n", __LINE__);
3217 SET_TRACE
3218 //sleep(1);
3219 //printf("MWindow::show_plugin 2\n");
3220 }
3221
3222 void MWindow::hide_plugin(Plugin *plugin, int lock)
3223 {
3224         plugin->show = 0;
3225 // Update the toggle
3226         gui->lock_window("MWindow::hide_plugin");
3227         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3228         gui->unlock_window();
3229
3230         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
3231         for(int i = 0; i < plugin_guis->total; i++)
3232         {
3233                 if(plugin_guis->get(i)->plugin == plugin)
3234                 {
3235                         PluginServer *ptr = plugin_guis->get(i);
3236                         plugin_guis->remove(ptr);
3237                         if(lock) plugin_gui_lock->unlock();
3238 // Last command executed in client side close
3239 // Schedule for deletion
3240                         ptr->hide_gui();
3241                         delete_plugin(ptr);
3242 //sleep(1);
3243                         return;
3244                 }
3245         }
3246         if(lock) plugin_gui_lock->unlock();
3247 }
3248
3249 void MWindow::delete_plugin(PluginServer *plugin)
3250 {
3251         dead_plugin_lock->lock("MWindow::delete_plugin");
3252         dead_plugins->append(plugin);
3253         dead_plugin_lock->unlock();
3254 }
3255
3256 void MWindow::hide_plugins()
3257 {
3258         plugin_gui_lock->lock("MWindow::hide_plugins 1");
3259         while(plugin_guis->size())
3260         {
3261                 PluginServer *ptr = plugin_guis->get(0);
3262                 plugin_guis->remove(ptr);
3263                 plugin_gui_lock->unlock();
3264 // Last command executed in client side close
3265 // Schedule for deletion
3266                 ptr->hide_gui();
3267                 delete_plugin(ptr);
3268                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
3269         }
3270         plugin_gui_lock->unlock();
3271
3272         hide_keyframe_guis();
3273 }
3274
3275 void MWindow::hide_keyframe_guis()
3276 {
3277         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
3278         for(int i = 0; i < keyframe_threads->size(); i++)
3279         {
3280                 keyframe_threads->get(i)->close_window();
3281         }
3282         keyframe_gui_lock->unlock();
3283 }
3284
3285 void MWindow::hide_keyframe_gui(Plugin *plugin)
3286 {
3287         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
3288         for(int i = 0; i < keyframe_threads->size(); i++)
3289         {
3290                 if(keyframe_threads->get(i)->plugin == plugin)
3291                 {
3292                         keyframe_threads->get(i)->close_window();
3293                         break;
3294                 }
3295         }
3296         keyframe_gui_lock->unlock();
3297 }
3298
3299 int MWindow::get_hash_color(Edit *edit)
3300 {
3301         Indexable *idxbl = edit->asset ?
3302                 (Indexable*)edit->asset : (Indexable*)edit->nested_edl;
3303         if( !idxbl ) return 0;
3304         char path[BCTEXTLEN];
3305         if( !edit->asset || edit->track->data_type != TRACK_VIDEO ||
3306             edl->session->proxy_scale == 1 ||
3307             ProxyRender::from_proxy_path(path, idxbl, edl->session->proxy_scale) )
3308                 strcpy(path, idxbl->path);
3309         char *cp = strrchr(path, '/');
3310         cp = !cp ? path : cp+1;
3311         uint8_t *bp = (uint8_t*)cp;
3312         int v = 0;
3313         while( *bp ) v += *bp++;
3314         return get_hash_color(v);
3315 }
3316
3317 int MWindow::get_hash_color(int v)
3318 {
3319         int hash = 0x303030;
3320         if( v & 0x01 ) hash ^= 0x000040;
3321         if( v & 0x02 ) hash ^= 0x004000;
3322         if( v & 0x04 ) hash ^= 0x400000;
3323         if( v & 0x08 ) hash ^= 0x080000;
3324         if( v & 0x10 ) hash ^= 0x000800;
3325         if( v & 0x20 ) hash ^= 0x000008;
3326         if( v & 0x40 ) hash ^= 0x404040;
3327         if( v & 0x80 ) hash ^= 0x080808;
3328         return hash;
3329 }
3330
3331 int MWindow::get_group_color(int v)
3332 {
3333         int color = 0x606060;
3334         if( v & 0x01 ) color ^= 0x000080;
3335         if( v & 0x02 ) color ^= 0x008000;
3336         if( v & 0x04 ) color ^= 0x800000;
3337         if( v & 0x08 ) color ^= 0x100000;
3338         if( v & 0x10 ) color ^= 0x001000;
3339         if( v & 0x20 ) color ^= 0x000010;
3340         if( v & 0x40 ) color ^= 0x080808;
3341         if( v & 0x80 ) color ^= 0x909090;
3342         return color;
3343 }
3344
3345 int MWindow::get_title_color(Edit *edit)
3346 {
3347         unsigned color = edit->color & 0xffffff;
3348         unsigned alpha = (~edit->color>>24) & 0xff;
3349         if( !color ) {
3350                 if( edit->group_id )
3351                         color = get_group_color(edit->group_id);
3352                 else if( preferences->autocolor_assets )
3353                         color = get_hash_color(edit);
3354                 else
3355                         return 0;
3356         }
3357         if( alpha == 0xff )
3358                 alpha = session->title_bar_alpha*255;
3359         return color | (~alpha<<24);
3360 }
3361
3362 void MWindow::update_keyframe_guis()
3363 {
3364 // Send new configuration to keyframe GUI's
3365         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
3366         for(int i = 0; i < keyframe_threads->size(); i++)
3367         {
3368                 KeyFrameThread *ptr = keyframe_threads->get(i);
3369                 if(edl->tracks->plugin_exists(ptr->plugin))
3370                         ptr->update_gui(1);
3371                 else
3372                 {
3373                         ptr->close_window();
3374                 }
3375         }
3376         keyframe_gui_lock->unlock();
3377 }
3378
3379 void MWindow::update_plugin_guis(int do_keyframe_guis)
3380 {
3381 // Send new configuration to plugin GUI's
3382         plugin_gui_lock->lock("MWindow::update_plugin_guis");
3383
3384         for(int i = 0; i < plugin_guis->size(); i++)
3385         {
3386                 PluginServer *ptr = plugin_guis->get(i);
3387                 if(edl->tracks->plugin_exists(ptr->plugin))
3388                         ptr->update_gui();
3389                 else
3390                 {
3391 // Schedule for deletion if no plugin
3392                         plugin_guis->remove_number(i);
3393                         i--;
3394
3395                         ptr->hide_gui();
3396                         delete_plugin(ptr);
3397                 }
3398         }
3399
3400
3401 // Change plugin variable if not visible
3402         Track *track = edl->tracks->first;
3403         while(track)
3404         {
3405                 for(int i = 0; i < track->plugin_set.size(); i++)
3406                 {
3407                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3408                         while(plugin)
3409                         {
3410                                 int got_it = 0;
3411                                 for(int i = 0; i < plugin_guis->size(); i++)
3412                                 {
3413                                         PluginServer *server = plugin_guis->get(i);
3414                                         if(server->plugin == plugin)
3415                                         {
3416                                                 got_it = 1;
3417                                                 break;
3418                                         }
3419                                 }
3420
3421                                 if(!got_it) plugin->show = 0;
3422
3423                                 plugin = (Plugin*)plugin->next;
3424                         }
3425                 }
3426
3427                 track = track->next;
3428         }
3429
3430         plugin_gui_lock->unlock();
3431
3432
3433         if(do_keyframe_guis) update_keyframe_guis();
3434 }
3435
3436 int MWindow::plugin_gui_open(Plugin *plugin)
3437 {
3438         int result = 0;
3439         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3440         for(int i = 0; i < plugin_guis->total; i++)
3441         {
3442                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3443                 {
3444                         result = 1;
3445                         break;
3446                 }
3447         }
3448         plugin_gui_lock->unlock();
3449         return result;
3450 }
3451
3452 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3453 {
3454         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3455         for(int i = 0; i < plugin_guis->total; i++)
3456         {
3457                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3458                 {
3459                         plugin_guis->get(i)->render_gui(data);
3460                         break;
3461                 }
3462         }
3463         plugin_gui_lock->unlock();
3464 }
3465
3466 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3467 {
3468         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3469         for(int i = 0; i < plugin_guis->total; i++)
3470         {
3471                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3472                 {
3473                         plugin_guis->get(i)->render_gui(data, size);
3474                         break;
3475                 }
3476         }
3477         plugin_gui_lock->unlock();
3478 }
3479
3480
3481 void MWindow::update_plugin_states()
3482 {
3483         plugin_gui_lock->lock("MWindow::update_plugin_states");
3484         for(int i = 0; i < plugin_guis->total; i++)
3485         {
3486                 int result = 0;
3487 // Get a plugin GUI
3488                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
3489                 PluginServer *src_plugingui = plugin_guis->get(i);
3490
3491 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
3492                 for(Track *track = edl->tracks->first;
3493                         track && !result;
3494                         track = track->next)
3495                 {
3496                         for(int j = 0;
3497                                 j < track->plugin_set.total && !result;
3498                                 j++)
3499                         {
3500                                 PluginSet *plugin_set = track->plugin_set[j];
3501                                 for(Plugin *plugin = (Plugin*)plugin_set->first;
3502                                         plugin && !result;
3503                                         plugin = (Plugin*)plugin->next)
3504                                 {
3505                                         if(plugin == src_plugin &&
3506                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
3507                                 }
3508                         }
3509                 }
3510
3511
3512 // Doesn't exist anymore
3513                 if(!result)
3514                 {
3515                         hide_plugin(src_plugin, 0);
3516                         i--;
3517                 }
3518         }
3519         plugin_gui_lock->unlock();
3520 }
3521
3522
3523 void MWindow::update_plugin_titles()
3524 {
3525         for(int i = 0; i < plugin_guis->total; i++)
3526         {
3527                 plugin_guis->get(i)->update_title();
3528         }
3529 }
3530
3531 int MWindow::asset_to_edl(EDL *new_edl,
3532         Asset *new_asset,
3533         RecordLabels *labels)
3534 {
3535 const int debug = 0;
3536 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3537 __LINE__,
3538 new_asset->layers);
3539 // Keep frame rate, sample rate, and output size unchanged.
3540 // These parameters would revert the project if VWindow displayed an asset
3541 // of different size than the project.
3542         if(new_asset->video_data)
3543         {
3544                 new_edl->session->video_tracks = new_asset->layers;
3545         }
3546         else
3547                 new_edl->session->video_tracks = 0;
3548
3549 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3550
3551
3552
3553
3554
3555         if(new_asset->audio_data)
3556         {
3557                 new_edl->session->audio_tracks = new_asset->channels;
3558         }
3559         else
3560                 new_edl->session->audio_tracks = 0;
3561 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3562
3563 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3564         new_edl->create_default_tracks();
3565 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3566 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3567
3568
3569
3570 //printf("MWindow::asset_to_edl 3\n");
3571         new_edl->insert_asset(new_asset,
3572                 0,
3573                 0,
3574                 0,
3575                 labels);
3576 //printf("MWindow::asset_to_edl 3\n");
3577 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3578
3579 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3580         if(edl->session->cursor_on_frames)
3581         {
3582                 double length = new_edl->tracks->total_length();
3583                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3584                 new_edl->tracks->clear(length, edl_length, 1, 1);
3585         }
3586
3587
3588
3589
3590         char string[BCTEXTLEN];
3591         FileSystem fs;
3592         fs.extract_name(string, new_asset->path);
3593 //printf("MWindow::asset_to_edl 3\n");
3594
3595         strcpy(new_edl->local_session->clip_title, string);
3596 //printf("MWindow::asset_to_edl 4 %s\n", string);
3597 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3598
3599         return 0;
3600 }
3601
3602
3603 // Reset everything after a load.
3604 void MWindow::update_project(int load_mode)
3605 {
3606         const int debug = 0;
3607
3608         if(debug) PRINT_TRACE
3609         edl->tracks->update_y_pixels(theme);
3610         session->update_clip_number();
3611
3612         if(debug) PRINT_TRACE
3613
3614         if( load_mode == LOADMODE_REPLACE ||
3615             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3616                 delete gui->keyvalue_popup;
3617                 gui->keyvalue_popup = 0;
3618                 gui->load_panes();
3619         }
3620
3621         gui->update(1, NORMAL_DRAW, 1, 1, 1, 1, 1);
3622         if(debug) PRINT_TRACE
3623         gui->unlock_window();
3624         init_brender();
3625
3626         cwindow->gui->lock_window("MWindow::update_project 1");
3627         cwindow->update(0, 0, 1, 1, 1);
3628         cwindow->gui->unlock_window();
3629
3630         if(debug) PRINT_TRACE
3631
3632 // Close all the vwindows
3633         if( load_mode == LOADMODE_REPLACE ||
3634             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3635                 if(debug) PRINT_TRACE
3636                 int first_vwindow = 0;
3637                 if(session->show_vwindow) first_vwindow = 1;
3638 // Change visible windows to no source
3639                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3640                         VWindow *vwindow = vwindows[i];
3641                         if( !vwindow->is_running() ) continue;
3642                         vwindow->change_source(-1);
3643                 }
3644
3645 // Close remaining windows
3646                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3647                         VWindow *vwindow = vwindows[i];
3648                         if( !vwindow->is_running() ) continue;
3649                         vwindow->close_window();
3650                 }
3651                 for( int i=0; i<edl->vwindow_edls.size(); ++i ) {
3652                         VWindow *vwindow = get_viewer(1, -1);
3653                         vwindow->change_source(i);
3654                 }
3655                 if(debug) PRINT_TRACE
3656                 select_zwindow(0);
3657                 close_mixers(0);
3658
3659                 for( int i=0; i<edl->mixers.size(); ++i ) {
3660                         Mixer *mixer = edl->mixers[i];
3661                         ZWindow *zwindow = get_mixer(mixer);
3662                         zwindow->set_title(mixer->title);
3663                         zwindow->start();
3664                 }
3665         }
3666         update_vwindow();
3667
3668         if(debug) PRINT_TRACE
3669         cwindow->gui->lock_window("MWindow::update_project 2");
3670         cwindow->gui->timebar->update(0);
3671         cwindow->gui->unlock_window();
3672
3673         if(debug) PRINT_TRACE
3674         cwindow->refresh_frame(CHANGE_ALL);
3675
3676         awindow->gui->async_update_assets();
3677         if(debug) PRINT_TRACE
3678
3679         gui->lock_window("MWindow::update_project");
3680         gui->update_mixers(0, 0);
3681         gui->flush();
3682         if(debug) PRINT_TRACE
3683 }
3684
3685 void MWindow::update_vwindow()
3686 {
3687         for( int i=0; i<vwindows.size(); ++i ) {
3688                 VWindow *vwindow = vwindows[i];
3689                 if( vwindow->is_running() ) {
3690                         vwindow->gui->lock_window("MWindow::update_vwindow");
3691                         vwindow->update(1);
3692                         vwindow->gui->unlock_window();
3693                 }
3694         }
3695 }
3696
3697 void MWindow::remove_indexfile(Indexable *indexable)
3698 {
3699         if( !indexable->is_asset ) return;
3700         Asset *asset = (Asset *)indexable;
3701 // Erase file
3702         IndexFile::delete_index(preferences, asset, ".toc");
3703         IndexFile::delete_index(preferences, asset, ".idx");
3704         IndexFile::delete_index(preferences, asset, ".mkr");
3705 }
3706
3707 void MWindow::rebuild_indices()
3708 {
3709         for(int i = 0; i < session->drag_assets->total; i++)
3710         {
3711                 Indexable *indexable = session->drag_assets->get(i);
3712 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3713                 remove_indexfile(indexable);
3714 // Schedule index build
3715                 IndexState *index_state = indexable->index_state;
3716                 index_state->index_status = INDEX_NOTTESTED;
3717                 if( indexable->is_asset ) {
3718                         Asset *asset = (Asset *)indexable;
3719                         if( asset->format != FILE_PCM ) {
3720                                 asset->format = FILE_UNKNOWN;
3721                                 asset->reset_audio();
3722                         }
3723                         asset->reset_video();
3724                         remove_asset_from_caches(asset);
3725 //                      File file; // re-probe the asset
3726 //                      file.open_file(preferences, asset, 1, 0);
3727                 }
3728                 mainindexes->add_next_asset(0, indexable);
3729         }
3730         mainindexes->start_build();
3731 }
3732
3733
3734 void MWindow::save_backup()
3735 {
3736         FileXML file;
3737         edl->optimize();
3738         edl->set_path(session->filename);
3739         char backup_path[BCTEXTLEN], backup_path1[BCTEXTLEN];
3740         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3741                 File::get_config_path(), BACKUP_FILE);
3742         snprintf(backup_path1, sizeof(backup_path1), "%s/%s",
3743                 File::get_config_path(), BACKUP_FILE1);
3744         rename(backup_path, backup_path1);
3745         edl->save_xml(&file, backup_path);
3746         file.terminate_string();
3747         FileSystem fs;
3748         fs.complete_path(backup_path);
3749
3750         if(file.write_to_file(backup_path))
3751         {
3752                 char string2[256];
3753                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
3754                 gui->show_message(string2);
3755         }
3756 }
3757
3758 void MWindow::load_backup()
3759 {
3760         ArrayList<char*> path_list;
3761         path_list.set_array_delete();
3762         char *out_path;
3763         char backup_path[BCTEXTLEN];
3764         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3765                 File::get_config_path(), BACKUP_FILE);
3766         FileSystem fs;
3767         fs.complete_path(backup_path);
3768
3769         path_list.append(out_path = new char[strlen(backup_path) + 1]);
3770         strcpy(out_path, backup_path);
3771
3772         load_filenames(&path_list, LOADMODE_REPLACE, 0);
3773         edl->local_session->clip_title[0] = 0;
3774 // This is unique to backups since the path of the backup is different than the
3775 // path of the project.
3776         set_filename(edl->path);
3777         path_list.remove_all_objects();
3778         save_backup();
3779 }
3780
3781
3782 void MWindow::save_undo_data()
3783 {
3784         undo->update_undo_before();
3785         undo->update_undo_after(_("perpetual session"), LOAD_ALL);
3786         char perpetual_path[BCTEXTLEN];
3787         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
3788                 File::get_config_path(), PERPETUAL_FILE);
3789         FILE *fp = fopen(perpetual_path,"w");
3790         if( !fp ) return;
3791         undo->save(fp);
3792         fclose(fp);
3793 }
3794
3795 void MWindow::load_undo_data()
3796 {
3797         char perpetual_path[BCTEXTLEN];
3798         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
3799                 File::get_config_path(), PERPETUAL_FILE);
3800         FILE *fp = fopen(perpetual_path,"r");
3801         if( !fp ) return;
3802         undo->load(fp);
3803         fclose(fp);
3804 }
3805
3806
3807 int MWindow::copy_target(const char *path, const char *target)
3808 {
3809         int ifd = ::open(path, O_RDONLY);
3810         if( ifd < 0 ) {
3811                 eprintf("Cannot open asset: %s", path);
3812                 return 1;
3813         }
3814         int ret = 0;
3815         int ofd = ::open(target, O_CREAT+O_TRUNC+O_WRONLY, 0777);
3816         if( ofd >= 0 ) {
3817                 struct stat st;
3818                 int64_t total_bytes = !fstat(ifd, &st) ? st.st_size : 0;
3819                 char progress_title[BCTEXTLEN];
3820                 sprintf(progress_title, _("Copying: %s\n"), target);
3821                 BC_ProgressBox progress(-1, -1, progress_title, total_bytes);
3822
3823                 int64_t count = 0, len = -1;
3824                 int bfrsz = 0x100000;
3825                 uint8_t *bfr = new uint8_t[bfrsz];
3826                 while( (len=::read(ifd, bfr, bfrsz)) > 0 ) {
3827                         if( len != ::write(ofd, bfr, len) ) {
3828                                 eprintf("Error writing: %s", target);
3829                                 break;
3830                         }
3831                         if( progress.is_cancelled() ) {
3832                                 ret = 1;
3833                                 break;
3834                         }
3835                         progress.update(count += len, 1);
3836                 }
3837                 delete [] bfr;
3838                 ::close(ofd);
3839
3840                 progress.stop_progress();
3841                 if( len < 0 ) {
3842                         eprintf("Error reading: %s", path);
3843                         ret = 1;
3844                 }
3845         }
3846         else
3847                 eprintf("Cannot create asset target: %s", target);
3848         ::close(ifd);
3849         return ret;
3850 }
3851
3852 int MWindow::link_target(const char *real_path, const char *link_path, int relative)
3853 {
3854         char target[BCTEXTLEN];
3855         if( relative ) {
3856                 const char *bp = real_path, *cp = bp;
3857                 const char *lp = link_path, *np = lp;
3858                 char *tp = target, *ep = tp+sizeof(target)-1, lch;
3859                 while( *lp && *bp && (lch=*lp++) == *bp++ ) {
3860                         if( lch == '/' ) { np = lp;  cp = bp; }
3861                 }
3862                 while( tp<ep && *np ) {
3863                         if( *np++ != '/' ) continue;
3864                         *tp++ = '.';  *tp++ = '.';  *tp++ = '/';
3865                 }
3866                 while( tp<ep && *cp ) *tp++ = *cp++;
3867                 *tp = 0;
3868         }
3869         else
3870                 strcpy(target, real_path);
3871         if( symlink(target, link_path) ) {
3872                 eprintf("Cannot create symlink: %s", link_path);
3873                 return 1;
3874         }
3875         return 0;
3876 }
3877
3878 void MWindow::save_project(const char *dir, int save_mode, int overwrite, int reload)
3879 {
3880         char dir_path[BCTEXTLEN];
3881         strcpy(dir_path, dir);
3882         FileSystem fs;
3883         fs.complete_path(dir_path);
3884
3885         struct stat st;
3886         if( !stat(dir_path, &st) ) {
3887                 if( !S_ISDIR(st.st_mode) ) {
3888                         eprintf("Path exists and is not a directory\n%s", dir_path);
3889                         return;
3890                 }
3891         }
3892         else {
3893                 if( mkdir(dir_path, S_IRWXU | S_IRWXG | S_IRWXO) ) {
3894                         eprintf("Cannot create directory\n%s", dir_path);
3895                         return;
3896                 }
3897         }
3898         char *real_dir = realpath(dir_path, 0);
3899         strcpy(dir_path, real_dir);
3900         free(real_dir);
3901
3902         EDL *save_edl = new EDL;
3903         save_edl->create_objects();
3904         save_edl->copy_all(edl);
3905
3906         char progress_title[BCTEXTLEN];
3907         sprintf(progress_title, _("Saving to %s:\n"), dir);
3908         int total_assets = save_edl->assets->total();
3909         MainProgressBar *progress = mainprogress->start_progress(progress_title, total_assets);
3910         int ret = 0;
3911         Asset *current = save_edl->assets->first;
3912         for( int i=0; !ret && current; ++i, current=NEXT ) {
3913                 char *path = current->path;
3914                 if( ::stat(path, &st) ) {
3915                         eprintf("Asset not found: %s", path);
3916                         continue;
3917                 }
3918                 char *real_path = realpath(path, 0);
3919                 const char *cp = strrchr(path, '/'), *bp = !cp ? path : cp+1;
3920                 char link_path[BCTEXTLEN];
3921                 snprintf(link_path, sizeof(link_path), "%s/%s", dir_path, bp);
3922                 int skip = 0;
3923                 if( strcmp(real_path, link_path) ) {
3924                         if( !::lstat(link_path, &st) ) {
3925                                 if( overwrite )
3926                                         ::remove(link_path);
3927                                 else
3928                                         skip = 1;
3929                         }
3930                 }
3931                 else {
3932                         eprintf("copy/link to self, skippped: %s", path);
3933                         skip = 1;
3934                 }
3935                 if( !skip ) {
3936                         if( save_mode == SAVE_PROJECT_COPY ) {
3937                                 if( copy_target(real_path, link_path) )
3938                                         ret = 1;
3939                         }
3940                         else {
3941                                 link_target(real_path, link_path,
3942                                         save_mode == SAVE_PROJECT_RELLINK ? 1 : 0);
3943                         }
3944                 }
3945                 free(real_path);
3946                 strcpy(path, link_path);
3947
3948                 if( progress->is_cancelled() ) break;
3949                 progress->update(i);
3950         }
3951
3952         progress->stop_progress();
3953         delete progress;
3954
3955         char *cp = strrchr(dir_path,'/');
3956         char *bp = cp ? cp+1 : dir_path;
3957         char filename[BCTEXTLEN];
3958         snprintf(filename, sizeof(filename), "%s/%s.xml", dir_path, bp);
3959         save_edl->set_path(filename);
3960         FileXML file;
3961         save_edl->save_xml(&file, filename);
3962         file.terminate_string();
3963
3964         if( !file.write_to_file(filename) ) {
3965                 char string[BCTEXTLEN];
3966                 sprintf(string, _("\"%s\" %dC written"), filename, (int)strlen(file.string()));
3967                 gui->lock_window("SaveProject::run 2");
3968                 gui->show_message(string);
3969                 gui->unlock_window();
3970                 gui->mainmenu->add_load(filename);
3971         }
3972         else
3973                 eprintf(_("Couldn't open %s."), filename);
3974
3975         save_edl->remove_user();
3976
3977         if( reload ) {
3978                 gui->lock_window("MWindow::save_project");
3979                 ArrayList<char*> filenames;
3980                 filenames.append(filename);
3981                 load_filenames(&filenames, LOADMODE_REPLACE);
3982                 gui->unlock_window();
3983         }
3984 }
3985
3986
3987 static inline int gcd(int m, int n)
3988 {
3989         int r;
3990         if( m < n ) { r = m;  m = n;  n = r; }
3991         while( (r = m % n) != 0 ) { m = n;  n = r; }
3992         return n;
3993 }
3994
3995 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
3996 {
3997         w = 1;  h = 1;
3998         if(!width || !height) return 1;
3999         if( width == 720 && (height == 480 || height == 576) ) {
4000                 w = 4;  h = 3;  return 0; // for NTSC and PAL
4001         }
4002         double ar = (double)width / height;
4003 // square-ish pixels
4004         if( EQUIV(ar, 1.0000) ) return 0;
4005         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
4006         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
4007         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
4008         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
4009         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
4010         int ww = width, hh = height;
4011         // numerator, denominator must be under mx
4012         int mx = 255, n = gcd(ww, hh);
4013         if( n > 1 ) { ww /= n; hh /= n; }
4014         // search near height in case extra/missing lines
4015         if( ww >= mx || hh >= mx ) {
4016                 double err = height;  // +/- 2 percent height
4017                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
4018                         int iw = width, ih = height+i;
4019                         if( (n=gcd(iw, ih)) > 1 ) {
4020                                 int u = iw/n;  if( u >= mx ) continue;
4021                                 int v = ih/n;  if( v >= mx ) continue;
4022                                 double r = (double) u/v, er = fabs(ar-r);
4023                                 if( er >= err ) continue;
4024                                 err = er;  ww = u;  hh = v;
4025                         }
4026                 }
4027         }
4028
4029         w = ww;  h = hh;
4030         return 0;
4031 }
4032
4033 void MWindow::reset_caches()
4034 {
4035         frame_cache->remove_all();
4036         wave_cache->remove_all();
4037         audio_cache->remove_all();
4038         video_cache->remove_all();
4039         if( cwindow->playback_engine ) {
4040                 if( cwindow->playback_engine->audio_cache )
4041                         cwindow->playback_engine->audio_cache->remove_all();
4042                 if( cwindow->playback_engine->video_cache )
4043                         cwindow->playback_engine->video_cache->remove_all();
4044         }
4045         for(int i = 0; i < vwindows.size(); i++) {
4046                 VWindow *vwindow = vwindows[i];
4047                 if( !vwindow->is_running() ) continue;
4048                 if( !vwindow->playback_engine ) continue;
4049                 if( vwindow->playback_engine->audio_cache )
4050                         vwindow->playback_engine->audio_cache->remove_all();
4051                 if( vwindow->playback_engine->video_cache )
4052                         vwindow->playback_engine->video_cache->remove_all();
4053         }
4054 }
4055
4056 void MWindow::remove_asset_from_caches(Asset *asset)
4057 {
4058         frame_cache->remove_asset(asset);
4059         wave_cache->remove_asset(asset);
4060         audio_cache->delete_entry(asset);
4061         video_cache->delete_entry(asset);
4062         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
4063                 cwindow->playback_engine->audio_cache->delete_entry(asset);
4064         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
4065                 cwindow->playback_engine->video_cache->delete_entry(asset);
4066         for(int i = 0; i < vwindows.size(); i++) {
4067                 VWindow *vwindow = vwindows[i];
4068                 if( !vwindow->is_running() ) continue;
4069                 if( !vwindow->playback_engine ) continue;
4070                 if( vwindow->playback_engine->audio_cache )
4071                         vwindow->playback_engine->audio_cache->delete_entry(asset);
4072                 if( vwindow->playback_engine->video_cache )
4073                         vwindow->playback_engine->video_cache->delete_entry(asset);
4074         }
4075 }
4076
4077
4078 void MWindow::remove_assets_from_project(int push_undo, int redraw,
4079                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
4080 {
4081         awindow->gui->close_view_popup();
4082
4083         for(int i = 0; i < drag_assets->total; i++) {
4084                 Indexable *indexable = drag_assets->get(i);
4085                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
4086         }
4087
4088 // Remove from VWindow.
4089         for(int i = 0; i < session->drag_clips->total; i++) {
4090                 for(int j = 0; j < vwindows.size(); j++) {
4091                         VWindow *vwindow = vwindows[j];
4092                         if( !vwindow->is_running() ) continue;
4093                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
4094                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
4095                                 vwindow->delete_source(1, 1);
4096                                 vwindow->gui->unlock_window();
4097                         }
4098                 }
4099         }
4100
4101         for(int i = 0; i < drag_assets->size(); i++) {
4102                 for(int j = 0; j < vwindows.size(); j++) {
4103                         VWindow *vwindow = vwindows[j];
4104                         if( !vwindow->is_running() ) continue;
4105                         if(drag_assets->get(i) == vwindow->get_source()) {
4106                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
4107                                 vwindow->delete_source(1, 1);
4108                                 vwindow->gui->unlock_window();
4109                         }
4110                 }
4111         }
4112
4113         for(int i = 0; i < drag_assets->size(); i++) {
4114                 Indexable *indexable = drag_assets->get(i);
4115                 remove_indexfile(indexable);
4116         }
4117
4118 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
4119         if(push_undo) undo->update_undo_before();
4120         if(drag_assets) edl->remove_from_project(drag_assets);
4121         if(drag_clips) edl->remove_from_project(drag_clips);
4122         if(redraw) save_backup();
4123         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
4124         if(redraw) {
4125                 restart_brender();
4126
4127                 gui->lock_window("MWindow::remove_assets_from_project 3");
4128                 gui->update(1, NORMAL_DRAW, 1, 1, 0, 1, 0);
4129                 gui->unlock_window();
4130
4131         // Removes from playback here
4132                 sync_parameters(CHANGE_ALL);
4133         }
4134
4135         awindow->gui->async_update_assets();
4136 }
4137
4138 void MWindow::remove_assets_from_disk()
4139 {
4140         remove_assets_from_project(1,
4141                 1,
4142                 session->drag_assets,
4143                 session->drag_clips);
4144
4145 // Remove from disk
4146         for(int i = 0; i < session->drag_assets->total; i++)
4147         {
4148                 remove(session->drag_assets->get(i)->path);
4149         }
4150 }
4151
4152 void MWindow::dump_plugins(FILE *fp)
4153 {
4154         if( !plugindb ) return;
4155         for(int i = 0; i < plugindb->total; i++)
4156         {
4157                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
4158                         " synth=%d transition=%d theme=%d %s\n",
4159                         plugindb->get(i)->plugin_type,
4160                         plugindb->get(i)->audio,
4161                         plugindb->get(i)->video,
4162                         plugindb->get(i)->realtime,
4163                         plugindb->get(i)->multichannel,
4164                         plugindb->get(i)->get_synthesis(),
4165                         plugindb->get(i)->transition,
4166                         plugindb->get(i)->theme,
4167                         plugindb->get(i)->title);
4168         }
4169 }
4170
4171 void MWindow::dump_edl(FILE *fp)
4172 {
4173         if( !edl ) return;
4174         edl->dump(fp);
4175 }
4176
4177 void MWindow::dump_undo(FILE *fp)
4178 {
4179         if( !undo ) return;
4180         undo->dump(fp);
4181 }
4182
4183 void MWindow::dump_exe(FILE *fp)
4184 {
4185         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
4186         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
4187
4188         int ret = -1, n = 100;
4189         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
4190                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
4191                 ret = 0;
4192         }
4193         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
4194
4195         struct stat st;
4196         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
4197         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
4198         struct tm *tm = localtime(&st.st_mtime);
4199         char mtime[256];
4200         strftime(mtime, sizeof(mtime), "%F %T", tm);
4201         fprintf(fp,"mtime: %s\n", mtime);
4202 #if 0
4203 // people hit ctl-c waiting for this
4204         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
4205         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
4206         uint8_t *bfr = 0;
4207         int64_t bfrsz = 0;
4208         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
4209         int64_t maxsz = 1024*pagsz;
4210         int64_t size = st.st_size, pos = 0;
4211         SHA1 sha1;
4212         while( (bfrsz = size-pos) > 0 ) {
4213                 if( bfrsz > maxsz ) bfrsz = maxsz;
4214                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
4215                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
4216                 if( bfr == MAP_FAILED ) break;
4217                 sha1.addBytes(bfr, bfrsz);
4218                 munmap(bfr, bfrsz);
4219                 pos += bfrsz;
4220         }
4221         close(fd);
4222         ret = pos < size ? EIO : 0;
4223         fprintf(fp, "SHA1: ");
4224         uint8_t digest[20];  sha1.computeHash(digest);
4225         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
4226         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
4227         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
4228 #endif
4229         fprintf(fp, "\n");
4230 }
4231
4232 void MWindow::trap_hook(FILE *fp, void *vp)
4233 {
4234         MWindow *mwindow = (MWindow *)vp;
4235 //      fprintf(fp, "\nPLUGINS:\n");
4236 //      mwindow->dump_plugins(fp);
4237         fprintf(fp, "\nEDL:\n");
4238         mwindow->dump_edl(fp);
4239         fprintf(fp, "\nUNDO:\n");
4240         mwindow->dump_undo(fp);
4241         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
4242         mwindow->dump_exe(fp);
4243 }
4244
4245
4246
4247
4248
4249
4250 int MWindow::save_defaults()
4251 {
4252         gui->save_defaults(defaults);
4253         edl->save_defaults(defaults);
4254         session->save_defaults(defaults);
4255         preferences->save_defaults(defaults);
4256
4257         for(int i = 0; i < plugin_guis->total; i++)
4258         {
4259 // Pointer comparison
4260                 plugin_guis->get(i)->save_defaults();
4261         }
4262         awindow->save_defaults(defaults);
4263
4264         defaults->save();
4265         return 0;
4266 }
4267
4268 int MWindow::run_script(FileXML *script)
4269 {
4270         int result = 0, result2 = 0;
4271         while(!result && !result2)
4272         {
4273                 result = script->read_tag();
4274                 if(!result)
4275                 {
4276                         if(script->tag.title_is("new_project"))
4277                         {
4278 // Run new in immediate mode.
4279 //                              gui->mainmenu->new_project->run_script(script);
4280                         }
4281                         else
4282                         if(script->tag.title_is("record"))
4283                         {
4284 // Run record as a thread.  It is a terminal command.
4285                                 ;
4286 // Will read the complete scipt file without letting record read it if not
4287 // terminated.
4288                                 result2 = 1;
4289                         }
4290                         else
4291                         {
4292                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
4293                         }
4294                 }
4295         }
4296         return result2;
4297 }
4298
4299 // ================================= synchronization
4300
4301
4302 int MWindow::interrupt_indexes()
4303 {
4304         mainprogress->cancelled = 1;
4305         mainindexes->interrupt_build();
4306         return 0;
4307 }
4308
4309
4310
4311 void MWindow::next_time_format()
4312 {
4313         switch(edl->session->time_format)
4314         {
4315                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
4316                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
4317                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
4318                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
4319                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
4320                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
4321                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
4322         }
4323
4324         time_format_common();
4325 }
4326
4327 void MWindow::prev_time_format()
4328 {
4329         switch(edl->session->time_format)
4330         {
4331                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
4332                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
4333                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
4334                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
4335                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
4336                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
4337                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
4338         }
4339
4340         time_format_common();
4341 }
4342
4343 void MWindow::time_format_common()
4344 {
4345         gui->lock_window("MWindow::next_time_format");
4346         gui->redraw_time_dependancies();
4347
4348
4349         char string[BCTEXTLEN], string2[BCTEXTLEN];
4350         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
4351         gui->show_message(string);
4352         gui->flush();
4353         gui->unlock_window();
4354 }
4355
4356
4357 int MWindow::set_filename(const char *filename)
4358 {
4359         if( filename != session->filename )
4360                 strcpy(session->filename, filename);
4361         if( filename != edl->path )
4362                 strcpy(edl->path, filename);
4363
4364         if(gui)
4365         {
4366                 if(filename[0] == 0)
4367                 {
4368                         gui->set_title(PROGRAM_NAME);
4369                 }
4370                 else
4371                 {
4372                         FileSystem dir;
4373                         char string[BCTEXTLEN], string2[BCTEXTLEN];
4374                         dir.extract_name(string, filename);
4375                         sprintf(string2, PROGRAM_NAME ": %s", string);
4376                         gui->set_title(string2);
4377                 }
4378         }
4379         return 0;
4380 }
4381
4382
4383
4384
4385
4386
4387
4388
4389 int MWindow::set_loop_boundaries()
4390 {
4391         double start = edl->local_session->get_selectionstart();
4392         double end = edl->local_session->get_selectionend();
4393
4394         if(start !=
4395                 end)
4396         {
4397                 ;
4398         }
4399         else
4400         if(edl->tracks->total_length())
4401         {
4402                 start = 0;
4403                 end = edl->tracks->total_length();
4404         }
4405         else
4406         {
4407                 start = end = 0;
4408         }
4409
4410         if(edl->local_session->loop_playback && start != end)
4411         {
4412                 edl->local_session->loop_start = start;
4413                 edl->local_session->loop_end = end;
4414         }
4415         return 0;
4416 }
4417
4418
4419
4420
4421
4422
4423
4424 int MWindow::reset_meters()
4425 {
4426         cwindow->gui->lock_window("MWindow::reset_meters 1");
4427         cwindow->gui->meters->reset_meters();
4428         cwindow->gui->unlock_window();
4429
4430         for(int j = 0; j < vwindows.size(); j++) {
4431                 VWindow *vwindow = vwindows[j];
4432                 if( !vwindow->is_running() ) continue;
4433                 vwindow->gui->lock_window("MWindow::reset_meters 2");
4434                 vwindow->gui->meters->reset_meters();
4435                 vwindow->gui->unlock_window();
4436         }
4437
4438         lwindow->gui->lock_window("MWindow::reset_meters 3");
4439         lwindow->gui->panel->reset_meters();
4440         lwindow->gui->unlock_window();
4441
4442         gui->lock_window("MWindow::reset_meters 4");
4443         gui->reset_meters();
4444         gui->unlock_window();
4445         return 0;
4446 }
4447
4448
4449 void MWindow::resync_guis()
4450 {
4451 // Update GUIs
4452         restart_brender();
4453         gui->lock_window("MWindow::resync_guis");
4454         gui->update(1, NORMAL_DRAW, 1, 1, 1, 1, 0);
4455         gui->unlock_window();
4456
4457         cwindow->gui->lock_window("MWindow::resync_guis");
4458         cwindow->gui->resize_event(cwindow->gui->get_w(),
4459                 cwindow->gui->get_h());
4460         int channels = edl->session->audio_channels;
4461         cwindow->gui->meters->set_meters(channels, 1);
4462         cwindow->gui->flush();
4463         cwindow->gui->unlock_window();
4464
4465         for(int i = 0; i < vwindows.size(); i++) {
4466                 VWindow *vwindow = vwindows[i];
4467                 if( !vwindow->is_running() ) continue;
4468                 vwindow->gui->lock_window("MWindow::resync_guis");
4469                 vwindow->gui->resize_event(vwindow->gui->get_w(),
4470                         vwindow->gui->get_h());
4471                 vwindow->gui->meters->set_meters(channels, 1);
4472                 vwindow->gui->flush();
4473                 vwindow->gui->unlock_window();
4474         }
4475
4476         lwindow->gui->lock_window("MWindow::resync_guis");
4477         lwindow->gui->panel->set_meters(channels, 1);
4478         lwindow->gui->flush();
4479         lwindow->gui->unlock_window();
4480
4481 // Warn user
4482         if(((edl->session->output_w % 4) ||
4483                 (edl->session->output_h % 4)) &&
4484                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
4485         {
4486                 MainError::show_error(
4487                         _("This project's dimensions are not multiples of 4 so\n"
4488                         "it can't be rendered by OpenGL."));
4489         }
4490
4491
4492 // Flash frame
4493         sync_parameters(CHANGE_ALL);
4494 }
4495
4496 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
4497 {
4498         File *file = new File;
4499         EDLSession *session = edl->session;
4500         double old_framerate = session->frame_rate;
4501         double old_samplerate = session->sample_rate;
4502         int old_auto_keyframes = session->auto_keyframes;
4503         session->auto_keyframes = 0;
4504         int result = file->open_file(preferences, asset, 1, 0);
4505         if( !result && delete_tracks > 0 )
4506                 undo->update_undo_before();
4507         int video_layers = asset->get_video_layers();
4508         if( !result && asset->video_data && vstream < video_layers ) {
4509                 // try to get asset up to date, may fail
4510                 file->select_video_stream(asset, vstream);
4511                 // either way use what was/is there.
4512                 double framerate = asset->get_frame_rate();
4513                 int width = asset->get_w();
4514                 int height = asset->get_h();
4515                 // must be multiple of 4 for opengl
4516                 width = (width+3) & ~3;  height = (height+3) & ~3;
4517                 int driver = session->playback_config->vconfig->driver;
4518                 int color_model = file->get_best_colormodel(asset, driver);
4519 //              color_model = BC_CModels::is_yuv(color_model) ?
4520 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
4521 //                      BC_CModels::is_float(color_model) ?
4522 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
4523 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
4524 // have alpha for now
4525                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
4526                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
4527                 session->color_model = color_model;
4528                 session->output_w = width;
4529                 session->output_h = height;
4530                 session->frame_rate = framerate;
4531                 // not, asset->actual_width/actual_height
4532                 asset->width = session->output_w;
4533                 asset->height = session->output_h;
4534                 asset->frame_rate = session->frame_rate;
4535                 create_aspect_ratio(session->aspect_w, session->aspect_h,
4536                         session->output_w, session->output_h);
4537                 Track *track = edl->tracks->first;
4538                 for( Track *next_track=0; track; track=next_track ) {
4539                         next_track = track->next;
4540                         if( track->data_type != TRACK_VIDEO ) continue;
4541                         if( delete_tracks ) {
4542                                 Edit *edit = track->edits->first;
4543                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
4544                                         next_edit = edit->next;
4545                                         if( edit->channel != vstream ||
4546                                             !edit->asset || !edit->asset->is_asset ||
4547                                             !asset->equivalent(*edit->asset,1,1,edl) )
4548                                                 delete edit;
4549                                 }
4550                         }
4551                         if( track->edits->first ) {
4552                                 track->track_w = edl->session->output_w;
4553                                 track->track_h = edl->session->output_h;
4554                         }
4555                         else if( delete_tracks )
4556                                 edl->tracks->delete_track(track);
4557                 }
4558                 edl->retrack();
4559                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
4560         }
4561         if( !result && asset->audio_data && asset->channels > 0 ) {
4562                 session->sample_rate = asset->get_sample_rate();
4563                 int64_t channel_mask = 0;
4564                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
4565                         file->get_audio_for_video(vstream, astream, channel_mask);
4566                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
4567                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
4568                 int channels = 0;
4569                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
4570                 if( channels < 1 ) channels = 1;
4571                 if( channels > 6 ) channels = 6;
4572                 session->audio_tracks = session->audio_channels = channels;
4573
4574                 int *achannel_positions = preferences->channel_positions[session->audio_channels-1];
4575                 memcpy(&session->achannel_positions, achannel_positions, sizeof(session->achannel_positions));
4576                 remap_audio(MWindow::AUDIO_1_TO_1);
4577
4578                 if( delete_tracks ) {
4579                         Track *track = edl->tracks->first;
4580                         for( Track *next_track=0; track; track=next_track ) {
4581                                 next_track = track->next;
4582                                 if( track->data_type != TRACK_AUDIO ) continue;
4583                                 Edit *edit = track->edits->first;
4584                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
4585                                         next_edit = edit->next;
4586                                         if( !((1<<edit->channel) & channel_mask) ||
4587                                             !edit->asset || !edit->asset->is_asset ||
4588                                             !asset->equivalent(*edit->asset,1,1,edl) )
4589                                                 delete edit;
4590                                 }
4591                                 if( !track->edits->first )
4592                                         edl->tracks->delete_track(track);
4593                         }
4594                 }
4595                 edl->rechannel();
4596                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
4597         }
4598         delete file;
4599         session->auto_keyframes = old_auto_keyframes;
4600         if( !result && delete_tracks > 0 ) {
4601                 save_backup();
4602                 undo->update_undo_after(_("select asset"), LOAD_ALL);
4603         }
4604         resync_guis();
4605         return result;
4606 }
4607
4608 int MWindow::select_asset(int vtrack, int delete_tracks)
4609 {
4610         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
4611         if( !track )
4612                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
4613         if( !track ) return 1;
4614         Edit *edit = track->edits->first;
4615         if( !edit ) return 1;
4616         Asset *asset = edit->asset;
4617         if( !asset || !asset->is_asset ) return 1;
4618         return select_asset(asset, edit->channel, 0, delete_tracks);
4619 }
4620
4621 void MWindow::dump_plugindb(FILE *fp)
4622 {
4623         if( !plugindb ) return;
4624         for(int i = 0; i < plugindb->total; i++)
4625                 plugindb->get(i)->dump(fp);
4626 }
4627
4628 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
4629 {
4630         Auto *current = 0;
4631         double unit_position = edl->local_session->get_selectionstart(1);
4632         unit_position = patch->track->to_units(unit_position, 0);
4633
4634         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
4635         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4636 }
4637
4638 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
4639 {
4640         Auto *current = 0;
4641         double unit_position = edl->local_session->get_selectionstart(1);
4642         unit_position = patch->track->to_units(unit_position, 0);
4643
4644         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
4645         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4646 }
4647
4648 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
4649 {
4650         Auto *current = 0;
4651         double unit_position = edl->local_session->get_selectionstart(1);
4652         unit_position = patch->track->to_units(unit_position, 0);
4653
4654         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
4655         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4656 }
4657
4658 PatchGUI *MWindow::get_patchgui(Track *track)
4659 {
4660         PatchGUI *patchgui = 0;
4661         TimelinePane **panes = gui->pane;
4662         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
4663                 if( !panes[i] ) continue;
4664                 PatchBay *patchbay = panes[i]->patchbay;
4665                 if( !patchbay ) continue;
4666                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
4667                         if( patchbay->patches.values[j]->track == track )
4668                                 patchgui = patchbay->patches.values[j];
4669                 }
4670         }
4671         return patchgui;
4672 }
4673