546444fe2bbd6b053ca1450298e2e4fc3ecdd9ad
[goodguy/cinelerra.git] / cinelerra-5.1 / cinelerra / mwindow.C
1 /*
2  * CINELERRA
3  * Copyright (C) 1997-2014 Adam Williams <broadcast at earthling dot net>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  */
20
21 #include "aboutprefs.h"
22 #include "asset.h"
23 #include "assets.h"
24 #include "atrack.h"
25 #include "audioalsa.h"
26 #include "autos.h"
27 #include "awindowgui.h"
28 #include "awindow.h"
29 #include "batchrender.h"
30 #include "bcdisplayinfo.h"
31 #include "bcprogressbox.h"
32 #include "bcsignals.h"
33 #include "bctimer.h"
34 #include "bctrace.h"
35 #include "bdcreate.h"
36 #include "brender.h"
37 #include "cache.h"
38 #include "channel.h"
39 #include "channeldb.h"
40 #include "channelinfo.h"
41 #include "clip.h"
42 #include "clipedls.h"
43 #include "bccmodels.h"
44 #include "commercials.h"
45 #include "confirmsave.h"
46 #include "cplayback.h"
47 #include "ctimebar.h"
48 #include "cwindowgui.h"
49 #include "cwindow.h"
50 #include "cwindowtool.h"
51 #include "bchash.h"
52 #include "devicedvbinput.inc"
53 #include "dvdcreate.h"
54 #include "editpanel.h"
55 #include "edl.h"
56 #include "edlsession.h"
57 #include "errorbox.h"
58 #include "fileformat.h"
59 #include "file.h"
60 #include "filesystem.h"
61 #include "filexml.h"
62 #include "floatautos.h"
63 #include "framecache.h"
64 #include "gwindow.h"
65 #include "gwindowgui.h"
66 #include "keyframegui.h"
67 #include "indexfile.h"
68 #include "intautos.h"
69 #include "interlacemodes.h"
70 #include "language.h"
71 #include "levelwindowgui.h"
72 #include "levelwindow.h"
73 #include "loadfile.inc"
74 #include "localsession.h"
75 #include "maincursor.h"
76 #include "mainerror.h"
77 #include "mainindexes.h"
78 #include "mainmenu.h"
79 #include "mainprogress.h"
80 #include "mainsession.h"
81 #include "mainundo.h"
82 #include "mbuttons.h"
83 #include "mixersalign.h"
84 #include "mutex.h"
85 #include "mwindowgui.h"
86 #include "mwindow.h"
87 #include "new.h"
88 #include "panautos.h"
89 #include "patchbay.h"
90 #include "playback3d.h"
91 #include "playbackengine.h"
92 #include "plugin.h"
93 #include "pluginserver.h"
94 #include "pluginset.h"
95 #include "preferences.h"
96 #include "proxy.h"
97 #include "record.h"
98 #include "recordmonitor.h"
99 #include "recordlabel.h"
100 #include "removefile.h"
101 #include "render.h"
102 #include "resourcethread.h"
103 #include "savefile.inc"
104 #include "samplescroll.h"
105 #include "sha1.h"
106 #include "shuttle.h"
107 #include "sighandler.h"
108 #include "splashgui.h"
109 #include "statusbar.h"
110 #include "theme.h"
111 #include "threadloader.h"
112 #include "timebar.h"
113 #include "timelinepane.h"
114 #include "tipwindow.h"
115 #include "trackcanvas.h"
116 #include "track.h"
117 #include "tracking.h"
118 #include "trackscroll.h"
119 #include "tracks.h"
120 #include "transition.h"
121 #include "transportque.h"
122 #include "vframe.h"
123 #include "vtrack.h"
124 #include "versioninfo.h"
125 #include "vicon.h"
126 #include "videodevice.inc"
127 #include "videowindow.h"
128 #include "vplayback.h"
129 #include "vwindowgui.h"
130 #include "vwindow.h"
131 #include "wavecache.h"
132 #include "wwindow.h"
133 #include "zoombar.h"
134 #include "zwindow.h"
135 #include "zwindowgui.h"
136 #include "exportedl.h"
137
138 #include "defaultformats.h"
139 #include "ntsczones.h"
140
141 #include <stdint.h>
142 #include <stdlib.h>
143 #include <unistd.h>
144 #include <fcntl.h>
145 #include <string.h>
146 #include <sys/types.h>
147 #include <sys/stat.h>
148 #include <sys/time.h>
149 #include <sys/mman.h>
150 #include <sys/file.h>
151 #include <limits.h>
152 #include <errno.h>
153
154
155 extern "C"
156 {
157
158
159
160
161 // Hack for libdv to remove glib dependancy
162
163 // void
164 // g_log (const char    *log_domain,
165 //        int  log_level,
166 //        const char    *format,
167 //        ...)
168 // {
169 // }
170 //
171 // void
172 // g_logv (const char    *log_domain,
173 //        int  log_level,
174 //        const char    *format,
175 //        ...)
176 // {
177 // }
178 //
179
180 }
181
182
183 extern long cin_timezone;
184
185 ArrayList<PluginServer*>* MWindow::plugindb = 0;
186 Commercials* MWindow::commercials = 0;
187
188
189 MWindow::MWindow()
190  : Thread(1, 0, 0)
191 {
192         run_lock = new Mutex("MWindow::run_lock");
193         plugin_gui_lock = new Mutex("MWindow::plugin_gui_lock");
194         dead_plugin_lock = new Mutex("MWindow::dead_plugin_lock");
195         vwindows_lock = new Mutex("MWindow::vwindows_lock");
196         zwindows_lock = new Mutex("MWindow::zwindows_lock");
197         brender_lock = new Mutex("MWindow::brender_lock");
198         keyframe_gui_lock = new Mutex("MWindow::keyframe_gui_lock");
199
200         playback_3d = 0;
201         splash_window = 0;
202         undo = 0;
203         undo_command = COMMAND_NONE;
204         defaults = 0;
205         assets = 0;
206         //commercials = 0;
207         commercial_active = 0;
208         audio_cache = 0;
209         video_cache = 0;
210         frame_cache = 0;
211         wave_cache = 0;
212         preferences = 0;
213         session = 0;
214         theme = 0;
215         mainindexes = 0;
216         mainprogress = 0;
217         brender = 0;
218         brender_active = 0;
219         strcpy(cin_lang,"en");
220         channeldb_buz =  new ChannelDB;
221         channeldb_v4l2jpeg =  new ChannelDB;
222         plugin_guis = 0;
223         dead_plugins = 0;
224         keyframe_threads = 0;
225         create_bd = 0;
226         create_dvd = 0;
227         batch_render = 0;
228         render = 0;
229         edl = 0;
230         gui = 0;
231         cwindow = 0;
232         awindow = 0;
233         gwindow = 0;
234         twindow = 0;
235         wwindow = 0;
236         lwindow = 0;
237         sighandler = 0;
238         restart_status = 0;
239         screens = 1;
240         in_destructor = 0;
241         speed_edl = 0;
242         proxy_beep = 0;
243         shuttle = 0;
244         mixers_align = 0;
245 }
246
247
248 // Need to delete brender temporary here.
249 MWindow::~MWindow()
250 {
251         run_lock->lock("MWindow::~MWindow");
252         in_destructor = 1;
253 //printf("MWindow::~MWindow %d\n", __LINE__);
254         if( wwindow && wwindow->is_running() )
255                 wwindow->close_window();
256         if( twindow && twindow->is_running() )
257                 twindow->close_window();
258         gui->remote_control->deactivate();
259         gui->record->stop();
260 #ifdef HAVE_DVB
261         gui->channel_info->stop();
262 #endif
263         delete proxy_beep;
264         delete create_bd;       create_bd = 0;
265         delete create_dvd;      create_dvd = 0;
266         delete shuttle;         shuttle = 0;
267         delete batch_render;    batch_render = 0;
268         delete render;          render = 0;
269         delete mixers_align;    mixers_align = 0;
270         commit_commercial();
271         if( commercials && !commercials->remove_user() ) commercials = 0;
272         close_mixers();
273         if( speed_edl ) { speed_edl->remove_user();  speed_edl = 0; }
274 // Save defaults for open plugins
275         plugin_gui_lock->lock("MWindow::~MWindow");
276         for(int i = 0; i < plugin_guis->size(); i++) {
277                 plugin_guis->get(i)->hide_gui();
278                 delete_plugin(plugin_guis->get(i));
279         }
280         plugin_gui_lock->unlock();
281         hide_keyframe_guis();
282         clean_indexes();
283         save_defaults();
284 // Give up and go to a movie
285 //  cant run valgrind if this is used
286
287         gui->del_keyboard_listener(
288                 (int (BC_WindowBase::*)(BC_WindowBase *))
289                 &MWindowGUI::keyboard_listener);
290 #if 0
291 // release the hounds
292         if( awindow && awindow->gui ) awindow->gui->close(0);
293         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
294         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
295         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
296         vwindows.remove_all_objects();
297         zwindows.remove_all_objects();
298         gui->close(0);
299         if( awindow ) awindow->join();
300         if( cwindow ) cwindow->join();
301         if( lwindow ) lwindow->join();
302         if( gwindow ) gwindow->join();
303         join();
304 #else
305 // one at a time, or nouveau chokes
306 #define close_gui(win) if( win ) { \
307   if( win->gui ) win->gui->close(0); \
308   win->join(); }
309         close_gui(awindow);
310         close_gui(cwindow);
311         close_gui(lwindow);
312         close_gui(gwindow);
313         vwindows.remove_all_objects();
314         zwindows.remove_all_objects();
315         gui->close(0);
316         join();
317 #endif
318         reset_caches();
319         dead_plugins->remove_all_objects();
320 // must delete theme before destroying plugindb
321 //  theme destructor will be deleted by delete_plugins
322         delete theme;           theme = 0;
323         delete_plugins();
324         finit_error();
325         keyframe_threads->remove_all_objects();
326         colormodels.remove_all_objects();
327         delete awindow;         awindow = 0;
328         delete lwindow;         lwindow = 0;
329         delete twindow;         twindow = 0;
330         delete wwindow;         wwindow = 0;
331         delete gwindow;         gwindow = 0;
332         delete cwindow;         cwindow = 0;
333         delete gui;             gui = 0;
334         delete mainindexes;     mainindexes = 0;
335         delete mainprogress;    mainprogress = 0;
336         delete audio_cache;     audio_cache = 0;  // delete the cache after the assets
337         delete video_cache;     video_cache = 0;  // delete the cache after the assets
338         delete frame_cache;     frame_cache = 0;
339         delete wave_cache;      wave_cache = 0;
340         delete plugin_guis;     plugin_guis = 0;
341         delete dead_plugins;    dead_plugins = 0;
342         delete keyframe_threads;  keyframe_threads = 0;
343         delete undo;            undo = 0;
344         delete preferences;     preferences = 0;
345         delete exportedl;       exportedl = 0;
346         delete session;         session = 0;
347         delete defaults;        defaults = 0;
348         delete assets;          assets = 0;
349         delete splash_window;   splash_window = 0;
350         if( !edl->Garbage::remove_user() ) edl = 0;
351         delete channeldb_buz;
352         delete channeldb_v4l2jpeg;
353 // This must be last thread to exit
354         delete playback_3d;     playback_3d = 0;
355         delete dead_plugin_lock;
356         delete plugin_gui_lock;
357         delete vwindows_lock;
358         delete zwindows_lock;
359         delete brender_lock;
360         delete keyframe_gui_lock;
361         colormodels.remove_all_objects();
362         interlace_project_modes.remove_all_objects();
363         interlace_asset_modes.remove_all_objects();
364         interlace_asset_fixmethods.remove_all_objects();
365         sighandler->terminate();
366         delete sighandler;
367         delete run_lock;
368 }
369
370
371 void MWindow::quit()
372 {
373         gui->set_done(0);
374 }
375
376 void MWindow::init_error()
377 {
378         MainError::init_error(this);
379 }
380
381 void MWindow::finit_error()
382 {
383         MainError::finit_error();
384 }
385
386 void MWindow::create_defaults_path(char *string, const char *config_file)
387 {
388 // set the .bcast path
389         FileSystem fs;
390
391         sprintf(string, "%s/", File::get_config_path());
392         fs.complete_path(string);
393         if(!fs.is_dir(string))
394                 fs.create_dir(string);
395
396 // load the defaults
397         strcat(string, config_file);
398 }
399 const char *MWindow::default_std()
400 {
401         char buf[BCTEXTLEN], *p = 0;
402
403         int fd = open(TIMEZONE_NAME, O_RDONLY);
404         if( fd >= 0 ) {
405                 int l = read(fd, buf, sizeof(buf)-1);
406                 close(fd);
407                 if( l > 0 ) {
408                         if( buf[l-1] == '\n' ) --l;
409                         buf[l] = 0;
410                         p = buf;
411                 }
412         }
413         if( !p ) {
414                 int l = readlink(LOCALTIME_LINK, buf, sizeof(buf)-1);
415                 if( l > 0 ) {
416                         buf[l] = 0;
417                         if( !(p=strstr(buf, ZONEINFO_STR)) != 0 ) return "PAL";
418                         p += strlen(ZONEINFO_STR);
419                 }
420         }
421
422         if( p ) {
423                 for( int i=0; ntsc_zones[i]; ++i ) {
424                         if( !strcmp(ntsc_zones[i], p) )
425                                 return "NTSC";
426                 }
427         }
428
429         p = getenv("TZ");
430         if( p ) {
431                 for( int i=0; ntsc_zones[i]; ++i ) {
432                         if( !strcmp(ntsc_zones[i], p) )
433                                 return "NTSC";
434                 }
435         }
436
437 // cin_timezone: Seconds west of UTC.  240sec/deg
438         double tz_deg =  -cin_timezone / 240.;
439 // from Honolulu = -10, to New York = -5, 15deg/hr   lat -150..-75
440         return tz_deg >= -10*15 && tz_deg <= -5*15 ? "NTSC" : "PAL";
441 }
442
443 void MWindow::fill_preset_defaults(const char *preset, EDLSession *session)
444 {
445         struct formatpresets *fpr;
446
447         for(fpr = &format_presets[0]; fpr->name; fpr++)
448         {
449                 if(strcmp(_(fpr->name), preset) == 0)
450                 {
451                         session->audio_channels = fpr->audio_channels;
452                         session->audio_tracks = fpr->audio_tracks;
453                         session->sample_rate = fpr->sample_rate;
454                         session->video_channels = fpr->video_channels;
455                         session->video_tracks = fpr->video_tracks;
456                         session->frame_rate = fpr->frame_rate;
457                         session->output_w = fpr->output_w;
458                         session->output_h = fpr->output_h;
459                         session->aspect_w = fpr->aspect_w;
460                         session->aspect_h = fpr->aspect_h;
461                         session->interlace_mode = fpr->interlace_mode;
462                         session->color_model = fpr->color_model;
463                         return;
464                 }
465         }
466 }
467
468 const char *MWindow::get_preset_name(int index)
469 {
470         if(index < 0 || index >= (int)MAX_NUM_PRESETS)
471                 return "Error";
472         return _(format_presets[index].name);
473 }
474
475
476 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
477 {
478         char path[BCTEXTLEN];
479 // Use user supplied path
480         if(config_path[0])
481                 strcpy(path, config_path);
482         else
483                 create_defaults_path(path, CONFIG_FILE);
484
485         delete defaults;
486         defaults = new BC_Hash(path);
487         defaults->load();
488 }
489
490
491 void MWindow::check_language()
492 {
493         char curr_lang[BCTEXTLEN]; curr_lang[0] = 0;
494         const char *env_lang = getenv("LANGUAGE");
495         if( !env_lang ) env_lang = getenv("LC_ALL");
496         if( !env_lang ) env_lang = getenv("LANG");
497         if( !env_lang ) {
498                 snprintf(curr_lang, sizeof(curr_lang), "%s_%s-%s",
499                         BC_Resources::language, BC_Resources::region, BC_Resources::encoding);
500                 env_lang = curr_lang;
501         }
502         char last_lang[BCTEXTLEN]; last_lang[0] = 0;
503         defaults->get("LAST_LANG",last_lang);
504         if( strcmp(env_lang,last_lang)) {
505                 printf("lang changed from '%s' to '%s'\n", last_lang, env_lang);
506                 defaults->update("LAST_LANG",env_lang);
507                 char plugin_path[BCTEXTLEN];
508                 create_defaults_path(plugin_path, PLUGIN_FILE);
509                 ::remove(plugin_path);
510                 char ladspa_path[BCTEXTLEN];
511                 create_defaults_path(ladspa_path, LADSPA_FILE);
512                 ::remove(ladspa_path);
513                 defaults->save();
514         }
515         if( strlen(env_lang) > 1 &&
516             ( env_lang[2] == 0 || env_lang[2] == '_'  || env_lang[2] == '.' ) ) {
517                 cin_lang[0] = env_lang[0];  cin_lang[1] = env_lang[1];  cin_lang[2] = 0;
518         }
519         else
520                 strcpy(cin_lang, "en");
521 }
522
523 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
524 {
525         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
526         if( plug_dir ) {
527                 const char *dp = plug_dir;
528                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
529                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
530         }
531         strcpy(path, bp);
532         delete [] base_path;
533 }
534
535 int MWindow::load_plugin_index(MWindow *mwindow, FILE *fp, const char *plugin_dir)
536 {
537         if( !fp ) return -1;
538 // load index
539         fseek(fp, 0, SEEK_SET);
540         int ret = 0;
541         char index_line[BCTEXTLEN];
542         int index_version = -1, len = strlen(plugin_dir);
543         if( !fgets(index_line, BCTEXTLEN, fp) ||
544             sscanf(index_line, "%d", &index_version) != 1 ||
545             index_version != PLUGIN_FILE_VERSION ||
546             !fgets(index_line, BCTEXTLEN, fp) ||
547             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
548             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
549
550         ArrayList<PluginServer*> plugins;
551         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
552                 if( index_line[0] == ';' ) continue;
553                 if( index_line[0] == '#' ) continue;
554                 int type = PLUGIN_TYPE_UNKNOWN;
555                 char path[BCTEXTLEN], title[BCTEXTLEN];
556                 int64_t mtime = 0;
557                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
558                         ret = 1; continue;
559                 }
560                 PluginServer *server = 0;
561                 switch( type ) {
562                 case PLUGIN_TYPE_BUILTIN:
563                 case PLUGIN_TYPE_EXECUTABLE:
564                 case PLUGIN_TYPE_LADSPA: {
565                         char plugin_path[BCTEXTLEN];  struct stat st;
566                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
567                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
568                                 ret = 1; continue;
569                         }
570                         server = new PluginServer(mwindow, plugin_path, type);
571                         break; }
572                 case PLUGIN_TYPE_FFMPEG: {
573                         server = new_ffmpeg_server(mwindow, path);
574                         break; }
575                 case PLUGIN_TYPE_LV2: {
576                         server = new_lv2_server(mwindow, path);
577                         break; }
578                 }
579                 if( !server ) continue;
580                 plugins.append(server);
581 // Create plugin server from index entry
582                 server->set_title(title);
583                 if( server->read_table(index_line) ) {
584                         ret = 1;  continue;
585                 }
586         }
587
588         if( !ret )
589                 ret = check_plugin_index(plugins, plugin_dir, ".");
590
591         if( !ret )
592                 add_plugins(plugins);
593         else
594                 plugins.remove_all_objects();
595
596         return ret;
597 }
598
599 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
600         const char *plug_dir, const char *plug_path)
601 {
602         char plugin_path[BCTEXTLEN];
603         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
604         FileSystem fs;
605         fs.set_filter( "[*.plugin][*.so]" );
606         if( fs.update(plugin_path) )
607                 return 1;
608
609         for( int i=0; i<fs.dir_list.total; ++i ) {
610                 char fs_path[BCTEXTLEN];
611                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
612                 if( fs.is_dir(fs_path) ) {
613                         get_plugin_path(plugin_path, plug_dir, fs_path);
614                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
615                                 return 1;
616                 }
617                 else if( !plugin_exists(fs_path, plugins) )
618                         return 1;
619         }
620         return 0;
621 }
622
623
624 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
625 {
626         if( !plugindb )
627                 plugindb = new ArrayList<PluginServer*>;
628         init_ffmpeg();
629         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
630         create_defaults_path(index_path, PLUGIN_FILE);
631         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
632         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
633         FILE *fp = fopen(index_path,"a+");
634         if( !fp ) {
635                 fprintf(stderr,_("MWindow::init_plugins: "
636                         "can't open plugin index: %s\n"), index_path);
637                 return -1;
638         }
639         int fd = fileno(fp), ret = -1;
640         if( !flock(fd, LOCK_EX) ) {
641                 fseek(fp, 0, SEEK_SET);
642                 ret = load_plugin_index(mwindow, fp, plugin_path);
643         }
644         if( ret > 0 ) {
645                 ftruncate(fd, 0);
646                 fseek(fp, 0, SEEK_SET);
647                 printf("init plugin index: %s\n", plugin_path);
648                 fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
649                 fprintf(fp, "%s\n", plugin_path);
650                 init_plugin_index(mwindow, preferences, fp, plugin_path);
651                 init_ffmpeg_index(mwindow, preferences, fp);
652                 init_lv2_index(mwindow, preferences, fp);
653                 fseek(fp, 0, SEEK_SET);
654                 ret = load_plugin_index(mwindow, fp, plugin_path);
655         }
656         if( ret ) {
657                 fprintf(stderr,_("MWindow::init_plugins: "
658                         "can't %s plugin index: %s\n"),
659                         ret>0 ? _("create") : _("lock"), index_path);
660         }
661         fclose(fp);
662         return ret;
663 }
664
665 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
666 {
667         char *path = getenv("LADSPA_PATH");
668         char ladspa_path[BCTEXTLEN];
669         if( !path ) {
670                 strncpy(ladspa_path, File::get_ladspa_path(), sizeof(ladspa_path));
671                 path = ladspa_path;
672         }
673         for( int len=0; *path; path+=len ) {
674                 char *cp = strchr(path,':');
675                 len = !cp ? strlen(path) : cp-path;
676                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
677                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
678                 if( cp ) ++len;
679                 char *plugin_dir = FileSystem::basepath(plugin_path);
680                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
681                 create_defaults_path(index_path, LADSPA_FILE);
682                 cp = index_path + strlen(index_path);
683                 for( char *bp=plugin_path; *bp!=0; ++bp )
684                         *cp++ = *bp=='/' ? '_' : *bp;
685                 *cp = 0;
686                 FILE *fp = fopen(index_path,"a+");
687                 if( !fp ) {
688                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
689                                 "can't open ladspa plugin index: %s\n"), index_path);
690                         continue;
691                 }
692                 int fd = fileno(fp), ret = -1;
693                 if( !flock(fd, LOCK_EX) ) {
694                         fseek(fp, 0, SEEK_SET);
695                         ret = load_plugin_index(mwindow, fp, plugin_path);
696                 }
697                 if( ret > 0 ) {
698                         ftruncate(fd, 0);
699                         fseek(fp, 0, SEEK_SET);
700                         init_ladspa_index(mwindow, preferences, fp, plugin_path);
701                         fseek(fp, 0, SEEK_SET);
702                         ret = load_plugin_index(mwindow, fp, plugin_path);
703                 }
704                 if( ret ) {
705                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
706                                 "can't %s ladspa plugin index: %s\n"),
707                                 ret>0 ? _("create") : _("lock"), index_path);
708                 }
709                 fclose(fp);
710         }
711         return 1;
712 }
713
714 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
715         FILE *fp, const char *plugin_dir)
716 {
717         int idx = PLUGIN_IDS;
718         if( plugindb ) {
719                 for( int i=0; i<plugindb->size(); ++i ) {
720                         PluginServer *server = plugindb->get(i);
721                         if( server->dir_idx >= idx )
722                                 idx = server->dir_idx+1;
723                 }
724         }
725         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
726 }
727
728 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
729         const char *plug_dir, const char *plug_path, int &idx)
730 {
731         char plugin_path[BCTEXTLEN];
732         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
733         FileSystem fs;
734         fs.set_filter( "[*.plugin][*.so]" );
735         int result = fs.update(plugin_path);
736         if( result || !fs.dir_list.total ) return;
737         int vis_id = idx++;
738
739         for( int i=0; i<fs.dir_list.total; ++i ) {
740                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
741                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
742                 get_plugin_path(path, plug_dir, fs_path);
743                 if( fs.is_dir(fs_path) ) {
744                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
745                         continue;
746                 }
747                 if( plugin_exists(path) ) continue;
748                 struct stat st;
749                 if( stat(fs_path, &st) ) continue;
750                 int64_t mtime = st.st_mtime;
751                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
752                 result = server.open_plugin(1, preferences, 0, 0);
753                 if( !result ) {
754                         server.write_table(fp, path, vis_id, mtime);
755                         server.close_plugin();
756                 }
757                 else if( result == PLUGINSERVER_IS_LAD ) {
758                         int lad_index = 0;
759                         for(;;) {
760                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
761                                 ladspa.set_lad_index(lad_index++);
762                                 result = ladspa.open_plugin(1, preferences, 0, 0);
763                                 if( result ) break;
764                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
765                                 ladspa.close_plugin();
766                         }
767                 }
768         }
769 }
770
771 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
772 {
773         for( int i=0; i<plugins.size(); ++i )
774                 plugindb->append(plugins[i]);
775         plugins.remove_all();
776 }
777
778 void MWindow::init_plugin_tips(ArrayList<PluginServer*> &plugins, const char *lang)
779 {
780         const char *dat_path = File::get_cindat_path();
781         char msg_path[BCTEXTLEN];
782         FILE *fp = 0;
783         if( BC_Resources::language[0] ) {
784                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.%s",
785                         dat_path, lang);
786                 fp = fopen(msg_path, "r");
787         }
788         if( !fp ) {
789                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.txt",
790                         dat_path);
791                 fp = fopen(msg_path, "r");
792         }
793         if( !fp ) return;
794         char text[BCTEXTLEN];
795         char *tp = text, *ep = tp + sizeof(text)-1;
796         char title[BCTEXTLEN];
797         title[0] = 0;
798         int no = 0;
799         for(;;) {
800                 ++no;  int done = 1;
801                 char line[BCTEXTLEN], *cp = line;
802                 if( fgets(line,sizeof(line)-1,fp) ) {
803                         if( *cp == '#' ) continue;
804                         done = *cp == ' ' || *cp == '\t' ? 0 : -1;
805                 }
806                 if( done ) {
807                         if( tp > text && *--tp == '\n' ) *tp = 0;
808                         if( title[0] ) {
809                                 int idx = plugins.size();
810                                 while( --idx>=0 && strcmp(plugins[idx]->title, title) );
811                                 if( idx >= 0 ) {
812                                         delete [] plugins[idx]->tip;
813                                         plugins[idx]->tip = cstrdup(text);
814                                 }
815                                 title[0] = 0;
816                         }
817                         if( done > 0 ) break;
818                         tp = text;  *tp = 0;
819                         char *dp = strchr(cp, ':');
820                         if( !dp ) {
821                                 printf("plugin tips: error on line %d\n", no);
822                                 continue;
823                         }
824                         char *bp = title;
825                         while( cp < dp ) *bp++ = *cp++;
826                         *bp = 0;
827                         ++cp;
828                 }
829
830                 while( *cp == ' ' || *cp == '\t' ) ++cp;
831                 for( ; tp<ep && (*tp=*cp)!=0; ++tp,++cp );
832         }
833         fclose(fp);
834 }
835
836 void MWindow::delete_plugins()
837 {
838         plugindb->remove_all_objects();
839         delete plugindb;
840         plugindb = 0;
841 }
842
843 void MWindow::search_plugindb(int do_audio,
844                 int do_video,
845                 int is_realtime,
846                 int is_transition,
847                 int is_theme,
848                 ArrayList<PluginServer*> &results)
849 {
850 // Get plugins
851         for(int i = 0; i < MWindow::plugindb->total; i++)
852         {
853                 PluginServer *current = MWindow::plugindb->get(i);
854
855                 if(current->audio == do_audio &&
856                         current->video == do_video &&
857                         (current->realtime == is_realtime || is_realtime < 0) &&
858                         current->transition == is_transition &&
859                         current->theme == is_theme)
860                         results.append(current);
861         }
862
863 // Alphabetize list by title
864         int done = 0;
865         while(!done)
866         {
867                 done = 1;
868
869                 for(int i = 0; i < results.total - 1; i++)
870                 {
871                         PluginServer *value1 = results[i];
872                         PluginServer *value2 = results[i + 1];
873                         if(strcmp(_(value1->title), _(value2->title)) > 0)
874                         {
875                                 done = 0;
876                                 results[i] = value2;
877                                 results[i + 1] = value1;
878                         }
879                 }
880         }
881 }
882
883 PluginServer* MWindow::scan_plugindb(char *title,
884                 int data_type)
885 {
886 //      if(data_type < 0)
887 //      {
888 //              printf("MWindow::scan_plugindb data_type < 0\n");
889 //              return 0;
890 //      }
891
892         for(int i = 0; i < plugindb->total; i++)
893         {
894                 PluginServer *server = plugindb->get(i);
895                 if(server->title &&
896                         !strcasecmp(server->title, title) &&
897                         (data_type < 0 ||
898                                 (data_type == TRACK_AUDIO && server->audio) ||
899                                 (data_type == TRACK_VIDEO && server->video)))
900                         return plugindb->get(i);
901         }
902         return 0;
903 }
904
905 // repair session files with xlated plugin titles
906 void MWindow::fix_plugin_title(char *title)
907 {
908         for(int i = 0; i < plugindb->total; i++) {
909                 PluginServer *server = plugindb->get(i);
910                 if( !server->title ) continue;
911                 const char *server_title = server->title;
912                 if( !bstrcasecmp(title, _(server_title)) ) {
913                         strcpy(title, server_title);
914                         return;
915                 }
916         }
917 }
918
919 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
920 {
921         for( int i=0; i<plugins.size(); ++i )
922                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
923         return 0;
924 }
925
926 int MWindow::plugin_exists(char *plugin_path)
927 {
928         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
929 }
930
931 void MWindow::remove_plugin_index()
932 {
933         char index_path[BCTEXTLEN];
934         MWindow::create_defaults_path(index_path, PLUGIN_FILE);
935         ::remove(index_path);
936 }
937
938 void MWindow::init_preferences()
939 {
940         preferences = new Preferences;
941         preferences->load_defaults(defaults);
942         const char *lv2_path = getenv("LV2_PATH");
943         if( lv2_path && strcmp(lv2_path, preferences->lv2_path) ) {
944                 strncpy(preferences->lv2_path, lv2_path, sizeof(preferences->lv2_path));
945                 remove_plugin_index();
946         }
947         else if( !lv2_path && preferences->lv2_path[0] ) {
948                 File::setenv_path("LV2_PATH",preferences->lv2_path, 0);
949         }
950         session = new MainSession(this);
951         session->load_defaults(defaults);
952         // set x11_host, screens, window_config
953         screens = session->set_default_x11_host();
954         BC_Signals::set_trap_hook(trap_hook, this);
955         BC_Signals::set_catch_segv(preferences->trap_sigsegv);
956         BC_Signals::set_catch_intr(preferences->trap_sigintr);
957         if( preferences->trap_sigsegv || preferences->trap_sigintr ) {
958                 BC_Trace::enable_locks();
959         }
960         else {
961                 BC_Trace::disable_locks();
962         }
963         BC_WindowBase::get_resources()->popupmenu_btnup = preferences->popupmenu_btnup;
964         BC_WindowBase::get_resources()->textbox_focus_policy = preferences->textbox_focus_policy;
965         BC_WindowBase::get_resources()->grab_input_focus = preferences->grab_input_focus;
966         YUV::yuv.yuv_set_colors(preferences->yuv_color_space, preferences->yuv_color_range);
967 }
968
969 void MWindow::clean_indexes()
970 {
971         FileSystem fs;
972         int total_excess;
973         long oldest = 0;
974         int oldest_item = -1;
975         int result;
976         char string[BCTEXTLEN];
977         char string2[BCTEXTLEN];
978
979 // Delete extra indexes
980         fs.set_filter("*.idx");
981         fs.complete_path(preferences->index_directory);
982         fs.update(preferences->index_directory);
983 //printf("MWindow::clean_indexes 1 %d\n", fs.dir_list.total);
984
985 // Eliminate directories
986         result = 1;
987         while(result)
988         {
989                 result = 0;
990                 for(int i = 0; i < fs.dir_list.total && !result; i++)
991                 {
992                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
993                         if(fs.is_dir(string))
994                         {
995                                 delete fs.dir_list[i];
996                                 fs.dir_list.remove_number(i);
997                                 result = 1;
998                         }
999                 }
1000         }
1001         total_excess = fs.dir_list.total - preferences->index_count;
1002
1003 //printf("MWindow::clean_indexes 2 %d\n", fs.dir_list.total);
1004         while(total_excess > 0)
1005         {
1006 // Get oldest
1007                 for(int i = 0; i < fs.dir_list.total; i++)
1008                 {
1009                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
1010
1011                         if(i == 0 || fs.get_date(string) <= oldest)
1012                         {
1013                                 oldest = fs.get_date(string);
1014                                 oldest_item = i;
1015                         }
1016                 }
1017
1018                 if(oldest_item >= 0)
1019                 {
1020 // Remove index file
1021                         fs.join_names(string,
1022                                 preferences->index_directory,
1023                                 fs.dir_list[oldest_item]->name);
1024 //printf("MWindow::clean_indexes 1 %s\n", string);
1025                         if(remove(string))
1026                                 perror("delete_indexes");
1027                         delete fs.dir_list[oldest_item];
1028                         fs.dir_list.remove_number(oldest_item);
1029
1030 // Remove table of contents if it exists
1031                         strcpy(string2, string);
1032                         char *ptr = strrchr(string2, '.');
1033                         if(ptr)
1034                         {
1035 //printf("MWindow::clean_indexes 2 %s\n", string2);
1036                                 sprintf(ptr, ".toc");
1037                                 remove(string2);
1038                                 sprintf(ptr, ".mkr");
1039                                 remove(string2);
1040                         }
1041                 }
1042
1043                 total_excess--;
1044         }
1045 }
1046
1047 void MWindow::init_awindow()
1048 {
1049         awindow = new AWindow(this);
1050         awindow->create_objects();
1051 }
1052
1053 void MWindow::init_gwindow()
1054 {
1055         gwindow = new GWindow(this);
1056         gwindow->create_objects();
1057 }
1058
1059 void MWindow::init_tipwindow()
1060 {
1061         TipWindow::load_tips(cin_lang);
1062         if( !twindow )
1063                 twindow = new TipWindow(this);
1064         twindow->start();
1065 }
1066
1067 void MWindow::show_warning(int *do_warning, const char *text)
1068 {
1069         if( do_warning && !*do_warning ) return;
1070         if( !wwindow )
1071                 wwindow = new WWindow(this);
1072         wwindow->show_warning(do_warning, text);
1073 }
1074
1075 int MWindow::wait_warning()
1076 {
1077         return wwindow->wait_result();
1078 }
1079
1080 void MWindow::init_theme()
1081 {
1082         Timer timer;
1083         theme = 0;
1084
1085         PluginServer *theme_plugin = 0;
1086         for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1087                 if( plugindb->get(i)->theme &&
1088                     !strcasecmp(preferences->theme, plugindb->get(i)->title) )
1089                         theme_plugin = plugindb->get(i);
1090         }
1091
1092         if( !theme_plugin )
1093                 fprintf(stderr, _("MWindow::init_theme: prefered theme %s not found.\n"),
1094                          preferences->theme);
1095
1096         const char *default_theme = DEFAULT_THEME;
1097         if( !theme_plugin && strcasecmp(preferences->theme, default_theme) ) {
1098                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
1099                         default_theme);
1100                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1101                         if( plugindb->get(i)->theme &&
1102                             !strcasecmp(default_theme, plugindb->get(i)->title) )
1103                                 theme_plugin = plugindb->get(i);
1104                 }
1105         }
1106
1107         if(!theme_plugin) {
1108                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
1109                 exit(1);
1110         }
1111
1112         PluginServer *plugin = new PluginServer(*theme_plugin);
1113         if( plugin->open_plugin(0, preferences, 0, 0) ) {
1114                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
1115                         theme_plugin->title);
1116                 exit(1);
1117         }
1118
1119         theme = plugin->new_theme();
1120         theme->mwindow = this;
1121         strcpy(theme->path, plugin->path);
1122         delete plugin;
1123
1124 // Load default images & settings
1125         theme->Theme::initialize();
1126 // Load user images & settings
1127         theme->initialize();
1128 // Create menus with user colors
1129         theme->build_menus();
1130         init_menus();
1131
1132         theme->sort_image_sets();
1133         theme->check_used();
1134 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1135 }
1136
1137 void MWindow::init_3d()
1138 {
1139         playback_3d = new Playback3D(this);
1140         playback_3d->create_objects();
1141 }
1142
1143 void MWindow::init_edl()
1144 {
1145         edl = new EDL;
1146         edl->create_objects();
1147         fill_preset_defaults(default_standard, edl->session);
1148         edl->load_defaults(defaults);
1149         edl->session->brender_start = edl->session->brender_end = 0;
1150         edl->create_default_tracks();
1151         edl->tracks->update_y_pixels(theme);
1152 }
1153
1154 void MWindow::init_compositor()
1155 {
1156         cwindow = new CWindow(this);
1157         cwindow->create_objects();
1158 }
1159
1160 void MWindow::init_levelwindow()
1161 {
1162         lwindow = new LevelWindow(this);
1163         lwindow->create_objects();
1164 }
1165
1166 VWindow *MWindow::get_viewer(int start_it, int idx)
1167 {
1168         vwindows_lock->lock("MWindow::get_viewer");
1169         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
1170         if( !vwindow ) idx = vwindows.size();
1171         while( !vwindow && --idx >= 0 ) {
1172                 VWindow *vwin = vwindows[idx];
1173                 if( !vwin->is_running() || !vwin->get_edl() )
1174                         vwindow = vwin;
1175         }
1176         if( !vwindow ) {
1177                 vwindow = new VWindow(this);
1178                 vwindow->load_defaults();
1179                 vwindow->create_objects();
1180                 vwindows.append(vwindow);
1181         }
1182         vwindows_lock->unlock();
1183         if( start_it ) vwindow->start();
1184         return vwindow;
1185 }
1186
1187 ZWindow *MWindow::get_mixer(Mixer *&mixer)
1188 {
1189         zwindows_lock->lock("MWindow::get_mixer");
1190         if( !mixer ) mixer = edl->mixers.new_mixer();
1191         ZWindow *zwindow = 0;
1192         for( int i=0; !zwindow && i<zwindows.size(); ++i )
1193                 if( zwindows[i]->idx < 0 ) zwindow = zwindows[i];
1194         if( !zwindow )
1195                 zwindows.append(zwindow = new ZWindow(this));
1196         zwindow->idx = mixer->idx;
1197         zwindows_lock->unlock();
1198         return zwindow;
1199 }
1200
1201 void MWindow::del_mixer(ZWindow *zwindow)
1202 {
1203         zwindows_lock->lock("MWindow::del_mixer 0");
1204         edl->mixers.del_mixer(zwindow->idx);
1205         if( session->selected_zwindow >= 0 ) {
1206                 int i = zwindows.number_of(zwindow);
1207                 if( i >= 0 && i < session->selected_zwindow )
1208                         --session->selected_zwindow;
1209                 else if( i == session->selected_zwindow )
1210                         session->selected_zwindow = -1;
1211         }
1212         zwindows_lock->unlock();
1213         gui->lock_window("MWindow::del_mixer 1");
1214         gui->update_mixers(0, -1);
1215         gui->unlock_window();
1216 }
1217
1218 void MWindow::start_mixer()
1219 {
1220         Mixer *mixer = 0;
1221         ZWindow *zwindow = get_mixer(mixer);
1222         const char *title = 0;
1223
1224         for( Track *track=edl->tracks->first; track!=0; track=track->next ) {
1225                 PatchGUI *patchgui = get_patchgui(track);
1226                 if( !patchgui || !patchgui->mixer ) continue;
1227                 mixer->mixer_ids.append(track->get_mixer_id());
1228                 if( !title ) title = track->title;
1229         }
1230
1231         session->selected_zwindow = -1;
1232         gui->lock_window("MWindow::start_mixer");
1233         gui->update_mixers(0, 0);
1234         gui->unlock_window();
1235
1236         zwindow->set_title(title);
1237         zwindow->start();
1238         refresh_mixers();
1239 }
1240
1241 int MWindow::mixer_track_active(Track *track)
1242 {
1243         int i = session->selected_zwindow;
1244         if( i < 0 || i >= zwindows.size() ) return 0;
1245         ZWindow *zwindow = zwindows[i];
1246         Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1247         if( !mixer ) return 0;
1248         int n = mixer->mixer_ids.number_of(track->get_mixer_id());
1249         return n >= 0 ? 1 : 0;
1250 }
1251
1252 void MWindow::update_mixer_tracks()
1253 {
1254         zwindows_lock->lock("MixPatch::handle_event");
1255         int i = session->selected_zwindow;
1256         if( i >= 0 && i < zwindows.size() ) {
1257                 ZWindow *zwindow = zwindows[i];
1258                 zwindow->update_mixer_ids();
1259         }
1260         zwindows_lock->unlock();
1261 }
1262
1263 void MWindow::handle_mixers(EDL *edl, int command, int wait_tracking,
1264                 int use_inout, int toggle_audio, int loop_play, float speed)
1265 {
1266         zwindows_lock->lock("MWindow::handle_mixers");
1267         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1268                 ZWindow *zwindow = zwindows[vidx];
1269                 if( zwindow->idx < 0 ) continue;
1270                 Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1271                 if( !mixer || !mixer->mixer_ids.size() ) continue;
1272                 int k = -1;
1273                 for( Track *track = edl->tracks->first; k<0 && track!=0; track=track->next ) {
1274                         if( track->data_type != TRACK_VIDEO ) continue;
1275                         int mixer_id = track->get_mixer_id();
1276                         k = mixer->mixer_ids.size();
1277                         while( --k >= 0 && mixer_id != mixer->mixer_ids[k] );
1278                 }
1279                 if( k < 0 ) continue;
1280                 EDL *mixer_edl = new EDL(this->edl);
1281                 mixer_edl->create_objects();
1282                 mixer_edl->copy_all(edl);
1283                 mixer_edl->remove_vwindow_edls();
1284                 for( Track *track = mixer_edl->tracks->first; track!=0; track=track->next ) {
1285                         k = mixer->mixer_ids.size();
1286                         while( --k >= 0 && track->get_mixer_id() != mixer->mixer_ids[k] );
1287                         if( k >= 0 ) {
1288                                 track->record = 1;
1289                                 track->play = track->data_type == TRACK_VIDEO ? 1 : 0;
1290                         }
1291                         else
1292                                 track->record = track->play = 0;
1293                 }
1294                 zwindow->change_source(mixer_edl);
1295                 zwindow->handle_mixer(command, 0,
1296                                 use_inout, toggle_audio, loop_play, speed);
1297         }
1298         zwindows_lock->unlock();
1299 }
1300
1301 void MWindow::refresh_mixers(int dir)
1302 {
1303         int command = dir >= 0 ? CURRENT_FRAME : LAST_FRAME;
1304         handle_mixers(edl, command, 0, 0, 0, 0, 0);
1305 }
1306
1307 void MWindow::stop_mixers()
1308 {
1309         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1310                 ZWindow *zwindow = zwindows[vidx];
1311                 if( zwindow->idx < 0 ) continue;
1312                 zwindow->handle_mixer(STOP, 0, 0, 0, 0, 0);
1313         }
1314 }
1315
1316 void MWindow::close_mixers(int destroy)
1317 {
1318         ArrayList<ZWindow*> closed;
1319         zwindows_lock->lock("MWindow::close_mixers");
1320         for( int i=zwindows.size(); --i>=0; ) {
1321                 ZWindow *zwindow = zwindows[i];
1322                 if( zwindow->idx < 0 ) continue;
1323                 zwindow->destroy = destroy;
1324                 ZWindowGUI *zgui = zwindow->zgui;
1325                 zgui->lock_window("MWindow::select_zwindow 0");
1326                 zgui->set_done(0);
1327                 zgui->unlock_window();
1328                 closed.append(zwindow);
1329         }
1330         zwindows_lock->unlock();
1331         for( int i=0; i<closed.size(); ++i ) {
1332                 ZWindow *zwindow = closed[i];
1333                 zwindow->join();
1334         }
1335 }
1336
1337 ZWindow *MWindow::create_mixer(Indexable *indexable, double position)
1338 {
1339         ArrayList<Indexable*> new_assets;
1340         new_assets.append(indexable);
1341         Track *track = edl->tracks->last;
1342         load_assets(&new_assets, position, LOADMODE_NEW_TRACKS, 0, 0, 0, 0, 0, 0);
1343         track = !track ? edl->tracks->first : track->next;
1344         Mixer *mixer = 0;
1345         ZWindow *zwindow = get_mixer(mixer);
1346         while( track ) {
1347                 track->play = track->record = 0;
1348                 if( track->data_type == TRACK_VIDEO ) {
1349                         sprintf(track->title, _("Mixer %d"), zwindow->idx);
1350                 }
1351                 mixer->mixer_ids.append(track->get_mixer_id());
1352                 track = track->next;
1353         }
1354         if(  indexable->is_asset ) {
1355                 char *path = indexable->path;
1356                 char *tp = strrchr(path, '/');
1357                 if( !tp ) tp = path; else ++tp;
1358                 zwindow->set_title(tp);
1359         }
1360         else {
1361                 char *title = ((EDL*)indexable)->local_session->clip_title;
1362                 zwindow->set_title(title);
1363         }
1364         return zwindow;
1365 }
1366
1367 void MWindow::create_mixers(double position)
1368 {
1369         if( !session->drag_assets->size() &&
1370             !session->drag_clips->size() ) return;
1371         undo_before();
1372
1373         select_zwindow(0);
1374         ArrayList<ZWindow *>new_mixers;
1375
1376         for( int i=0; i<session->drag_assets->size(); ++i ) {
1377                 Indexable *indexable = session->drag_assets->get(i);
1378                 if( !indexable->have_video() ) continue;
1379                 ZWindow *zwindow = create_mixer(indexable, position);
1380                 new_mixers.append(zwindow);
1381         }
1382         for( int i=0; i<session->drag_clips->size(); ++i ) {
1383                 Indexable *indexable = (Indexable*)session->drag_clips->get(i);
1384                 if( !indexable->have_video() ) continue;
1385                 ZWindow *zwindow = create_mixer(indexable, position);
1386                 new_mixers.append(zwindow);
1387         }
1388
1389         tile_mixers();
1390         for( int i=0; i<new_mixers.size(); ++i )
1391                 new_mixers[i]->start();
1392
1393         refresh_mixers();
1394         save_backup();
1395         undo_after(_("create mixers"), LOAD_ALL);
1396         restart_brender();
1397         gui->update(1, FORCE_REDRAW, 1, 1, 1, 1, 0);
1398         sync_parameters(CHANGE_ALL);
1399 }
1400
1401 void MWindow::open_mixers()
1402 {
1403         for( int i=0; i<edl->mixers.size(); ++i ) {
1404                 Mixer *mixer = edl->mixers[i];
1405                 ZWindow *zwindow = get_mixer(mixer);
1406                 zwindow->set_title(mixer->title);
1407                 zwindow->start();
1408         }
1409         refresh_mixers();
1410 }
1411
1412 int MWindow::select_zwindow(ZWindow *zwindow)
1413 {
1414         int ret = 0, n = zwindows.number_of(zwindow);
1415         if( session->selected_zwindow != n ) {
1416                 session->selected_zwindow = n;
1417                 for( int i=0; i<zwindows.size(); ++i ) {
1418                         ZWindow *zwindow = zwindows[i];
1419                         if( zwindow->idx < 0 ) continue;
1420                         ZWindowGUI *zgui = zwindow->zgui;
1421                         zgui->lock_window("MWindow::select_zwindow 0");
1422                         zwindow->highlighted = i == n ? 1 : 0;
1423                         if( zgui->draw_overlays() )
1424                                 zgui->canvas->get_canvas()->flash(1);
1425                         zgui->unlock_window();
1426                 }
1427                 ret = 1;
1428                 gui->lock_window("MWindow::select_window 1");
1429                 gui->update_mixers(0, -1);
1430                 gui->unlock_window();
1431         }
1432         return ret;
1433 }
1434
1435 void MWindow::tile_mixers()
1436 {
1437         int nz = 0;
1438         for( int i=0; i<zwindows.size(); ++i ) {
1439                 ZWindow *zwindow = zwindows[i];
1440                 if( zwindow->idx < 0 ) continue;
1441                 ++nz;
1442         }
1443         if( !nz ) return;
1444         int zn = ceil(sqrt(nz));
1445         int x1 = 1 + gui->get_x(), x2 = cwindow->gui->get_x();
1446         int y1 = 1, y2 = gui->get_y();
1447         int rw = gui->get_root_w(0), rh = gui->get_root_h(0);
1448         if( x1 < 0 ) x1 = 0;
1449         if( y1 < 0 ) y1 = 0;
1450         if( x2 > rw ) x2 = rw;
1451         if( y2 > rh ) y2 = rh;
1452         int dx = x2 - x1, dy = y2 - y1;
1453         int zw = dx / zn;
1454         int lt = BC_DisplayInfo::get_left_border();
1455         int top = BC_DisplayInfo::get_top_border();
1456         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1457         int bh = top + BC_DisplayInfo::get_bottom_border();
1458         int zx = 0, zy = 0;  // window origins
1459         int mw = 10+10, mh = 10+10; // canvas margins
1460         int rsz = 0, n = 0, dz = 0;
1461         int ow = edl->session->output_w, oh = edl->session->output_h;
1462         for( int i=0; i<zwindows.size(); ++i ) {
1463                 ZWindow *zwindow = zwindows[i];
1464                 if( zwindow->idx < 0 ) continue;
1465                 int ww = zw - bw, hh = (ww - mw) * oh / ow + mh, zh = hh + bh;
1466                 if( rsz < hh ) rsz = hh;
1467                 int xx = zx + x1, yy = zy + y1;
1468                 int mx = x2 - zw, my = y2 - zh;
1469                 if( xx > mx ) xx = mx;
1470                 if( yy > my ) yy = my;
1471                 xx += lt + dz;  yy += top + dz;
1472                 zwindow->reposition(xx,yy, ww,hh);
1473                 if( zwindow->running() ) {
1474                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1475                         gui->lock_window("MWindow::tile_mixers");
1476                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1477                         gui->unlock_window();
1478                 }
1479                 if( ++n >= zn ) {
1480                         n = 0;  rsz += bh;
1481                         if( (zy += rsz) > (dy - rsz) ) dz += 10;
1482                         rsz = 0;
1483                         zx = 0;
1484                 }
1485                 else
1486                         zx += zw;
1487         }
1488 }
1489
1490 void MWindow::init_cache()
1491 {
1492         audio_cache = new CICache(preferences);
1493         video_cache = new CICache(preferences);
1494         frame_cache = new FrameCache;
1495         wave_cache = new WaveCache;
1496 }
1497
1498 void MWindow::init_channeldb()
1499 {
1500         channeldb_buz->load("channeldb_buz");
1501         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1502 }
1503
1504 void MWindow::init_menus()
1505 {
1506         char string[BCTEXTLEN];
1507
1508         // Color Models
1509         BC_CModels::to_text(string, BC_RGB888);
1510         colormodels.append(new ColormodelItem(string, BC_RGB888));
1511         BC_CModels::to_text(string, BC_RGBA8888);
1512         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1513 //      BC_CModels::to_text(string, BC_RGB161616);
1514 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1515 //      BC_CModels::to_text(string, BC_RGBA16161616);
1516 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1517         BC_CModels::to_text(string, BC_RGB_FLOAT);
1518         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1519         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1520         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1521         BC_CModels::to_text(string, BC_YUV888);
1522         colormodels.append(new ColormodelItem(string, BC_YUV888));
1523         BC_CModels::to_text(string, BC_YUVA8888);
1524         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1525 //      BC_CModels::to_text(string, BC_YUV161616);
1526 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1527 //      BC_CModels::to_text(string, BC_YUVA16161616);
1528 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1529
1530 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1531                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1532
1533 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1534                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1535
1536 #define ILACEFIXMETHODLISTADD(x) ilacefixmethod_to_text(string, x); \
1537                            interlace_asset_fixmethods.append(new InterlacefixmethodItem(string, x));
1538
1539         // Interlacing Modes
1540         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1541
1542         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1543         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1544
1545         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1546         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1547
1548         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1549         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1550
1551         // Interlacing Fixing Methods
1552         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_NONE);
1553         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_UPONE);
1554         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_DOWNONE);
1555
1556         mixers_align = new MixersAlign(this);
1557 }
1558
1559 void MWindow::init_indexes()
1560 {
1561         mainindexes = new MainIndexes(this);
1562         mainindexes->start_loop();
1563 }
1564
1565 void MWindow::init_gui()
1566 {
1567         gui = new MWindowGUI(this);
1568         gui->create_objects();
1569         gui->load_defaults(defaults);
1570 }
1571
1572 void MWindow::init_signals()
1573 {
1574         sighandler = new SigHandler;
1575         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1576 ENABLE_BUFFER
1577 }
1578
1579 void MWindow::init_render()
1580 {
1581         render = new Render(this);
1582         create_bd = new CreateBD_Thread(this);
1583         create_dvd = new CreateDVD_Thread(this);
1584         batch_render = new BatchRenderThread(this);
1585 }
1586
1587 void MWindow::init_exportedl()
1588 {
1589         exportedl = new ExportEDL(this);
1590 }
1591
1592 void MWindow::init_shuttle()
1593 {
1594 #ifdef HAVE_SHUTTLE
1595         int ret = Shuttle::probe();
1596         if( ret >= 0 ) {
1597                 shuttle = new Shuttle(this);
1598                 if( shuttle->read_config_file() > 0 ) {
1599                         printf("shuttle: bad config file\n");
1600                         delete shuttle;  shuttle = 0;
1601                         return;
1602                 }
1603                 shuttle->start(ret);
1604         }
1605 #endif
1606 }
1607
1608 void MWindow::init_brender()
1609 {
1610         if(preferences->use_brender && !brender)
1611         {
1612                 brender_lock->lock("MWindow::init_brender 1");
1613                 brender = new BRender(this);
1614                 brender->initialize();
1615                 session->brender_end = 0;
1616                 brender_lock->unlock();
1617         }
1618         else
1619         if(!preferences->use_brender && brender)
1620         {
1621                 brender_lock->lock("MWindow::init_brender 2");
1622                 delete brender;
1623                 brender = 0;
1624                 session->brender_end = 0;
1625                 brender_lock->unlock();
1626         }
1627         brender_active = 0;
1628         stop_brender();
1629 }
1630
1631 void MWindow::restart_brender()
1632 {
1633 //printf("MWindow::restart_brender 1\n");
1634         if( !brender_active || !preferences->use_brender ) return;
1635         if( !brender ) return;
1636         brender->restart(edl);
1637 }
1638
1639 void MWindow::stop_brender()
1640 {
1641         if( !brender ) return;
1642 // cannot be holding mwindow->gui display lock
1643         brender->stop();
1644 }
1645
1646 int MWindow::brender_available(int position)
1647 {
1648         int result = 0;
1649         brender_lock->lock("MWindow::brender_available 1");
1650         if(brender && brender_active)
1651         {
1652                 if(brender->map_valid)
1653                 {
1654                         brender->map_lock->lock("MWindow::brender_available 2");
1655                         if(position < brender->map_size &&
1656                                 position >= 0)
1657                         {
1658 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1659                                 if(brender->map[position] == BRender::RENDERED)
1660                                         result = 1;
1661                         }
1662                         brender->map_lock->unlock();
1663                 }
1664         }
1665         brender_lock->unlock();
1666         return result;
1667 }
1668
1669 void MWindow::set_brender_active(int v, int update)
1670 {
1671         if( !preferences->use_brender ) v = 0;
1672         brender_active = v;
1673         gui->mainmenu->brender_active->set_checked(v);
1674         if( v != 0 ) {
1675                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1676                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1677
1678                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1679                         edl->session->brender_end = edl->tracks->total_video_length();
1680                 }
1681                 restart_brender();
1682         }
1683         else {
1684                 edl->session->brender_start = edl->session->brender_end = 0;
1685                 gui->unlock_window();
1686                 stop_brender();
1687                 gui->lock_window("MWindow::set_brender_active");
1688         }
1689         if( update ) {
1690                 gui->update_timebar(0);
1691                 gui->draw_overlays(1);
1692         }
1693 }
1694
1695 int MWindow::has_commercials()
1696 {
1697 #ifdef HAVE_COMMERCIAL
1698         return theme->use_commercials;
1699 #else
1700         return 0;
1701 #endif
1702 }
1703
1704 void MWindow::init_commercials()
1705 {
1706 #ifdef HAVE_COMMERCIAL
1707         if( !commercials ) {
1708                 commercials = new Commercials(this);
1709                 commercial_active = 0;
1710         }
1711         else
1712                 commercials->add_user();
1713 #endif
1714 }
1715
1716 void MWindow::commit_commercial()
1717 {
1718 #ifdef HAVE_COMMERCIAL
1719         if( !commercial_active ) return;
1720         commercial_active = 0;
1721         if( !commercials ) return;
1722         commercials->commitDb();
1723 #endif
1724 }
1725
1726 void MWindow::undo_commercial()
1727 {
1728 #ifdef HAVE_COMMERCIAL
1729         if( !commercial_active ) return;
1730         commercial_active = 0;
1731         if( !commercials ) return;
1732         commercials->undoDb();
1733 #endif
1734 }
1735
1736 int MWindow::put_commercial()
1737 {
1738         int result = 0;
1739 #ifdef HAVE_COMMERCIAL
1740         double start = edl->local_session->get_selectionstart();
1741         double end = edl->local_session->get_selectionend();
1742         if( start >= end ) return 0;
1743
1744         const char *errmsg = 0;
1745         int count = 0;
1746         Tracks *tracks = edl->tracks;
1747         //check it
1748         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1749                 if( track->data_type != TRACK_VIDEO ) continue;
1750                 if( !track->record ) continue;
1751                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1752                 ++count;
1753                 int64_t units_start = track->to_units(start,0);
1754                 int64_t units_end = track->to_units(end,0);
1755                 Edits *edits = track->edits;
1756                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1757                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1758                 if(!edit1 && !edit2) continue;  // nothing selected
1759                 if(!edit2) {                    // edit2 beyond end of track
1760                         edit2 = edits->last;
1761                         units_end = edits->length();
1762                 }
1763                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1764                 Indexable *indexable = edit1->get_source();
1765                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1766         }
1767         //run it
1768         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1769                 if( track->data_type != TRACK_VIDEO ) continue;
1770                 if( !track->record ) continue;
1771                 int64_t units_start = track->to_units(start,0);
1772                 int64_t units_end = track->to_units(end,0);
1773                 Edits *edits = track->edits;
1774                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1775                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1776                 if(!edit1 && !edit2) continue;  // nothing selected
1777                 if(!edit2) {                    // edit2 beyond end of track
1778                         edit2 = edits->last;
1779                         units_end = edits->length();
1780                 }
1781                 Indexable *indexable = edit1->get_source();
1782                 Asset *asset = (Asset *)indexable;
1783                 File *file = video_cache->check_out(asset, edl);
1784                 if( !file ) { errmsg = _("no file"); break; }
1785                 int64_t edit_length = units_end - units_start;
1786                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1787                 result = commercials->put_clip(file, edit1->channel,
1788                         track->from_units(edit_start), track->from_units(edit_length));
1789                 video_cache->check_in(asset);
1790                 if( result ) { errmsg = _("db failed"); break; }
1791         }
1792         if( errmsg ) {
1793                 char string[BCTEXTLEN];
1794                 sprintf(string, _("put_commercial: %s"), errmsg);
1795                 MainError::show_error(string);
1796                 undo_commercial();
1797                 result = 1;
1798         }
1799 #endif
1800         return result;
1801 }
1802
1803 void MWindow::stop_playback(int wait)
1804 {
1805         gui->stop_drawing();
1806
1807         cwindow->stop_playback(wait);
1808
1809         for(int i = 0; i < vwindows.size(); i++) {
1810                 VWindow *vwindow = vwindows[i];
1811                 if( !vwindow->is_running() ) continue;
1812                 vwindow->stop_playback(wait);
1813         }
1814         for(int i = 0; i < zwindows.size(); i++) {
1815                 ZWindow *zwindow = zwindows[i];
1816                 if( zwindow->idx < 0 ) continue;
1817                 zwindow->stop_playback(wait);
1818         }
1819 }
1820
1821 void MWindow::stop_transport()
1822 {
1823         gui->stop_transport(gui->get_window_lock() ? "MWindow::stop_transport" : 0);
1824 }
1825
1826 void MWindow::undo_before(const char *description, void *creator)
1827 {
1828         undo->update_undo_before(description, creator);
1829 }
1830
1831 void MWindow::undo_after(const char *description, uint32_t load_flags, int changes_made)
1832 {
1833         undo->update_undo_after(description, load_flags, changes_made);
1834 }
1835
1836 void MWindow::beep(double freq, double secs, double gain)
1837 {
1838         if( !proxy_beep ) proxy_beep = new ProxyBeep(this);
1839         proxy_beep->tone(freq, secs, gain);
1840 }
1841
1842 int MWindow::load_filenames(ArrayList<char*> *filenames,
1843         int load_mode,
1844         int update_filename)
1845 {
1846         ArrayList<EDL*> new_edls;
1847         ArrayList<Asset*> new_assets;
1848         ArrayList<File*> new_files;
1849         const int debug = 0;
1850 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1851
1852 //      save_defaults();
1853         gui->start_hourglass();
1854
1855 // Need to stop playback since tracking depends on the EDL not getting
1856 // deleted.
1857         gui->unlock_window();
1858         stop_playback(1);
1859         gui->lock_window("MWindow::load_filenames 0");
1860
1861 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1862         undo_before();
1863
1864
1865 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1866
1867 // Define new_edls and new_assets to load
1868         int result = 0, ftype = -1;
1869
1870         for( int i=0; i<filenames->size(); ++i ) {
1871 // Get type of file
1872                 File *new_file = new File;
1873                 Asset *new_asset = new Asset(filenames->get(i));
1874                 EDL *new_edl = new EDL;
1875                 char string[BCTEXTLEN];
1876
1877                 new_edl->create_objects();
1878                 new_edl->copy_session(edl, -1);
1879                 new_file->set_program(edl->session->program_no);
1880
1881                 sprintf(string, _("Loading %s"), new_asset->path);
1882                 gui->show_message(string);
1883
1884                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1885
1886                 result = 1;
1887                 switch( ftype ) {
1888 // Convert media file to EDL
1889                 case FILE_OK:
1890 // Warn about odd image dimensions
1891                         if( new_asset->video_data &&
1892                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
1893                                 char string[BCTEXTLEN];
1894                                 sprintf(string, _("%s's resolution is %dx%d.\n"
1895                                         "Images with odd dimensions may not decode properly."),
1896                                         new_asset->path, new_asset->width, new_asset->height);
1897                                 MainError::show_error(string);
1898                         }
1899
1900                         if( new_asset->program >= 0 &&
1901                             edl->session->program_no != new_asset->program ) {
1902                                 char string[BCTEXTLEN];
1903                                 sprintf(string, _("%s's index was built for program number %d\n"
1904                                         "Playback preference is %d.\n  Using program %d."),
1905                                         new_asset->path, new_asset->program,
1906                                         edl->session->program_no, new_asset->program);
1907                                 MainError::show_error(string);
1908                         }
1909
1910                         if( load_mode != LOADMODE_RESOURCESONLY ) {
1911                                 RecordLabels *labels = edl->session->label_cells ?
1912                                         new RecordLabels(new_file) : 0;
1913                                 asset_to_edl(new_edl, new_asset, labels);
1914                                 new_edls.append(new_edl);
1915                                 new_edl->add_user();
1916                                 delete labels;
1917                         }
1918                         else {
1919                                 new_assets.append(new_asset);
1920                                 new_asset->add_user();
1921                         }
1922
1923 // Set filename to nothing for assets since save EDL would overwrite them.
1924                         if( load_mode == LOADMODE_REPLACE ||
1925                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
1926                                 set_filename("");
1927 // Reset timeline position
1928                                 for( int i=0; i<TOTAL_PANES; ++i ) {
1929                                         new_edl->local_session->view_start[i] = 0;
1930                                         new_edl->local_session->track_start[i] = 0;
1931                                 }
1932                         }
1933
1934                         result = 0;
1935                         break;
1936
1937 // File not found
1938                 case FILE_NOT_FOUND:
1939                         sprintf(string, _("Failed to open %s"), new_asset->path);
1940                         gui->show_message(string, theme->message_error);
1941                         gui->update_default_message();
1942                         break;
1943
1944 // Unknown format
1945                 case FILE_UNRECOGNIZED_CODEC: {
1946 // Test index file
1947                         { IndexFile indexfile(this, new_asset);
1948                         if( !(result = indexfile.open_index()) )
1949                                 indexfile.close_index(); }
1950
1951 // Test existing EDLs
1952                         for( int j=0; result && j<new_edls.total; ++j ) {
1953                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
1954                                 if( old_asset ) {
1955                                         new_asset->copy_from(old_asset,1);
1956                                         result = 0;
1957                                 }
1958                         }
1959                         if( result ) {
1960                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
1961                                 if( old_asset ) {
1962                                         new_asset->copy_from(old_asset,1);
1963                                         result = 0;
1964                                 }
1965                         }
1966
1967 // Prompt user
1968                         if( result ) {
1969                                 char string[BCTEXTLEN];
1970                                 FileSystem fs;
1971                                 fs.extract_name(string, new_asset->path);
1972
1973                                 strcat(string, _("'s format couldn't be determined."));
1974                                 new_asset->audio_data = 1;
1975                                 new_asset->format = FILE_PCM;
1976                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
1977                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
1978                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
1979                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
1980                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
1981                                 new_asset->header = defaults->get("HEADER", 0);
1982
1983                                 FileFormat fwindow(this);
1984                                 fwindow.create_objects(new_asset, string);
1985                                 result = fwindow.run_window();
1986
1987                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
1988                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
1989                                 defaults->update("AUDIO_BITS", new_asset->bits);
1990                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
1991                                 defaults->update("SIGNED_", new_asset->signed_);
1992                                 defaults->update("HEADER", new_asset->header);
1993                                 save_defaults();
1994                         }
1995
1996 // Append to list
1997                         if( !result ) {
1998 // Recalculate length
1999                                 delete new_file;
2000                                 new_file = new File;
2001                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2002
2003                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
2004                                         RecordLabels *labels = edl->session->label_cells ?
2005                                                 new RecordLabels(new_file) : 0;
2006                                         asset_to_edl(new_edl, new_asset, labels);
2007                                         new_edls.append(new_edl);
2008                                         new_edl->add_user();
2009                                         delete labels;
2010                                 }
2011                                 else {
2012                                         new_assets.append(new_asset);
2013                                         new_asset->add_user();
2014                                 }
2015                         }
2016                         else {
2017                                 result = 1;
2018                         }
2019                         break; }
2020
2021                 case FILE_IS_XML: {
2022                         FileXML xml_file;
2023                         xml_file.read_from_file(filenames->get(i));
2024                         const char *cin_version = 0;
2025                         while( !xml_file.read_tag() ) {
2026                                 if( xml_file.tag.title_is("EDL") ) {
2027                                         cin_version = xml_file.tag.get_property("VERSION");
2028                                         break;
2029                                 }
2030                         }
2031                         xml_file.rewind();
2032                         if( !cin_version ) {
2033                                 eprintf(_("XML file %s\n not from cinelerra."),filenames->get(i));
2034                                 char string[BCTEXTLEN];
2035                                 sprintf(string,_("Unknown %s"), filenames->get(i));
2036                                 gui->show_message(string);
2037                                 result = 1;
2038                                 break;
2039                         }
2040                         if( strcmp(cin_version, CINELERRA_VERSION) &&
2041                             strcmp(cin_version, "Unify") &&
2042                             strcmp(cin_version, "5.1") ) {
2043                                 char string[BCTEXTLEN];
2044                                 snprintf(string, sizeof(string),
2045                                          _("Warning: XML from cinelerra version %s\n"
2046                                         "Session data may be incompatible."), cin_version);
2047                                 show_warning(&preferences->warn_version, string);
2048                         }
2049                         if( load_mode == LOADMODE_NESTED ) {
2050 // Load temporary EDL for nesting.
2051                                 EDL *nested_edl = new EDL;
2052                                 nested_edl->create_objects();
2053                                 nested_edl->load_xml(&xml_file, LOAD_ALL);
2054                                 int groups = nested_edl->regroup(session->group_number);
2055                                 session->group_number += groups;
2056                                 new_edl->create_nested(nested_edl);
2057                                 new_edl->set_path(filenames->get(i));
2058                                 nested_edl->Garbage::remove_user();
2059                         }
2060                         else {
2061 // Load EDL for pasting
2062                                 new_edl->load_xml(&xml_file, LOAD_ALL);
2063                                 int groups = new_edl->regroup(session->group_number);
2064                                 session->group_number += groups;
2065                                 test_plugins(new_edl, filenames->get(i));
2066
2067                                 if( load_mode == LOADMODE_REPLACE ||
2068                                     load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2069                                         strcpy(session->filename, filenames->get(i));
2070                                         strcpy(new_edl->local_session->clip_title,
2071                                                 filenames->get(i));
2072                                         if(update_filename)
2073                                                 set_filename(new_edl->local_session->clip_title);
2074                                 }
2075                                 else if( load_mode == LOADMODE_RESOURCESONLY ) {
2076                                         strcpy(new_edl->local_session->clip_title,
2077                                                 filenames->get(i));
2078                                         struct stat st;
2079                                         time_t t = !stat(filenames->get(i),&st) ?
2080                                                 st.st_mtime : time(&t);
2081                                         ctime_r(&t, new_edl->local_session->clip_notes);
2082                                 }
2083                         }
2084
2085                         new_edls.append(new_edl);
2086                         new_edl->add_user();
2087                         result = 0;
2088                         break; }
2089                 }
2090
2091                 new_edl->Garbage::remove_user();
2092                 new_asset->Garbage::remove_user();
2093
2094 // Store for testing index
2095                 new_files.append(new_file);
2096         }
2097
2098 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2099
2100
2101         if(!result) {
2102                 gui->reset_default_message();
2103                 gui->default_message();
2104         }
2105
2106
2107 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2108
2109 // Paste them.
2110 // Don't back up here.
2111         if( new_edls.size() ) {
2112 // For pasting, clear the active region
2113                 if( load_mode == LOADMODE_PASTE ||
2114                     load_mode == LOADMODE_NESTED ) {
2115                         double start = edl->local_session->get_selectionstart();
2116                         double end = edl->local_session->get_selectionend();
2117                         if(!EQUIV(start, end))
2118                                 edl->clear(start, end,
2119                                         edl->session->labels_follow_edits,
2120                                         edl->session->plugins_follow_edits,
2121                                         edl->session->autos_follow_edits);
2122
2123                         paste_edls(&new_edls, load_mode, 0, -1,
2124                                 edl->session->labels_follow_edits,
2125                                 edl->session->plugins_follow_edits,
2126                                 edl->session->autos_follow_edits,
2127                                 0); // overwrite
2128                 }
2129                 else
2130                         paste_edls(&new_edls, load_mode, 0, -1, 1, 1, 1, 0);
2131         }
2132
2133 // Add new assets to EDL and schedule assets for index building.
2134         int got_indexes = 0;
2135         for( int i=0; i<new_edls.size(); ++i ) {
2136                 EDL *new_edl = new_edls[i];
2137                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2138                         mainindexes->add_next_asset(0, new_edl->nested_edls[j]);
2139                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2140                         got_indexes = 1;
2141                 }
2142
2143         }
2144
2145         for( int i=0; i<new_assets.size(); ++i ) {
2146                 Asset *new_asset = new_assets[i];
2147
2148                 File *new_file = 0;
2149                 int got_it = 0;
2150                 for( int j=0; j<new_files.size(); ++j ) {
2151                         new_file = new_files[j];
2152                         if( !strcmp(new_file->asset->path, new_asset->path) ) {
2153                                 got_it = 1;
2154                                 break;
2155                         }
2156                 }
2157
2158                 mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
2159                 edl->assets->update(new_asset);
2160                 got_indexes = 1;
2161         }
2162
2163 // Start examining next batch of index files
2164         if(got_indexes) mainindexes->start_build();
2165
2166 // Open plugin GUIs
2167         Track *track = edl->tracks->first;
2168         while( track ) {
2169                 for( int j = 0; j < track->plugin_set.size(); j++ ) {
2170                         PluginSet *plugins = track->plugin_set[j];
2171                         Plugin *plugin = plugins->get_first_plugin();
2172
2173                         while(plugin) {
2174                                 if( load_mode == LOADMODE_REPLACE ||
2175                                     load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2176                                         if( plugin->plugin_type == PLUGIN_STANDALONE &&
2177                                             plugin->show ) {
2178                                                 show_plugin(plugin);
2179                                         }
2180                                 }
2181
2182                                 plugin = (Plugin*)plugin->next;
2183                         }
2184                 }
2185
2186                 track = track->next;
2187         }
2188
2189         // if just opening one new resource in replace mode
2190         if( ftype != FILE_IS_XML &&
2191             ( load_mode == LOADMODE_REPLACE ||
2192               load_mode == LOADMODE_REPLACE_CONCATENATE ) ) {
2193                 select_asset(0, 0);
2194                 edl->session->proxy_scale = 1;
2195                 edl->session->proxy_disabled_scale = 1;
2196                 edl->session->proxy_use_scaler = 0;
2197                 edl->session->proxy_auto_scale = 0;
2198                 edl->session->proxy_beep = 0;
2199                 edl->local_session->preview_start = 0;
2200                 edl->local_session->preview_end = -1;
2201                 edl->local_session->loop_playback = 0;
2202                 edl->local_session->set_selectionstart(0);
2203                 edl->local_session->set_selectionend(0);
2204                 set_brender_active(0, 0);
2205                 fit_selection();
2206                 goto_start();
2207         }
2208
2209         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
2210             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
2211                 ArrayList<Indexable *> orig_idxbls;
2212                 for( int i=0; i<new_assets.size(); ++i )
2213                         orig_idxbls.append(new_assets.get(i));
2214                 for( int i=0; i<new_edls.size(); ++i ) {
2215                         EDL *new_edl = new_edls[i];
2216                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2217                                 if( track->data_type != TRACK_VIDEO ) continue;
2218                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2219                                         Indexable *idxbl = (Indexable *)edit->asset;
2220                                         if( !idxbl ) continue;
2221                                         if( !idxbl->have_video() ) continue;
2222                                         if( edit->channel != 0 ) continue; // first layer only
2223                                         orig_idxbls.append(edit->asset);
2224                                 }
2225                         }
2226                 }
2227                 gui->unlock_window(); // to update progress bar
2228                 int ret = render_proxy(orig_idxbls);
2229                 gui->lock_window("MWindow::load_filenames");
2230                 if( ret >= 0 && edl->session->proxy_beep ) {
2231                         if( ret > 0 )
2232                                 beep(2000., 1.5, 0.5);
2233                         else
2234                                 beep(4000., 0.25, 0.5);
2235                 }
2236         }
2237
2238 // need to update undo before project, since mwindow is unlocked & a new load
2239 // can begin here.  Should really prevent loading until we're done.
2240 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2241         undo_after(_("load"), LOAD_ALL);
2242
2243         for(int i = 0; i < new_edls.size(); i++)
2244         {
2245                 new_edls[i]->remove_user();
2246         }
2247 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2248
2249         new_edls.remove_all();
2250
2251         for(int i = 0; i < new_assets.size(); i++)
2252         {
2253                 new_assets[i]->Garbage::remove_user();
2254         }
2255
2256         new_assets.remove_all();
2257         new_files.remove_all_objects();
2258
2259
2260 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2261         if(load_mode == LOADMODE_REPLACE ||
2262                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2263         {
2264                 session->changes_made = 0;
2265         }
2266         else
2267         {
2268                 session->changes_made = 1;
2269         }
2270
2271         gui->stop_hourglass();
2272
2273
2274 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2275         update_project(load_mode);
2276
2277 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2278
2279         return 0;
2280 }
2281
2282 int MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2283 {
2284         Asset *format_asset = new Asset;
2285         format_asset->format = FILE_FFMPEG;
2286         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2287         ProxyRender proxy_render(this, format_asset);
2288         int new_scale = edl->session->proxy_scale;
2289         int use_scaler = edl->session->proxy_use_scaler;
2290
2291         for( int i=0; i<new_idxbls.size(); ++i ) {
2292                 Indexable *orig = new_idxbls.get(i);
2293                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2294                 if( !proxy ) continue;
2295                 FileSystem fs;
2296                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2297                 int got_it = exists && // if proxy exists, and is newer than orig
2298                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2299                 if( got_it ) continue;
2300                 proxy_render.add_needed(orig, proxy);
2301         }
2302
2303 // render needed proxies
2304         int result = proxy_render.create_needed_proxies(new_scale);
2305         if( !result ) {
2306                 add_proxy(use_scaler,
2307                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2308         }
2309         format_asset->remove_user();
2310         return !result ? proxy_render.needed_proxies.size() : -1;
2311 }
2312
2313 int MWindow::enable_proxy()
2314 {
2315         int ret = 0;
2316         if( edl->session->proxy_scale == 1 &&
2317             edl->session->proxy_disabled_scale != 1 ) {
2318                 int new_scale = edl->session->proxy_disabled_scale;
2319                 int new_use_scaler = edl->session->proxy_use_scaler;
2320                 edl->session->proxy_disabled_scale = 1;
2321                 Asset *asset = new Asset;
2322                 asset->format = FILE_FFMPEG;
2323                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2324                 ret = to_proxy(asset, new_scale, new_use_scaler);
2325                 asset->remove_user();
2326                 if( ret > 0 )
2327                         beep(2000., 1.5, 0.5);
2328         }
2329         return 1;
2330 }
2331
2332 int MWindow::disable_proxy()
2333 {
2334         if( edl->session->proxy_scale != 1 &&
2335             edl->session->proxy_disabled_scale == 1 ) {
2336                 int new_scale = 1;
2337                 int new_use_scaler = edl->session->proxy_use_scaler;
2338                 edl->session->proxy_disabled_scale = edl->session->proxy_scale;
2339                 Asset *asset = new Asset;
2340                 asset->format = FILE_FFMPEG;
2341                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2342                 to_proxy(asset, new_scale, new_use_scaler);
2343                 asset->remove_user();
2344         }
2345         return 1;
2346 }
2347
2348 int MWindow::to_proxy(Asset *asset, int new_scale, int new_use_scaler)
2349 {
2350         ArrayList<Indexable*> orig_idxbls;
2351         ArrayList<Indexable*> proxy_assets;
2352
2353         edl->Garbage::add_user();
2354         save_backup();
2355         undo_before(_("proxy"), this);
2356         ProxyRender proxy_render(this, asset);
2357
2358 // revert project to original size from current size
2359 // remove all session proxy assets at the at the current proxy_scale
2360         int proxy_scale = edl->session->proxy_scale;
2361
2362         if( proxy_scale > 1 ) {
2363                 Asset *orig_asset = edl->assets->first;
2364                 for( ; orig_asset; orig_asset=orig_asset->next ) {
2365                         char new_path[BCTEXTLEN];
2366                         proxy_render.to_proxy_path(new_path, orig_asset, proxy_scale);
2367 // test if proxy asset was already added to proxy_assets
2368                         int got_it = 0;
2369                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2370                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2371                         if( got_it ) continue;
2372                         Asset *proxy_asset = edl->assets->get_asset(new_path);
2373                         if( !proxy_asset ) continue;
2374 // add pointer to existing EDL asset if it exists
2375 // EDL won't delete it unless it's the same pointer.
2376                         proxy_assets.append(proxy_asset);
2377                         proxy_asset->add_user();
2378                         orig_idxbls.append(orig_asset);
2379                         orig_asset->add_user();
2380                 }
2381                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2382                         EDL *orig_nested = edl->nested_edls[i];
2383                         char new_path[BCTEXTLEN];
2384                         if( !ProxyRender::from_proxy_path(new_path, orig_nested, proxy_scale) )
2385                                 continue;
2386                         proxy_render.to_proxy_path(new_path, orig_nested, proxy_scale);
2387 // test if proxy asset was already added to proxy_assets
2388                         int got_it = 0;
2389                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2390                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2391                         if( got_it ) continue;
2392                         Asset *proxy_nested = edl->assets->get_asset(new_path);
2393                         if( !proxy_nested ) continue;
2394 // add pointer to existing EDL asset if it exists
2395 // EDL won't delete it unless it's the same pointer.
2396                         proxy_assets.append(proxy_nested);
2397                         proxy_nested->add_user();
2398                         orig_idxbls.append(orig_nested);
2399                         orig_nested->add_user();
2400                 }
2401
2402 // convert from the proxy assets to the original assets
2403                 edl->set_proxy(1, 0, &proxy_assets, &orig_idxbls);
2404
2405 // remove the references
2406                 for( int i=0; i<proxy_assets.size(); ++i ) {
2407                         Asset *proxy = (Asset *) proxy_assets[i];
2408                         proxy->width = proxy->actual_width;
2409                         proxy->height = proxy->actual_height;
2410                         proxy->remove_user();
2411                         edl->assets->remove_pointer(proxy);
2412                         proxy->remove_user();
2413                 }
2414                 proxy_assets.remove_all();
2415                 for( int i = 0; i < orig_idxbls.size(); i++ )
2416                         orig_idxbls[i]->remove_user();
2417                 orig_idxbls.remove_all();
2418         }
2419
2420         ArrayList<char *> confirm_paths;    // test for new files
2421         confirm_paths.set_array_delete();
2422
2423 // convert to new size if not original size
2424         if( new_scale != 1 ) {
2425                 FileSystem fs;
2426                 Asset *orig = edl->assets->first;
2427                 for( ; orig; orig=orig->next ) {
2428                         Asset *proxy = proxy_render.add_original(orig, new_scale);
2429                         if( !proxy ) continue;
2430                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2431                         int got_it = exists && // if proxy exists, and is newer than orig
2432                             fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2433                         if( !got_it ) {
2434                                 if( exists ) // prompt user to overwrite
2435                                         confirm_paths.append(cstrdup(proxy->path));
2436                                 proxy_render.add_needed(orig, proxy);
2437                         }
2438                 }
2439                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2440                         EDL *orig_nested = edl->nested_edls[i];
2441                         Asset *proxy = proxy_render.add_original(orig_nested, new_scale);
2442                         if( !proxy ) continue;
2443                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2444                         int got_it = exists && // if proxy exists, and is newer than orig_nested
2445                             fs.get_date(proxy->path) > fs.get_date(orig_nested->path) ? 1 : 0;
2446                         if( !got_it ) {
2447                                 if( exists ) // prompt user to overwrite
2448                                         confirm_paths.append(cstrdup(proxy->path));
2449                                 proxy_render.add_needed(orig_nested, proxy);
2450                         }
2451                 }
2452         }
2453
2454         int result = 0;
2455 // test for existing files
2456         if( confirm_paths.size() ) {
2457                 result = ConfirmSave::test_files(this, &confirm_paths);
2458                 confirm_paths.remove_all_objects();
2459         }
2460
2461         if( !result )
2462                 result = proxy_render.create_needed_proxies(new_scale);
2463
2464         if( !result ) // resize project
2465                 edl->set_proxy(new_scale, new_use_scaler,
2466                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2467
2468         undo_after(_("proxy"), LOAD_ALL);
2469         edl->Garbage::remove_user();
2470         restart_brender();
2471
2472         gui->lock_window("MWindow::to_proxy");
2473         update_project(LOADMODE_REPLACE);
2474         gui->unlock_window();
2475
2476         return !result ? proxy_render.needed_proxies.size() : -1;
2477 }
2478
2479 void MWindow::test_plugins(EDL *new_edl, char *path)
2480 {
2481         char string[BCTEXTLEN];
2482
2483 // Do a check whether plugins exist
2484         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2485                 for( int k=0; k<track->plugin_set.total; ++k ) {
2486                         PluginSet *plugin_set = track->plugin_set[k];
2487                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2488                                         plugin; plugin = (Plugin*)plugin->next ) {
2489                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2490 // ok we need to find it in plugindb
2491                                 PluginServer *server =
2492                                         scan_plugindb(plugin->title, track->data_type);
2493                                 if( !server || server->transition ) {
2494                                         sprintf(string,
2495         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2496           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2497                                                 "effect", _(plugin->title), path);
2498                                         MainError::show_error(string);
2499                                 }
2500                         }
2501                 }
2502
2503                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2504                         if( !edit->transition ) continue;
2505 // ok we need to find transition in plugindb
2506                         PluginServer *server =
2507                                 scan_plugindb(edit->transition->title, track->data_type);
2508                         if( !server || !server->transition ) {
2509                                 sprintf(string,
2510         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2511           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2512                                         "transition", _(edit->transition->title), path);
2513                                 MainError::show_error(string);
2514                         }
2515                 }
2516         }
2517 }
2518
2519
2520 void MWindow::init_shm(const char *pfn, int64_t min)
2521 {
2522         int64_t result = 0;
2523 // Fix shared memory
2524         FILE *fd = fopen(pfn, "r");
2525         if( fd ) {
2526                 fscanf(fd, "%jd", &result);
2527                 fclose(fd);
2528                 if( result >= min ) return;
2529         }
2530
2531         fd = fopen(pfn, "w");
2532         if( !fd ) return;
2533         fprintf(fd, "0x%jx", min);
2534         fclose(fd);
2535
2536         fd = fopen(pfn, "r");
2537         if( !fd ) {
2538                 eprintf(_("MWindow::init_shm: couldn't open %s for reading.\n"), pfn);
2539                 return;
2540         }
2541
2542         fscanf(fd, "%jd", &result);
2543         fclose(fd);
2544         if( result < min ) {
2545                 eprintf(_("MWindow::init_shm: %s is %p.\n"
2546                         "you probably need to be root, or:\n"
2547                         "as root, run: echo 0x%jx > %s\n"
2548                         "before trying to start cinelerra.\n"
2549                         "It should be at least 0x%jx for Cinelerra.\n"),
2550                         pfn, (void *)result, min, pfn, min);
2551         }
2552 }
2553
2554 void MWindow::create_objects(int want_gui,
2555         int want_new,
2556         char *config_path)
2557 {
2558         const int debug = 0;
2559         if(debug) PRINT_TRACE
2560
2561 // For some reason, init_signals must come after show_splash or the signals won't
2562 // get trapped.
2563         init_signals();
2564         if(debug) PRINT_TRACE
2565         init_3d();
2566
2567         if(debug) PRINT_TRACE
2568         show_splash();
2569
2570         if(debug) PRINT_TRACE
2571         default_standard = default_std();
2572         init_defaults(defaults, config_path);
2573         check_language();
2574         init_preferences();
2575         if(splash_window)
2576                 splash_window->update_status(_("Initializing Plugins"));
2577         init_plugins(this, preferences);
2578         if(debug) PRINT_TRACE
2579         init_ladspa_plugins(this, preferences);
2580         if(debug) PRINT_TRACE
2581         init_plugin_tips(*plugindb, cin_lang);
2582         if(splash_window)
2583                 splash_window->update_status(_("Initializing GUI"));
2584         if(debug) PRINT_TRACE
2585         init_theme();
2586
2587         if(debug) PRINT_TRACE
2588         init_error();
2589
2590         if(splash_window)
2591                 splash_window->update_status(_("Initializing Fonts"));
2592         char string[BCTEXTLEN];
2593         strcpy(string, preferences->plugin_dir);
2594         strcat(string, "/" FONT_SEARCHPATH);
2595         BC_Resources::init_fontconfig(string);
2596         if(debug) PRINT_TRACE
2597
2598 // Default project created here
2599         init_edl();
2600         if(debug) PRINT_TRACE
2601
2602         init_cache();
2603         if(debug) PRINT_TRACE
2604
2605         Timer timer;
2606
2607         init_awindow();
2608         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2609
2610         init_compositor();
2611         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2612
2613 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2614         if(session->show_vwindow)
2615                 get_viewer(1, DEFAULT_VWINDOW);
2616         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2617
2618         init_gui();
2619         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2620
2621         init_levelwindow();
2622         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2623
2624         init_indexes();
2625         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2626
2627         init_channeldb();
2628         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2629
2630         init_gwindow();
2631         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2632
2633         init_render();
2634         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2635
2636         init_shuttle();
2637         init_brender();
2638         init_exportedl();
2639         init_commercials();
2640         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2641         mainprogress = new MainProgress(this, gui);
2642         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2643         undo = new MainUndo(this);
2644
2645         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2646
2647         plugin_guis = new ArrayList<PluginServer*>;
2648         dead_plugins = new ArrayList<PluginServer*>;
2649         keyframe_threads = new ArrayList<KeyFrameThread*>;
2650
2651         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2652                 __LINE__,
2653                 vwindows.size(),
2654                 session->show_vwindow);
2655
2656 // Show all vwindows
2657 //      if(session->show_vwindow) {
2658 //              for(int j = 0; j < vwindows.size(); j++) {
2659 //                      VWindow *vwindow = vwindows[j];
2660 //                      if( !vwindow->is_running() ) continue;
2661 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2662 //                              __LINE__,
2663 //                              vwindow);
2664 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2665 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2666 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2667 //                      vwindow->gui->show_window();
2668 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2669 //                      vwindow->gui->unlock_window();
2670 //              }
2671 //      }
2672
2673
2674         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2675
2676         if(session->show_cwindow)
2677         {
2678                 cwindow->gui->lock_window("MWindow::create_objects 1");
2679                 cwindow->gui->show_window();
2680                 cwindow->gui->unlock_window();
2681         }
2682
2683         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2684         if(session->show_awindow)
2685         {
2686                 awindow->gui->lock_window("MWindow::create_objects 1");
2687                 awindow->gui->show_window();
2688                 awindow->gui->unlock_window();
2689         }
2690
2691         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2692         if(session->show_lwindow)
2693         {
2694                 lwindow->gui->lock_window("MWindow::create_objects 1");
2695                 lwindow->gui->show_window();
2696                 lwindow->gui->unlock_window();
2697         }
2698
2699         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2700                 __LINE__,
2701                 (int)timer.get_difference(),
2702                 gwindow->gui);
2703         if(session->show_gwindow)
2704         {
2705                 gwindow->gui->lock_window("MWindow::create_objects 1");
2706                 gwindow->gui->show_window();
2707                 gwindow->gui->unlock_window();
2708         }
2709
2710         if(debug) PRINT_TRACE
2711
2712         gui->lock_window("MWindow::create_objects 1");
2713         gui->mainmenu->load_defaults(defaults);
2714         gui->mainmenu->update_toggles(0);
2715         gui->update_patchbay();
2716         gui->draw_canvas(0, 0);
2717         gui->draw_cursor(1);
2718         gui->show_window();
2719         gui->raise_window();
2720         gui->unlock_window();
2721
2722         if(debug) PRINT_TRACE
2723
2724         if(preferences->use_tipwindow)
2725                 init_tipwindow();
2726         if(debug) PRINT_TRACE
2727
2728         gui->add_keyboard_listener(
2729                 (int (BC_WindowBase::*)(BC_WindowBase *))
2730                 &MWindowGUI::keyboard_listener);
2731
2732         hide_splash();
2733         init_shm("/proc/sys/kernel/shmmax", 0x7fffffff);
2734         init_shm("/proc/sys/kernel/shmmni", 0x4000);
2735         if(debug) PRINT_TRACE
2736
2737         BC_WindowBase::get_resources()->vframe_shm = 1;
2738 }
2739
2740
2741 void MWindow::show_splash()
2742 {
2743 #include "data/heroine_logo9_png.h"
2744         VFrame *frame = new VFramePng(heroine_logo9_png);
2745         BC_DisplayInfo dpyi;
2746         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2747         int rr = (rw < rh ? rw : rh) / 4;
2748         splash_window = new SplashGUI(frame, rr, rr);
2749         splash_window->create_objects();
2750 }
2751
2752 void MWindow::hide_splash()
2753 {
2754         if(splash_window)
2755                 delete splash_window;
2756         splash_window = 0;
2757 }
2758
2759
2760 void MWindow::start()
2761 {
2762 ENABLE_BUFFER
2763 //PRINT_TRACE
2764 //      vwindows[DEFAULT_VWINDOW]->start();
2765         awindow->start();
2766 //PRINT_TRACE
2767         cwindow->start();
2768 //PRINT_TRACE
2769         lwindow->start();
2770 //PRINT_TRACE
2771         gwindow->start();
2772 //PRINT_TRACE
2773 //      Thread::start();
2774 //PRINT_TRACE
2775         playback_3d->start();
2776 //PRINT_TRACE
2777 }
2778
2779 void MWindow::run()
2780 {
2781         run_lock->lock("MWindow::run");
2782         gui->run_window();
2783         stop_playback(1);
2784
2785         brender_lock->lock("MWindow::run 1");
2786         delete brender;         brender = 0;
2787         brender_lock->unlock();
2788
2789         interrupt_indexes();
2790         clean_indexes();
2791         save_defaults();
2792         run_lock->unlock();
2793 }
2794
2795 void MWindow::show_vwindow()
2796 {
2797         int total_running = 0;
2798         session->show_vwindow = 1;
2799
2800 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2801 // Raise all windows which are visible
2802         for(int j = 0; j < vwindows.size(); j++) {
2803                 VWindow *vwindow = vwindows[j];
2804                 if( !vwindow->is_running() ) continue;
2805                 vwindow->gui->lock_window("MWindow::show_vwindow");
2806                 vwindow->gui->show_window(0);
2807                 vwindow->gui->raise_window();
2808                 vwindow->gui->flush();
2809                 vwindow->gui->unlock_window();
2810                 total_running++;
2811         }
2812
2813 // If no windows visible
2814         if(!total_running)
2815         {
2816                 get_viewer(1, DEFAULT_VWINDOW);
2817         }
2818
2819         gui->mainmenu->show_vwindow->set_checked(1);
2820 }
2821
2822 void MWindow::show_awindow()
2823 {
2824         session->show_awindow = 1;
2825         awindow->gui->lock_window("MWindow::show_awindow");
2826         awindow->gui->show_window();
2827         awindow->gui->raise_window();
2828         awindow->gui->flush();
2829         awindow->gui->unlock_window();
2830         gui->mainmenu->show_awindow->set_checked(1);
2831 }
2832
2833 char *MWindow::get_cwindow_display()
2834 {
2835         char *x11_host = screens < 2 || session->window_config == 0 ?
2836                 session->a_x11_host : session->b_x11_host;
2837         return *x11_host ? x11_host : 0;
2838 }
2839
2840 void MWindow::show_cwindow()
2841 {
2842         session->show_cwindow = 1;
2843         cwindow->show_window();
2844         gui->mainmenu->show_cwindow->set_checked(1);
2845 }
2846
2847 void MWindow::show_gwindow()
2848 {
2849         session->show_gwindow = 1;
2850
2851         gwindow->gui->lock_window("MWindow::show_gwindow");
2852         gwindow->gui->show_window();
2853         gwindow->gui->raise_window();
2854         gwindow->gui->flush();
2855         gwindow->gui->unlock_window();
2856
2857         gui->mainmenu->show_gwindow->set_checked(1);
2858 }
2859 void MWindow::hide_gwindow()
2860 {
2861         session->show_gwindow = 0;
2862
2863         gwindow->gui->lock_window("MWindow::show_gwindow");
2864         gwindow->gui->hide_window();
2865         gwindow->gui->unlock_window();
2866 }
2867
2868 void MWindow::show_lwindow()
2869 {
2870         session->show_lwindow = 1;
2871         lwindow->gui->lock_window("MWindow::show_lwindow");
2872         lwindow->gui->show_window();
2873         lwindow->gui->raise_window();
2874         lwindow->gui->flush();
2875         lwindow->gui->unlock_window();
2876         gui->mainmenu->show_lwindow->set_checked(1);
2877 }
2878
2879 void MWindow::restore_windows()
2880 {
2881         if( !session->show_vwindow ) {
2882                 for( int i=0, n=vwindows.size(); i<n; ++i ) {
2883                         VWindow *vwindow = vwindows[i];
2884                         if( !vwindow || !vwindow->is_running() ) continue;
2885                         vwindow->gui->lock_window("MWindow::restore_windows");
2886                         vwindow->gui->close(1);
2887                         vwindow->gui->unlock_window();
2888                 }
2889         }
2890         else
2891                 show_vwindow();
2892
2893         if( !session->show_awindow && !awindow->gui->is_hidden() ) {
2894                 awindow->gui->lock_window("MWindow::restore_windows");
2895                 awindow->gui->close_event();
2896                 awindow->gui->unlock_window();
2897         }
2898         else if( session->show_awindow && awindow->gui->is_hidden() )
2899                 show_awindow();
2900
2901         if( !session->show_cwindow && !cwindow->gui->is_hidden() ) {
2902                 cwindow->gui->lock_window("MWindow::restore_windows");
2903                 cwindow->hide_window();
2904                 cwindow->gui->unlock_window();
2905         }
2906         else if( session->show_cwindow && cwindow->gui->is_hidden() )
2907                 cwindow->show_window();
2908
2909         if( !session->show_gwindow && !gwindow->gui->is_hidden() ) {
2910                 gwindow->gui->lock_window("MWindow::restore_windows");
2911                 gwindow->gui->close_event();
2912                 gwindow->gui->unlock_window();
2913         }
2914         else if( session->show_gwindow && gwindow->gui->is_hidden() )
2915                 show_gwindow();
2916
2917         if( !session->show_lwindow && !lwindow->gui->is_hidden() ) {
2918                 lwindow->gui->lock_window("MWindow::restore_windows");
2919                 lwindow->gui->close_event();
2920                 lwindow->gui->unlock_window();
2921         }
2922         else if( session->show_lwindow && lwindow->gui->is_hidden() )
2923                 show_lwindow();
2924
2925         gui->focus();
2926 }
2927
2928 void MWindow::load_layout(const char *layout)
2929 {
2930         char path[BCTEXTLEN];
2931         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
2932         session->load_file(path);
2933         restore_windows();
2934         gui->default_positions();
2935         save_defaults();
2936 }
2937
2938 void MWindow::save_layout(const char *layout)
2939 {
2940         char path[BCTEXTLEN];
2941         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
2942         session->save_file(path);
2943 }
2944
2945 void MWindow::delete_layout(const char *layout)
2946 {
2947         char path[BCTEXTLEN];
2948         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
2949         unlink(path);
2950 }
2951
2952 int MWindow::tile_windows(int window_config)
2953 {
2954         int need_reload = 0;
2955         int play_config = window_config==0 ? 0 : 1;
2956         edl->session->playback_config->load_defaults(defaults, play_config);
2957         session->default_window_positions(window_config);
2958         if( screens == 1 ) {
2959                 gui->default_positions();
2960                 sync_parameters(CHANGE_ALL);
2961         }
2962         else
2963                 need_reload = 1;
2964         return need_reload;
2965 }
2966
2967 void MWindow::toggle_loop_playback()
2968 {
2969         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2970         set_loop_boundaries();
2971         save_backup();
2972
2973         gui->draw_overlays(1);
2974         sync_parameters(CHANGE_PARAMS);
2975 }
2976
2977 void MWindow::set_screens(int value)
2978 {
2979         screens = value;
2980 }
2981
2982 void MWindow::set_auto_keyframes(int value)
2983 {
2984         edl->session->auto_keyframes = value;
2985         gui->mbuttons->edit_panel->keyframe->update(value);
2986         gui->flush();
2987         cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2988         cwindow->gui->edit_panel->keyframe->update(value);
2989         cwindow->gui->flush();
2990         cwindow->gui->unlock_window();
2991 }
2992
2993 void MWindow::set_auto_visibility(Autos *autos, int value)
2994 {
2995         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2996                 edl->session->auto_conf->plugins = value;
2997         else if( autos->autoidx >= 0 )
2998                 edl->session->auto_conf->autos[autos->autoidx] = value;
2999         else
3000                 return;
3001
3002         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3003         gui->mainmenu->update_toggles(1);
3004         gui->unlock_window();
3005         gwindow->gui->update_toggles(1);
3006         gui->lock_window("MWindow::set_auto_visibility");
3007 }
3008
3009 void MWindow::set_keyframe_type(int mode)
3010 {
3011         gui->lock_window("MWindow::set_keyframe_type");
3012         edl->local_session->floatauto_type = mode;
3013         gui->mainmenu->update_toggles(0);
3014         gui->unlock_window();
3015 }
3016
3017 int MWindow::set_editing_mode(int new_editing_mode)
3018 {
3019         edl->session->editing_mode = new_editing_mode;
3020         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
3021         gui->mbuttons->edit_panel->update();
3022         gui->set_editing_mode(1);
3023
3024         cwindow->gui->lock_window("MWindow::set_editing_mode");
3025         cwindow->gui->edit_panel->update();
3026         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
3027         cwindow->gui->unlock_window();
3028         return 0;
3029 }
3030
3031 void MWindow::toggle_editing_mode()
3032 {
3033         int mode = edl->session->editing_mode;
3034         if( mode == EDITING_ARROW )
3035                 set_editing_mode(EDITING_IBEAM);
3036         else
3037                 set_editing_mode(EDITING_ARROW);
3038 }
3039
3040 void MWindow::toggle_camera_xyz()
3041 {
3042         gwindow->gui->lock_window("MWindow::toggle_camera_xyz");
3043         gwindow->gui->toggle_camera_xyz();
3044         gwindow->gui->unlock_window();
3045 }
3046
3047 void MWindow::toggle_projector_xyz()
3048 {
3049         gwindow->gui->lock_window("MWindow::toggle_projector_xyz");
3050         gwindow->gui->toggle_projector_xyz();
3051         gwindow->gui->unlock_window();
3052 }
3053
3054 void MWindow::set_labels_follow_edits(int value)
3055 {
3056         edl->session->labels_follow_edits = value;
3057         gui->mbuttons->edit_panel->locklabels->update(value);
3058         gui->mainmenu->labels_follow_edits->set_checked(value);
3059         gui->flush();
3060 }
3061
3062 void MWindow::sync_parameters(int change_type)
3063 {
3064         if( in_destructor ) return;
3065
3066 // Sync engines which are playing back
3067         if( cwindow->playback_engine->is_playing_back ) {
3068                 if( change_type == CHANGE_PARAMS ) {
3069 // TODO: block keyframes until synchronization is done
3070                         cwindow->playback_engine->sync_parameters(edl);
3071                 }
3072                 else {
3073 // Stop and restart
3074                         int command = cwindow->playback_engine->command->command;
3075 // Waiting for tracking to finish would make the restart position more
3076 // accurate but it can't lock the window to stop tracking for some reason.
3077 // Not waiting for tracking gives a faster response but restart position is
3078 // only as accurate as the last tracking update.
3079                         cwindow->playback_engine->transport_stop(0);
3080                         cwindow->playback_engine->next_command->realtime = 1;
3081                         cwindow->playback_engine->transport_command(command, change_type, edl, 0);
3082                 }
3083         }
3084         else {
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_before();
3785         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_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_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_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_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