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