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