9ab96a9ed97e5ba7277b3456244d45a333201338
[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 "bccmodels.h"
42 #include "commercials.h"
43 #include "cplayback.h"
44 #include "ctimebar.h"
45 #include "cwindowgui.h"
46 #include "cwindow.h"
47 #include "cwindowtool.h"
48 #include "bchash.h"
49 #include "devicedvbinput.inc"
50 #include "dvdcreate.h"
51 #include "editpanel.h"
52 #include "edl.h"
53 #include "edlsession.h"
54 #include "errorbox.h"
55 #include "fileformat.h"
56 #include "file.h"
57 #include "filesystem.h"
58 #include "filexml.h"
59 #include "floatautos.h"
60 #include "framecache.h"
61 #include "gwindow.h"
62 #include "gwindowgui.h"
63 #include "keyframegui.h"
64 #include "indexfile.h"
65 #include "intautos.h"
66 #include "interlacemodes.h"
67 #include "language.h"
68 #include "levelwindowgui.h"
69 #include "levelwindow.h"
70 #include "loadfile.inc"
71 #include "localsession.h"
72 #include "maincursor.h"
73 #include "mainerror.h"
74 #include "mainindexes.h"
75 #include "mainmenu.h"
76 #include "mainprogress.h"
77 #include "mainsession.h"
78 #include "mainundo.h"
79 #include "mbuttons.h"
80 #include "mutex.h"
81 #include "mwindowgui.h"
82 #include "mwindow.h"
83 #include "nestededls.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)
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);
1253         }
1254         zwindows_lock->unlock();
1255 }
1256
1257 void MWindow::refresh_mixers()
1258 {
1259         queue_mixers(edl,CURRENT_FRAME,0,0,1,0);
1260 }
1261
1262 void MWindow::stop_mixers()
1263 {
1264         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1265                 ZWindow *zwindow = zwindows[vidx];
1266                 if( zwindow->idx < 0 ) continue;
1267                 zwindow->issue_command(STOP, 0, 0, 0, 0);
1268         }
1269 }
1270
1271 void MWindow::close_mixers()
1272 {
1273         zwindows_lock->lock("MWindow::close_mixers");
1274         for( int i=0; i<zwindows.size(); ++i ) {
1275                 ZWindow *zwindow = zwindows[i];
1276                 if( zwindow->idx < 0 ) continue;
1277                 ZWindowGUI *zgui = zwindow->zgui;
1278                 zgui->lock_window("MWindow::select_zwindow 0");
1279                 zgui->set_done(0);
1280                 zgui->unlock_window();
1281         }
1282         zwindows_lock->unlock();
1283         for( int i=0; i<zwindows.size(); ++i ) {
1284                 ZWindow *zwindow = zwindows[i];
1285                 if( zwindow->idx < 0 ) continue;
1286                 zwindow->close_window();
1287         }
1288 }
1289
1290 void MWindow::create_mixers()
1291 {
1292         if( !session->drag_assets->size() ) return;
1293         undo->update_undo_before();
1294
1295         select_zwindow(0);
1296         ArrayList<ZWindow *>new_mixers;
1297
1298         for( int i=0; i<session->drag_assets->total; ++i ) {
1299                 Indexable *indexable = session->drag_assets->values[i];
1300                 ArrayList<Indexable*> new_assets;
1301                 new_assets.append(indexable);
1302                 Track *track = edl->tracks->last;
1303                 load_assets(&new_assets, -1, LOADMODE_NEW_TRACKS, 0, 0, 0, 0, 0, 0);
1304                 track = !track ? edl->tracks->first : track->next;
1305                 Mixer *mixer = 0;
1306                 ZWindow *zwindow = get_mixer(mixer);
1307                 while( track ) {
1308                         track->play = track->record = 0;
1309                         if( track->data_type == TRACK_VIDEO ) {
1310                                 sprintf(track->title, _("Mixer %d"), zwindow->idx);
1311                         }
1312                         mixer->mixer_ids.append(track->get_mixer_id());
1313                         track = track->next;
1314                 }
1315                 char *path = indexable->path;
1316                 char *tp = strrchr(path, '/');
1317                 if( !tp ) tp = path; else ++tp;
1318                 zwindow->set_title(tp);
1319                 new_mixers.append(zwindow);
1320         }
1321
1322         tile_mixers();
1323         for( int i=0; i<new_mixers.size(); ++i )
1324                 new_mixers[i]->start();
1325
1326         refresh_mixers();
1327         save_backup();
1328         undo->update_undo_after(_("create mixers"), LOAD_ALL);
1329         restart_brender();
1330         gui->update(1, 2, 1, 1, 1, 1, 0);
1331         sync_parameters(CHANGE_ALL);
1332 }
1333
1334 void MWindow::open_mixers()
1335 {
1336         for( int i=0; i<edl->mixers.size(); ++i ) {
1337                 Mixer *mixer = edl->mixers[i];
1338                 ZWindow *zwindow = get_mixer(mixer);
1339                 zwindow->set_title(mixer->title);
1340                 zwindow->start();
1341         }
1342         refresh_mixers();
1343 }
1344
1345 int MWindow::select_zwindow(ZWindow *zwindow)
1346 {
1347         int ret = 0, n = zwindows.number_of(zwindow);
1348         if( session->selected_zwindow != n ) {
1349                 session->selected_zwindow = n;
1350                 for( int i=0; i<zwindows.size(); ++i ) {
1351                         ZWindow *zwindow = zwindows[i];
1352                         if( zwindow->idx < 0 ) continue;
1353                         ZWindowGUI *zgui = zwindow->zgui;
1354                         zgui->lock_window("MWindow::select_zwindow 0");
1355                         zwindow->highlighted = i == n ? 1 : 0;
1356                         if( zgui->draw_overlays() )
1357                                 zgui->canvas->get_canvas()->flash(1);
1358                         zgui->unlock_window();
1359                 }
1360                 ret = 1;
1361                 gui->lock_window("MWindow::select_window 1");
1362                 gui->update_mixers(0, -1);
1363                 gui->unlock_window();
1364         }
1365         return ret;
1366 }
1367
1368 void MWindow::tile_mixers()
1369 {
1370         int nz = 0;
1371         for( int i=0; i<zwindows.size(); ++i ) {
1372                 ZWindow *zwindow = zwindows[i];
1373                 if( zwindow->idx < 0 ) continue;
1374                 ++nz;
1375         }
1376         if( !nz ) return;
1377         int zn = ceil(sqrt(nz));
1378         int x1 = 1 + gui->get_x(), x2 = cwindow->gui->get_x();
1379         int y1 = 1, y2 = gui->get_y();
1380         int rw = gui->get_root_w(0), rh = gui->get_root_h(0);
1381         if( x1 < 0 ) x1 = 0;
1382         if( y1 < 0 ) y1 = 0;
1383         if( x2 > rw ) x2 = rw;
1384         if( y2 > rh ) y2 = rh;
1385         int dx = x2 - x1, dy = y2 - y1;
1386         int zw = dx / zn;
1387         int lt = BC_DisplayInfo::get_left_border();
1388         int top = BC_DisplayInfo::get_top_border();
1389         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1390         int bh = top + BC_DisplayInfo::get_bottom_border();
1391         int zx = 0, zy = 0;  // window origins
1392         int mw = 10+10, mh = 10+10; // canvas margins
1393         int rsz = 0, n = 0, dz = 0;
1394         int ow = edl->session->output_w, oh = edl->session->output_h;
1395         for( int i=0; i<zwindows.size(); ++i ) {
1396                 ZWindow *zwindow = zwindows[i];
1397                 if( zwindow->idx < 0 ) continue;
1398                 int ww = zw - bw, hh = (ww - mw) * oh / ow + mh, zh = hh + bh;
1399                 if( rsz < hh ) rsz = hh;
1400                 int xx = zx + x1, yy = zy + y1;
1401                 int mx = x2 - zw, my = y2 - zh;
1402                 if( xx > mx ) xx = mx;
1403                 if( yy > my ) yy = my;
1404                 xx += lt + dz;  yy += top + dz;
1405                 zwindow->reposition(xx,yy, ww,hh);
1406                 if( zwindow->running() ) {
1407                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1408                         gui->lock_window("MWindow::tile_mixers");
1409                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1410                         gui->unlock_window();
1411                 }
1412                 if( ++n >= zn ) {
1413                         n = 0;  rsz += bh;
1414                         if( (zy += rsz) > (dy - rsz) ) dz += 10;
1415                         rsz = 0;
1416                         zx = 0;
1417                 }
1418                 else
1419                         zx += zw;
1420         }
1421 }
1422
1423 void MWindow::init_cache()
1424 {
1425         audio_cache = new CICache(preferences);
1426         video_cache = new CICache(preferences);
1427         frame_cache = new FrameCache;
1428         wave_cache = new WaveCache;
1429 }
1430
1431 void MWindow::init_channeldb()
1432 {
1433         channeldb_buz->load("channeldb_buz");
1434         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1435 }
1436
1437 void MWindow::init_menus()
1438 {
1439         char string[BCTEXTLEN];
1440
1441         // Color Models
1442         BC_CModels::to_text(string, BC_RGB888);
1443         colormodels.append(new ColormodelItem(string, BC_RGB888));
1444         BC_CModels::to_text(string, BC_RGBA8888);
1445         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1446 //      BC_CModels::to_text(string, BC_RGB161616);
1447 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1448 //      BC_CModels::to_text(string, BC_RGBA16161616);
1449 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1450         BC_CModels::to_text(string, BC_RGB_FLOAT);
1451         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1452         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1453         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1454         BC_CModels::to_text(string, BC_YUV888);
1455         colormodels.append(new ColormodelItem(string, BC_YUV888));
1456         BC_CModels::to_text(string, BC_YUVA8888);
1457         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1458 //      BC_CModels::to_text(string, BC_YUV161616);
1459 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1460 //      BC_CModels::to_text(string, BC_YUVA16161616);
1461 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1462
1463 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1464                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1465
1466 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1467                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1468
1469 #define ILACEFIXMETHODLISTADD(x) ilacefixmethod_to_text(string, x); \
1470                            interlace_asset_fixmethods.append(new InterlacefixmethodItem(string, x));
1471
1472         // Interlacing Modes
1473         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1474
1475         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1476         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1477
1478         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1479         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1480
1481         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1482         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1483
1484         // Interlacing Fixing Methods
1485         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_NONE);
1486         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_UPONE);
1487         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_DOWNONE);
1488 }
1489
1490 void MWindow::init_indexes()
1491 {
1492         mainindexes = new MainIndexes(this);
1493         mainindexes->start_loop();
1494 }
1495
1496 void MWindow::init_gui()
1497 {
1498         gui = new MWindowGUI(this);
1499         gui->lock_window("MWindow::init_gui");
1500         gui->create_objects();
1501         gui->unlock_window();
1502         gui->load_defaults(defaults);
1503 }
1504
1505 void MWindow::init_signals()
1506 {
1507         sighandler = new SigHandler;
1508         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1509 ENABLE_BUFFER
1510 }
1511
1512 void MWindow::init_render()
1513 {
1514         render = new Render(this);
1515         create_bd = new CreateBD_Thread(this);
1516         create_dvd = new CreateDVD_Thread(this);
1517         batch_render = new BatchRenderThread(this);
1518 }
1519
1520 void MWindow::init_exportedl()
1521 {
1522         exportedl = new ExportEDL(this);
1523 }
1524
1525 void MWindow::init_brender()
1526 {
1527         if(preferences->use_brender && !brender)
1528         {
1529                 brender_lock->lock("MWindow::init_brender 1");
1530                 brender = new BRender(this);
1531                 brender->initialize();
1532                 session->brender_end = 0;
1533                 brender_lock->unlock();
1534         }
1535         else
1536         if(!preferences->use_brender && brender)
1537         {
1538                 brender_lock->lock("MWindow::init_brender 2");
1539                 delete brender;
1540                 brender = 0;
1541                 session->brender_end = 0;
1542                 brender_lock->unlock();
1543         }
1544         brender_active = 0;
1545         stop_brender();
1546 }
1547
1548 void MWindow::restart_brender()
1549 {
1550 //printf("MWindow::restart_brender 1\n");
1551         if( !brender_active || !preferences->use_brender ) return;
1552         if( !brender ) return;
1553         brender->restart(edl);
1554 }
1555
1556 void MWindow::stop_brender()
1557 {
1558         if( !brender ) return;
1559         brender->stop();
1560 }
1561
1562 int MWindow::brender_available(int position)
1563 {
1564         int result = 0;
1565         brender_lock->lock("MWindow::brender_available 1");
1566         if(brender && brender_active)
1567         {
1568                 if(brender->map_valid)
1569                 {
1570                         brender->map_lock->lock("MWindow::brender_available 2");
1571                         if(position < brender->map_size &&
1572                                 position >= 0)
1573                         {
1574 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1575                                 if(brender->map[position] == BRender::RENDERED)
1576                                         result = 1;
1577                         }
1578                         brender->map_lock->unlock();
1579                 }
1580         }
1581         brender_lock->unlock();
1582         return result;
1583 }
1584
1585 void MWindow::set_brender_active(int v, int update)
1586 {
1587         if( !preferences->use_brender ) v = 0;
1588         brender_active = v;
1589         gui->mainmenu->brender_active->set_checked(v);
1590         if( v != 0 ) {
1591                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1592                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1593
1594                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1595                         edl->session->brender_end = edl->tracks->total_video_length();
1596                 }
1597                 restart_brender();
1598         }
1599         else {
1600                 edl->session->brender_start = edl->session->brender_end = 0;
1601                 stop_brender();
1602         }
1603         if( update ) {
1604                 gui->update_timebar(0);
1605                 gui->draw_overlays(1);
1606         }
1607 }
1608
1609 int MWindow::has_commercials()
1610 {
1611         return theme->use_commercials;
1612 }
1613
1614 void MWindow::init_commercials()
1615 {
1616         if( !commercials ) {
1617                 commercials = new Commercials(this);
1618                 commercial_active = 0;
1619         }
1620         else
1621                 commercials->add_user();
1622 }
1623
1624 void MWindow::commit_commercial()
1625 {
1626         if( !commercial_active ) return;
1627         commercial_active = 0;
1628         if( !commercials ) return;
1629         commercials->commitDb();
1630 }
1631
1632 void MWindow::undo_commercial()
1633 {
1634         if( !commercial_active ) return;
1635         commercial_active = 0;
1636         if( !commercials ) return;
1637         commercials->undoDb();
1638 }
1639
1640 int MWindow::put_commercial()
1641 {
1642         double start = edl->local_session->get_selectionstart();
1643         double end = edl->local_session->get_selectionend();
1644         if( start >= end ) return 0;
1645
1646         const char *errmsg = 0;
1647         int count = 0;
1648         Tracks *tracks = edl->tracks;
1649         int result = 0;
1650         //check it
1651         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1652                 if( track->data_type != TRACK_VIDEO ) continue;
1653                 if( !track->record ) continue;
1654                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1655                 ++count;
1656                 int64_t units_start = track->to_units(start,0);
1657                 int64_t units_end = track->to_units(end,0);
1658                 Edits *edits = track->edits;
1659                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1660                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1661                 if(!edit1 && !edit2) continue;  // nothing selected
1662                 if(!edit2) {                    // edit2 beyond end of track
1663                         edit2 = edits->last;
1664                         units_end = edits->length();
1665                 }
1666                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1667                 Indexable *indexable = edit1->get_source();
1668                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1669         }
1670         //run it
1671         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1672                 if( track->data_type != TRACK_VIDEO ) continue;
1673                 if( !track->record ) continue;
1674                 int64_t units_start = track->to_units(start,0);
1675                 int64_t units_end = track->to_units(end,0);
1676                 Edits *edits = track->edits;
1677                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1678                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1679                 if(!edit1 && !edit2) continue;  // nothing selected
1680                 if(!edit2) {                    // edit2 beyond end of track
1681                         edit2 = edits->last;
1682                         units_end = edits->length();
1683                 }
1684                 Indexable *indexable = edit1->get_source();
1685                 Asset *asset = (Asset *)indexable;
1686                 File *file = video_cache->check_out(asset, edl);
1687                 if( !file ) { errmsg = _("no file"); break; }
1688                 int64_t edit_length = units_end - units_start;
1689                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1690                 result = commercials->put_clip(file, edit1->channel,
1691                         track->from_units(edit_start), track->from_units(edit_length));
1692                 video_cache->check_in(asset);
1693                 if( result ) { errmsg = _("db failed"); break; }
1694         }
1695         if( errmsg ) {
1696                 char string[BCTEXTLEN];
1697                 sprintf(string, _("put_commercial: %s"), errmsg);
1698                 MainError::show_error(string);
1699                 undo_commercial();
1700                 result = 1;
1701         }
1702         return result;
1703 }
1704
1705 void MWindow::stop_playback(int wait)
1706 {
1707         gui->stop_drawing();
1708
1709         cwindow->stop_playback(wait);
1710
1711         for(int i = 0; i < vwindows.size(); i++) {
1712                 VWindow *vwindow = vwindows[i];
1713                 if( !vwindow->is_running() ) continue;
1714                 vwindow->stop_playback(wait);
1715         }
1716         for(int i = 0; i < zwindows.size(); i++) {
1717                 ZWindow *zwindow = zwindows[i];
1718                 if( zwindow->idx < 0 ) continue;
1719                 zwindow->stop_playback(wait);
1720         }
1721 }
1722
1723 int MWindow::load_filenames(ArrayList<char*> *filenames,
1724         int load_mode,
1725         int update_filename)
1726 {
1727         ArrayList<EDL*> new_edls;
1728         ArrayList<Asset*> new_assets;
1729         ArrayList<File*> new_files;
1730         const int debug = 0;
1731 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1732
1733 //      save_defaults();
1734         gui->start_hourglass();
1735
1736 // Need to stop playback since tracking depends on the EDL not getting
1737 // deleted.
1738         gui->unlock_window();
1739         stop_playback(1);
1740         gui->lock_window("MWindow::load_filenames 0");
1741
1742 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1743         undo->update_undo_before();
1744
1745
1746 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1747
1748 // Define new_edls and new_assets to load
1749         int result = 0, ftype = -1;
1750
1751         for( int i=0; i<filenames->size(); ++i ) {
1752 // Get type of file
1753                 File *new_file = new File;
1754                 Asset *new_asset = new Asset(filenames->get(i));
1755                 EDL *new_edl = new EDL;
1756                 char string[BCTEXTLEN];
1757
1758                 new_edl->create_objects();
1759                 new_edl->copy_session(edl);
1760                 new_file->set_program(edl->session->program_no);
1761
1762                 sprintf(string, _("Loading %s"), new_asset->path);
1763                 gui->show_message(string);
1764 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1765
1766                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1767 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1768
1769                 result = 1;
1770                 switch( ftype ) {
1771 // Convert media file to EDL
1772                 case FILE_OK:
1773 // Warn about odd image dimensions
1774                         if( new_asset->video_data &&
1775                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
1776                                 char string[BCTEXTLEN];
1777                                 sprintf(string, _("%s's resolution is %dx%d.\nImages with odd dimensions may not decode properly."),
1778                                         new_asset->path, new_asset->width, new_asset->height);
1779                                 MainError::show_error(string);
1780                         }
1781
1782                         if( new_asset->program >= 0 &&
1783                             edl->session->program_no != new_asset->program ) {
1784                                 char string[BCTEXTLEN];
1785                                 sprintf(string, _("%s's index was built for program number %d\n"
1786                                         "Playback preference is %d.\n  Using program %d."),
1787                                         new_asset->path, new_asset->program,
1788                                         edl->session->program_no, new_asset->program);
1789                                 MainError::show_error(string);
1790                         }
1791
1792                         if( load_mode != LOADMODE_RESOURCESONLY ) {
1793                                 RecordLabels *labels = edl->session->label_cells ?
1794                                         new RecordLabels(new_file) : 0;
1795                                 asset_to_edl(new_edl, new_asset, labels);
1796                                 new_edls.append(new_edl);
1797                                 new_edl->add_user();
1798                                 delete labels;
1799                         }
1800                         else {
1801                                 new_assets.append(new_asset);
1802                                 new_asset->add_user();
1803                         }
1804
1805 // Set filename to nothing for assets since save EDL would overwrite them.
1806                         if( load_mode == LOADMODE_REPLACE ||
1807                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
1808                                 set_filename("");
1809 // Reset timeline position
1810                                 for( int i=0; i<TOTAL_PANES; ++i ) {
1811                                         new_edl->local_session->view_start[i] = 0;
1812                                         new_edl->local_session->track_start[i] = 0;
1813                                 }
1814                         }
1815
1816                         result = 0;
1817                         break;
1818
1819 // File not found
1820                 case FILE_NOT_FOUND:
1821                         sprintf(string, _("Failed to open %s"), new_asset->path);
1822                         gui->show_message(string, theme->message_error);
1823                         gui->update_default_message();
1824                         break;
1825
1826 // Unknown format
1827                 case FILE_UNRECOGNIZED_CODEC: {
1828 // Test index file
1829                         { IndexFile indexfile(this, new_asset);
1830                         if( !(result = indexfile.open_index()) )
1831                                 indexfile.close_index(); }
1832
1833 // Test existing EDLs
1834                         for( int j=0; result && j<new_edls.total; ++j ) {
1835                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
1836                                 if( old_asset ) {
1837                                         new_asset->copy_from(old_asset,1);
1838                                         result = 0;
1839                                 }
1840                         }
1841                         if( result ) {
1842                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
1843                                 if( old_asset ) {
1844                                         new_asset->copy_from(old_asset,1);
1845                                         result = 0;
1846                                 }
1847                         }
1848
1849 // Prompt user
1850                         if( result ) {
1851                                 char string[BCTEXTLEN];
1852                                 FileSystem fs;
1853                                 fs.extract_name(string, new_asset->path);
1854
1855                                 strcat(string, _("'s format couldn't be determined."));
1856                                 new_asset->audio_data = 1;
1857                                 new_asset->format = FILE_PCM;
1858                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
1859                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
1860                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
1861                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
1862                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
1863                                 new_asset->header = defaults->get("HEADER", 0);
1864
1865                                 FileFormat fwindow(this);
1866                                 fwindow.create_objects(new_asset, string);
1867                                 result = fwindow.run_window();
1868
1869                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
1870                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
1871                                 defaults->update("AUDIO_BITS", new_asset->bits);
1872                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
1873                                 defaults->update("SIGNED_", new_asset->signed_);
1874                                 defaults->update("HEADER", new_asset->header);
1875                                 save_defaults();
1876                         }
1877
1878 // Append to list
1879                         if( !result ) {
1880 // Recalculate length
1881                                 delete new_file;
1882                                 new_file = new File;
1883                                 result = new_file->open_file(preferences, new_asset, 1, 0);
1884
1885                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
1886                                         RecordLabels *labels = edl->session->label_cells ?
1887                                                 new RecordLabels(new_file) : 0;
1888                                         asset_to_edl(new_edl, new_asset, labels);
1889                                         new_edls.append(new_edl);
1890                                         new_edl->add_user();
1891                                         delete labels;
1892                                 }
1893                                 else {
1894                                         new_assets.append(new_asset);
1895                                         new_asset->add_user();
1896                                 }
1897                         }
1898                         else {
1899                                 result = 1;
1900                         }
1901                         break; }
1902
1903                 case FILE_IS_XML: {
1904                         FileXML xml_file;
1905 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1906                         xml_file.read_from_file(filenames->get(i));
1907 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1908                         const char *cin_version = 0;
1909                         while( !xml_file.read_tag() ) {
1910                                 if( xml_file.tag.title_is("EDL") ) {
1911                                         cin_version = xml_file.tag.get_property("VERSION");
1912                                         break;
1913                                 }
1914                         }
1915                         xml_file.rewind();
1916                         if( !cin_version ) {
1917                                 eprintf(_("XML file %s\n not from cinelerra."),filenames->get(i));
1918                                 char string[BCTEXTLEN];
1919                                 sprintf(string,_("Unknown %s"), filenames->get(i));
1920                                 gui->show_message(string);
1921                                 result = 1;
1922                                 break;
1923                         }
1924                         if( strcmp(cin_version, CINELERRA_VERSION) ) {
1925                                 char string[BCTEXTLEN];
1926                                 snprintf(string, sizeof(string),
1927                                          _("Warning: XML from cinelerra version %s\n"
1928                                         "Session data may be incompatible."), cin_version);
1929                                 show_warning(&preferences->warn_version, string);
1930                         }
1931                         if( load_mode == LOADMODE_NESTED ) {
1932 // Load temporary EDL for nesting.
1933                                 EDL *nested_edl = new EDL;
1934                                 nested_edl->create_objects();
1935                                 nested_edl->set_path(filenames->get(i));
1936                                 nested_edl->load_xml(&xml_file, LOAD_ALL);
1937 //printf("MWindow::load_filenames %p %s\n", nested_edl, nested_edl->project_path);
1938                                 edl_to_nested(new_edl, nested_edl);
1939                                 nested_edl->Garbage::remove_user();
1940                         }
1941                         else {
1942 // Load EDL for pasting
1943                                 new_edl->load_xml(&xml_file, LOAD_ALL);
1944 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1945                                 test_plugins(new_edl, filenames->get(i));
1946 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1947
1948                                 if( load_mode == LOADMODE_REPLACE ||
1949                                     load_mode == LOADMODE_REPLACE_CONCATENATE ) {
1950                                         strcpy(session->filename, filenames->get(i));
1951                                         strcpy(new_edl->local_session->clip_title,
1952                                                 filenames->get(i));
1953                                         if(update_filename)
1954                                                 set_filename(new_edl->local_session->clip_title);
1955                                 }
1956                                 else if( load_mode == LOADMODE_RESOURCESONLY ) {
1957                                         strcpy(new_edl->local_session->clip_title,
1958                                                 filenames->get(i));
1959                                         struct stat st;
1960                                         time_t t = !stat(filenames->get(i),&st) ?
1961                                                 st.st_mtime : time(&t);
1962                                         ctime_r(&t, new_edl->local_session->clip_notes);
1963                                 }
1964                         }
1965
1966                         new_edls.append(new_edl);
1967                         new_edl->add_user();
1968                         result = 0;
1969                         break; }
1970                 }
1971
1972                 new_edl->Garbage::remove_user();
1973                 new_asset->Garbage::remove_user();
1974
1975 // Store for testing index
1976                 new_files.append(new_file);
1977         }
1978
1979 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1980
1981
1982         if(!result) {
1983                 gui->reset_default_message();
1984                 gui->default_message();
1985         }
1986
1987
1988 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1989
1990 // Paste them.
1991 // Don't back up here.
1992         if(new_edls.size())
1993         {
1994 // For pasting, clear the active region
1995                 if(load_mode == LOADMODE_PASTE ||
1996                         load_mode == LOADMODE_NESTED)
1997                 {
1998                         double start = edl->local_session->get_selectionstart();
1999                         double end = edl->local_session->get_selectionend();
2000                         if(!EQUIV(start, end))
2001                                 edl->clear(start,
2002                                         end,
2003                                         edl->session->labels_follow_edits,
2004                                         edl->session->plugins_follow_edits,
2005                                         edl->session->autos_follow_edits);
2006                 }
2007
2008                 paste_edls(&new_edls, load_mode, 0, -1,
2009                         edl->session->labels_follow_edits,
2010                         edl->session->plugins_follow_edits,
2011                         edl->session->autos_follow_edits,
2012                         0); // overwrite
2013         }
2014
2015
2016
2017
2018 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2019
2020 // Add new assets to EDL and schedule assets for index building.
2021         int got_indexes = 0;
2022         for(int i = 0; i < new_edls.size(); i++)
2023         {
2024                 EDL *new_edl = new_edls[i];
2025                 for(int j = 0; j < new_edl->nested_edls->size(); j++)
2026                 {
2027                         mainindexes->add_next_asset(0,
2028                                 new_edl->nested_edls->get(j));
2029                         got_indexes = 1;
2030                         edl->nested_edls->update_index(new_edl->nested_edls->get(j));
2031                 }
2032
2033         }
2034
2035 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2036         for(int i = 0; i < new_assets.size(); i++)
2037         {
2038                 Asset *new_asset = new_assets[i];
2039
2040                 File *new_file = 0;
2041                 int got_it = 0;
2042                 for(int j = 0; j < new_files.size(); j++)
2043                 {
2044                         new_file = new_files[j];
2045                         if(!strcmp(new_file->asset->path,
2046                                 new_asset->path))
2047                         {
2048                                 got_it = 1;
2049                                 break;
2050                         }
2051                 }
2052
2053                 mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
2054                 got_indexes = 1;
2055                 edl->assets->update(new_asset);
2056         }
2057 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2058
2059 // Start examining next batch of index files
2060         if(got_indexes) mainindexes->start_build();
2061 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2062
2063 // Open plugin GUIs
2064         Track *track = edl->tracks->first;
2065         while(track)
2066         {
2067                 for(int j = 0; j < track->plugin_set.size(); j++)
2068                 {
2069                         PluginSet *plugins = track->plugin_set[j];
2070                         Plugin *plugin = plugins->get_first_plugin();
2071
2072                         while(plugin)
2073                         {
2074                                 if(load_mode == LOADMODE_REPLACE ||
2075                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
2076                                 {
2077                                         if(plugin->plugin_type == PLUGIN_STANDALONE &&
2078                                                 plugin->show)
2079                                         {
2080                                                 show_plugin(plugin);
2081                                         }
2082                                 }
2083
2084                                 plugin = (Plugin*)plugin->next;
2085                         }
2086                 }
2087
2088                 track = track->next;
2089         }
2090
2091         // if just opening one new resource in replace mode
2092         if( ftype != FILE_IS_XML &&
2093             ( load_mode == LOADMODE_REPLACE ||
2094               load_mode == LOADMODE_REPLACE_CONCATENATE ) ) {
2095                 select_asset(0, 0);
2096                 edl->session->proxy_scale = 1;
2097                 edl->session->proxy_use_scaler = 0;
2098                 edl->session->proxy_auto_scale = 0;
2099                 edl->local_session->preview_start = 0;
2100                 edl->local_session->preview_end = 0;
2101                 edl->local_session->loop_playback = 0;
2102                 edl->local_session->set_selectionstart(0);
2103                 edl->local_session->set_selectionend(0);
2104                 set_brender_active(0, 0);
2105                 fit_selection();
2106                 goto_start();
2107         }
2108
2109         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
2110             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
2111                 ArrayList<Indexable *> orig_idxbls;
2112                 for( int i=0; i<new_assets.size(); ++i )
2113                         orig_idxbls.append(new_assets.get(i));
2114                 for( int i=0; i<new_edls.size(); ++i ) {
2115                         EDL *new_edl = new_edls[i];
2116                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2117                                 if( track->data_type != TRACK_VIDEO ) continue;
2118                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2119                                         Indexable *idxbl = (Indexable *)edit->asset;
2120                                         if( !idxbl ) continue;
2121                                         if( !idxbl->have_video() ) continue;
2122                                         if( edit->channel != 0 ) continue; // first layer only
2123                                         orig_idxbls.append(edit->asset);
2124                                 }
2125                         }
2126                 }
2127                 gui->unlock_window(); // to update progress bar
2128                 render_proxy(orig_idxbls);
2129                 gui->lock_window("MWindow::load_filenames");
2130         }
2131
2132 // need to update undo before project, since mwindow is unlocked & a new load
2133 // can begin here.  Should really prevent loading until we're done.
2134 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2135         undo->update_undo_after(_("load"), LOAD_ALL);
2136
2137         for(int i = 0; i < new_edls.size(); i++)
2138         {
2139                 new_edls[i]->remove_user();
2140         }
2141 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2142
2143         new_edls.remove_all();
2144
2145         for(int i = 0; i < new_assets.size(); i++)
2146         {
2147                 new_assets[i]->Garbage::remove_user();
2148         }
2149
2150         new_assets.remove_all();
2151         new_files.remove_all_objects();
2152
2153
2154 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2155         if(load_mode == LOADMODE_REPLACE ||
2156                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2157         {
2158                 session->changes_made = 0;
2159         }
2160         else
2161         {
2162                 session->changes_made = 1;
2163         }
2164
2165         gui->stop_hourglass();
2166
2167
2168 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2169         update_project(load_mode);
2170
2171 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2172
2173         return 0;
2174 }
2175
2176 void MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2177 {
2178         Asset *format_asset = new Asset;
2179         format_asset->format = FILE_FFMPEG;
2180         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2181         ProxyRender proxy_render(this, format_asset);
2182         int new_scale = edl->session->proxy_scale;
2183         int use_scaler = edl->session->proxy_use_scaler;
2184
2185         for( int i=0; i<new_idxbls.size(); ++i ) {
2186                 Indexable *orig = new_idxbls.get(i);
2187                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2188                 if( !proxy ) continue;
2189                 FileSystem fs;
2190                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2191                 int got_it = exists && // if proxy exists, and is newer than orig
2192                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2193                 if( got_it ) continue;
2194                 proxy_render.add_needed(orig, proxy);
2195         }
2196
2197 // render needed proxies
2198         int result = proxy_render.create_needed_proxies(new_scale);
2199         if( !result ) {
2200                 add_proxy(use_scaler,
2201                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2202         }
2203         format_asset->remove_user();
2204 }
2205
2206 void MWindow::test_plugins(EDL *new_edl, char *path)
2207 {
2208         char string[BCTEXTLEN];
2209
2210 // Do a check whether plugins exist
2211         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2212                 for( int k=0; k<track->plugin_set.total; ++k ) {
2213                         PluginSet *plugin_set = track->plugin_set[k];
2214                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2215                                         plugin; plugin = (Plugin*)plugin->next ) {
2216                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2217 // ok we need to find it in plugindb
2218                                 PluginServer *server =
2219                                         scan_plugindb(plugin->title, track->data_type);
2220                                 if( !server || server->transition ) {
2221                                         sprintf(string,
2222         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2223           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2224                                                 "effect", _(plugin->title), path);
2225                                         MainError::show_error(string);
2226                                 }
2227                         }
2228                 }
2229
2230                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2231                         if( !edit->transition ) continue;
2232 // ok we need to find transition in plugindb
2233                         PluginServer *server =
2234                                 scan_plugindb(edit->transition->title, track->data_type);
2235                         if( !server || !server->transition ) {
2236                                 sprintf(string,
2237         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2238           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2239                                         "transition", _(edit->transition->title), path);
2240                                 MainError::show_error(string);
2241                         }
2242                 }
2243         }
2244 }
2245
2246
2247 void MWindow::init_shm()
2248 {
2249 // Fix shared memory
2250         FILE *fd = fopen("/proc/sys/kernel/shmmax", "w");
2251         if(fd) {
2252                 fprintf(fd, "0x7fffffff");
2253                 fclose(fd);
2254         }
2255         fd = 0;
2256
2257         fd = fopen("/proc/sys/kernel/shmmax", "r");
2258         if(!fd) {
2259                 MainError::show_error("MWindow::init_shm: couldn't open /proc/sys/kernel/shmmax for reading.\n");
2260                 return;
2261         }
2262
2263         int64_t result = 0;
2264         fscanf(fd, "%jd", &result);
2265         fclose(fd);
2266         fd = 0;
2267         if(result < 0x7fffffff) {
2268                 eprintf(_("MWindow::init_shm: /proc/sys/kernel/shmmax is %p.\n"
2269                         "you probably need to be root, or:\n"
2270                         "as root, run: echo 0x7fffffff > /proc/sys/kernel/shmmax\n"
2271                         "before trying to start cinelerra.\n"
2272                         "It should be at least 0x7fffffff for Cinelerra.\n"), (void *)result);
2273         }
2274 }
2275
2276 void MWindow::create_objects(int want_gui,
2277         int want_new,
2278         char *config_path)
2279 {
2280         const int debug = 0;
2281         if(debug) PRINT_TRACE
2282
2283 // For some reason, init_signals must come after show_splash or the signals won't
2284 // get trapped.
2285         init_signals();
2286         if(debug) PRINT_TRACE
2287         init_3d();
2288
2289         if(debug) PRINT_TRACE
2290         show_splash();
2291
2292         if(debug) PRINT_TRACE
2293         default_standard = default_std();
2294         init_defaults(defaults, config_path);
2295         check_language();
2296         init_preferences();
2297         if(splash_window)
2298                 splash_window->operation->update(_("Initializing Plugins"));
2299         init_plugins(this, preferences);
2300         if(debug) PRINT_TRACE
2301         init_ladspa_plugins(this, preferences);
2302         if(debug) PRINT_TRACE
2303         init_plugin_tips(*plugindb, cin_lang);
2304         if(splash_window)
2305                 splash_window->operation->update(_("Initializing GUI"));
2306         if(debug) PRINT_TRACE
2307         init_theme();
2308
2309         if(debug) PRINT_TRACE
2310         init_error();
2311
2312         if(splash_window)
2313                 splash_window->operation->update(_("Initializing Fonts"));
2314         char string[BCTEXTLEN];
2315         strcpy(string, preferences->plugin_dir);
2316         strcat(string, "/" FONT_SEARCHPATH);
2317         BC_Resources::init_fontconfig(string);
2318         if(debug) PRINT_TRACE
2319
2320 // Initialize before too much else is running
2321 // Preferences & theme are required for building MPEG table of contents
2322
2323 // Default project created here
2324         init_edl();
2325         if(debug) PRINT_TRACE
2326
2327         init_cache();
2328         if(debug) PRINT_TRACE
2329
2330         Timer timer;
2331
2332         init_awindow();
2333         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2334
2335         init_compositor();
2336         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2337
2338 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2339         if(session->show_vwindow)
2340                 get_viewer(1, DEFAULT_VWINDOW);
2341         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2342
2343         init_gui();
2344         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2345
2346         init_levelwindow();
2347         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2348
2349         init_indexes();
2350         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2351
2352         init_channeldb();
2353         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2354
2355         init_gwindow();
2356         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2357
2358         init_render();
2359         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2360
2361         init_brender();
2362         init_exportedl();
2363         init_commercials();
2364         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2365         mainprogress = new MainProgress(this, gui);
2366         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2367         undo = new MainUndo(this);
2368
2369         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2370
2371         plugin_guis = new ArrayList<PluginServer*>;
2372         dead_plugins = new ArrayList<PluginServer*>;
2373         keyframe_threads = new ArrayList<KeyFrameThread*>;
2374
2375         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2376                 __LINE__,
2377                 vwindows.size(),
2378                 session->show_vwindow);
2379
2380 // Show all vwindows
2381 //      if(session->show_vwindow) {
2382 //              for(int j = 0; j < vwindows.size(); j++) {
2383 //                      VWindow *vwindow = vwindows[j];
2384 //                      if( !vwindow->is_running() ) continue;
2385 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2386 //                              __LINE__,
2387 //                              vwindow);
2388 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2389 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2390 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2391 //                      vwindow->gui->show_window();
2392 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2393 //                      vwindow->gui->unlock_window();
2394 //              }
2395 //      }
2396
2397
2398         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2399
2400         if(session->show_cwindow)
2401         {
2402                 cwindow->gui->lock_window("MWindow::create_objects 1");
2403                 cwindow->gui->show_window();
2404                 cwindow->gui->unlock_window();
2405         }
2406
2407         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2408         if(session->show_awindow)
2409         {
2410                 awindow->gui->lock_window("MWindow::create_objects 1");
2411                 awindow->gui->show_window();
2412                 awindow->gui->unlock_window();
2413         }
2414
2415         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2416         if(session->show_lwindow)
2417         {
2418                 lwindow->gui->lock_window("MWindow::create_objects 1");
2419                 lwindow->gui->show_window();
2420                 lwindow->gui->unlock_window();
2421         }
2422
2423         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2424                 __LINE__,
2425                 (int)timer.get_difference(),
2426                 gwindow->gui);
2427         if(session->show_gwindow)
2428         {
2429                 gwindow->gui->lock_window("MWindow::create_objects 1");
2430                 gwindow->gui->show_window();
2431                 gwindow->gui->unlock_window();
2432         }
2433
2434         if(debug) PRINT_TRACE
2435
2436         gui->lock_window("MWindow::create_objects 1");
2437         gui->mainmenu->load_defaults(defaults);
2438         gui->mainmenu->update_toggles(0);
2439         gui->update_patchbay();
2440         gui->draw_canvas(0, 0);
2441         gui->draw_cursor(1);
2442         gui->show_window();
2443         gui->raise_window();
2444         gui->unlock_window();
2445
2446         if(debug) PRINT_TRACE
2447
2448         if(preferences->use_tipwindow)
2449                 init_tipwindow();
2450         if(debug) PRINT_TRACE
2451
2452         gui->add_keyboard_listener(
2453                 (int (BC_WindowBase::*)(BC_WindowBase *))
2454                 &MWindowGUI::keyboard_listener);
2455
2456         hide_splash();
2457         init_shm();
2458         if(debug) PRINT_TRACE
2459
2460         BC_WindowBase::get_resources()->vframe_shm = 1;
2461 }
2462
2463
2464 void MWindow::show_splash()
2465 {
2466 #include "data/heroine_logo9_png.h"
2467         VFrame *frame = new VFramePng(heroine_logo9_png);
2468         BC_DisplayInfo dpyi;
2469         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2470         int rr = (rw < rh ? rw : rh) / 4;
2471         splash_window = new SplashGUI(frame, rr, rr);
2472         splash_window->create_objects();
2473 }
2474
2475 void MWindow::hide_splash()
2476 {
2477         if(splash_window)
2478                 delete splash_window;
2479         splash_window = 0;
2480 }
2481
2482
2483 void MWindow::start()
2484 {
2485 ENABLE_BUFFER
2486 //PRINT_TRACE
2487 //      vwindows[DEFAULT_VWINDOW]->start();
2488         awindow->start();
2489 //PRINT_TRACE
2490         cwindow->start();
2491 //PRINT_TRACE
2492         lwindow->start();
2493 //PRINT_TRACE
2494         gwindow->start();
2495 //PRINT_TRACE
2496 //      Thread::start();
2497 //PRINT_TRACE
2498         playback_3d->start();
2499 //PRINT_TRACE
2500 }
2501
2502 void MWindow::run()
2503 {
2504         run_lock->lock("MWindow::run");
2505         gui->run_window();
2506         stop_playback(1);
2507
2508         brender_lock->lock("MWindow::run 1");
2509         delete brender;         brender = 0;
2510         brender_lock->unlock();
2511
2512         interrupt_indexes();
2513         clean_indexes();
2514         save_defaults();
2515         run_lock->unlock();
2516 }
2517
2518 void MWindow::show_vwindow()
2519 {
2520         int total_running = 0;
2521         session->show_vwindow = 1;
2522
2523 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2524 // Raise all windows which are visible
2525         for(int j = 0; j < vwindows.size(); j++) {
2526                 VWindow *vwindow = vwindows[j];
2527                 if( !vwindow->is_running() ) continue;
2528                 vwindow->gui->lock_window("MWindow::show_vwindow");
2529                 vwindow->gui->show_window(0);
2530                 vwindow->gui->raise_window();
2531                 vwindow->gui->flush();
2532                 vwindow->gui->unlock_window();
2533                 total_running++;
2534         }
2535
2536 // If no windows visible
2537         if(!total_running)
2538         {
2539                 get_viewer(1, DEFAULT_VWINDOW);
2540         }
2541
2542         gui->mainmenu->show_vwindow->set_checked(1);
2543 }
2544
2545 void MWindow::show_awindow()
2546 {
2547         session->show_awindow = 1;
2548         awindow->gui->lock_window("MWindow::show_awindow");
2549         awindow->gui->show_window();
2550         awindow->gui->raise_window();
2551         awindow->gui->flush();
2552         awindow->gui->unlock_window();
2553         gui->mainmenu->show_awindow->set_checked(1);
2554 }
2555
2556 char *MWindow::get_cwindow_display()
2557 {
2558         char *x11_host = screens < 2 || session->window_config == 0 ?
2559                 session->a_x11_host : session->b_x11_host;
2560         return *x11_host ? x11_host : 0;
2561 }
2562
2563 void MWindow::show_cwindow()
2564 {
2565         session->show_cwindow = 1;
2566         cwindow->show_window();
2567         gui->mainmenu->show_cwindow->set_checked(1);
2568 }
2569
2570 void MWindow::show_gwindow()
2571 {
2572         session->show_gwindow = 1;
2573
2574         gwindow->gui->lock_window("MWindow::show_gwindow");
2575         gwindow->gui->show_window();
2576         gwindow->gui->raise_window();
2577         gwindow->gui->flush();
2578         gwindow->gui->unlock_window();
2579
2580         gui->mainmenu->show_gwindow->set_checked(1);
2581 }
2582 void MWindow::hide_gwindow()
2583 {
2584         session->show_gwindow = 0;
2585
2586         gwindow->gui->lock_window("MWindow::show_gwindow");
2587         gwindow->gui->hide_window();
2588         gwindow->gui->unlock_window();
2589 }
2590
2591 void MWindow::show_lwindow()
2592 {
2593         session->show_lwindow = 1;
2594         lwindow->gui->lock_window("MWindow::show_lwindow");
2595         lwindow->gui->show_window();
2596         lwindow->gui->raise_window();
2597         lwindow->gui->flush();
2598         lwindow->gui->unlock_window();
2599         gui->mainmenu->show_lwindow->set_checked(1);
2600 }
2601
2602 int MWindow::tile_windows(int window_config)
2603 {
2604         int need_reload = 0;
2605         int play_config = window_config==0 ? 0 : 1;
2606         edl->session->playback_config->load_defaults(defaults, play_config);
2607         session->default_window_positions(window_config);
2608         if( screens == 1 ) {
2609                 gui->default_positions();
2610                 sync_parameters(CHANGE_ALL);
2611         }
2612         else
2613                 need_reload = 1;
2614         return need_reload;
2615 }
2616
2617 void MWindow::toggle_loop_playback()
2618 {
2619         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2620         set_loop_boundaries();
2621         save_backup();
2622
2623         gui->draw_overlays(1);
2624         sync_parameters(CHANGE_PARAMS);
2625 }
2626
2627 //void MWindow::set_titles(int value)
2628 //{
2629 //      edl->session->show_titles = value;
2630 //      trackmovement(edl->local_session->track_start);
2631 //}
2632
2633 void MWindow::set_screens(int value)
2634 {
2635         screens = value;
2636 }
2637
2638 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2639 {
2640         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2641         edl->session->auto_keyframes = value;
2642         gui->mbuttons->edit_panel->keyframe->update(value);
2643         gui->flush();
2644         if(lock_mwindow) gui->unlock_window();
2645
2646         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2647         cwindow->gui->edit_panel->keyframe->update(value);
2648         cwindow->gui->flush();
2649         if(lock_cwindow) cwindow->gui->unlock_window();
2650 }
2651
2652 void MWindow::set_auto_visibility(Autos *autos, int value)
2653 {
2654         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2655                 edl->session->auto_conf->plugins = value;
2656         else if( autos->autoidx >= 0 )
2657                 edl->session->auto_conf->autos[autos->autoidx] = value;
2658         else
2659                 return;
2660
2661         gui->update(0, 1, 0, 0, 0, 0, 0);
2662         gui->mainmenu->update_toggles(1);
2663         gui->unlock_window();
2664         gwindow->gui->update_toggles(1);
2665         gui->lock_window("MWindow::set_auto_visibility");
2666 }
2667
2668 void MWindow::set_keyframe_type(int mode)
2669 {
2670         gui->lock_window("MWindow::set_keyframe_type");
2671         edl->local_session->floatauto_type = mode;
2672         gui->mainmenu->update_toggles(0);
2673         gui->unlock_window();
2674 }
2675
2676 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
2677 {
2678         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
2679         edl->session->editing_mode = new_editing_mode;
2680         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
2681         gui->mbuttons->edit_panel->update();
2682         gui->set_editing_mode(1);
2683         if(lock_mwindow) gui->unlock_window();
2684
2685
2686         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
2687         cwindow->gui->edit_panel->update();
2688         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
2689         if(lock_cwindow) cwindow->gui->unlock_window();
2690         return 0;
2691 }
2692
2693 void MWindow::toggle_editing_mode()
2694 {
2695         int mode = edl->session->editing_mode;
2696         if( mode == EDITING_ARROW )
2697                 set_editing_mode(EDITING_IBEAM, 0, 1);
2698         else
2699                 set_editing_mode(EDITING_ARROW, 0, 1);
2700 }
2701
2702
2703 void MWindow::set_labels_follow_edits(int value)
2704 {
2705         gui->lock_window("MWindow::set_labels_follow_edits");
2706         edl->session->labels_follow_edits = value;
2707         gui->mbuttons->edit_panel->locklabels->update(value);
2708         gui->mainmenu->labels_follow_edits->set_checked(value);
2709         gui->flush();
2710         gui->unlock_window();
2711 }
2712
2713 void MWindow::sync_parameters(int change_type)
2714 {
2715         if( in_destructor ) return;
2716
2717 // Sync engines which are playing back
2718         if(cwindow->playback_engine->is_playing_back)
2719         {
2720                 if(change_type == CHANGE_PARAMS)
2721                 {
2722 // TODO: block keyframes until synchronization is done
2723                         cwindow->playback_engine->sync_parameters(edl);
2724                 }
2725                 else
2726 // Stop and restart
2727                 {
2728                         int command = cwindow->playback_engine->command->command;
2729                         cwindow->playback_engine->que->send_command(STOP,
2730                                 CHANGE_NONE,
2731                                 0,
2732                                 0);
2733 // Waiting for tracking to finish would make the restart position more
2734 // accurate but it can't lock the window to stop tracking for some reason.
2735 // Not waiting for tracking gives a faster response but restart position is
2736 // only as accurate as the last tracking update.
2737                         cwindow->playback_engine->interrupt_playback(0);
2738                         cwindow->playback_engine->que->send_command(command,
2739                                         change_type,
2740                                         edl,
2741                                         1,
2742                                         0);
2743                 }
2744         }
2745         else
2746         {
2747                 cwindow->refresh_frame(change_type);
2748         }
2749 }
2750
2751 void MWindow::age_caches()
2752 {
2753 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
2754 // __LINE__,
2755 // preferences->cache_size,
2756 // audio_cache->get_memory_usage(1),
2757 // video_cache->get_memory_usage(1),
2758 // frame_cache->get_memory_usage(),
2759 // wave_cache->get_memory_usage(),
2760 // memory_usage);
2761         frame_cache->age_cache(512);
2762         wave_cache->age_cache(8192);
2763
2764         int64_t memory_usage;
2765         int64_t prev_memory_usage = 0;
2766         int result = 0;
2767         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
2768         while( !result && prev_memory_usage !=
2769                 (memory_usage=video_cache->get_memory_usage(1)) &&
2770                 memory_usage > video_size ) {
2771                 video_cache->delete_oldest();
2772                 prev_memory_usage = memory_usage;
2773         }
2774
2775         prev_memory_usage = 0;
2776         result = 0;
2777         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
2778         while( !result && prev_memory_usage !=
2779                 (memory_usage=audio_cache->get_memory_usage(1)) &&
2780                 memory_usage > audio_size ) {
2781                 audio_cache->delete_oldest();
2782                 prev_memory_usage = memory_usage;
2783         }
2784 }
2785
2786 void MWindow::reset_android_remote()
2787 {
2788         gui->use_android_remote(preferences->android_remote);
2789 }
2790
2791
2792 void MWindow::show_keyframe_gui(Plugin *plugin)
2793 {
2794         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
2795 // Find existing thread
2796         for(int i = 0; i < keyframe_threads->size(); i++)
2797         {
2798                 if(keyframe_threads->get(i)->plugin == plugin)
2799                 {
2800                         keyframe_threads->get(i)->start_window(plugin, 0);
2801                         keyframe_gui_lock->unlock();
2802                         return;
2803                 }
2804         }
2805
2806 // Find unused thread
2807         for(int i = 0; i < keyframe_threads->size(); i++)
2808         {
2809                 if(!keyframe_threads->get(i)->plugin)
2810                 {
2811                         keyframe_threads->get(i)->start_window(plugin, 0);
2812                         keyframe_gui_lock->unlock();
2813                         return;
2814                 }
2815         }
2816
2817 // Create new thread
2818         KeyFrameThread *thread = new KeyFrameThread(this);
2819         keyframe_threads->append(thread);
2820         thread->start_window(plugin, 0);
2821
2822         keyframe_gui_lock->unlock();
2823 }
2824
2825
2826
2827
2828
2829 void MWindow::show_plugin(Plugin *plugin)
2830 {
2831         int done = 0;
2832
2833 SET_TRACE
2834 // Remove previously deleted plugin GUIs
2835         dead_plugin_lock->lock("MWindow::show_plugin");
2836         dead_plugins->remove_all_objects();
2837         dead_plugin_lock->unlock();
2838
2839 //printf("MWindow::show_plugin %d\n", __LINE__);
2840 SET_TRACE
2841
2842
2843         plugin_gui_lock->lock("MWindow::show_plugin");
2844         for(int i = 0; i < plugin_guis->total; i++)
2845         {
2846 // Pointer comparison
2847                 if(plugin_guis->get(i)->plugin == plugin)
2848                 {
2849                         plugin_guis->get(i)->raise_window();
2850                         done = 1;
2851                         break;
2852                 }
2853         }
2854 SET_TRACE
2855
2856 //printf("MWindow::show_plugin 1\n");
2857         if( !done && !plugin->track ) {
2858                 printf("MWindow::show_plugin track not defined.\n");
2859                 done = 1;
2860         }
2861         if( !done ) {
2862                 PluginServer *server = scan_plugindb(plugin->title,
2863                         plugin->track->data_type);
2864
2865 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
2866                 if(server && server->uses_gui)
2867                 {
2868                         PluginServer *gui = new PluginServer(*server);
2869                         plugin_guis->append(gui);
2870 // Needs mwindow to do GUI
2871                         gui->set_mwindow(this);
2872                         gui->open_plugin(0, preferences, edl, plugin);
2873                         plugin->show = 1;
2874                         gui->show_gui();
2875                 }
2876         }
2877         plugin_gui_lock->unlock();
2878 //printf("MWindow::show_plugin %d\n", __LINE__);
2879 SET_TRACE
2880 //sleep(1);
2881 //printf("MWindow::show_plugin 2\n");
2882 }
2883
2884 void MWindow::hide_plugin(Plugin *plugin, int lock)
2885 {
2886         plugin->show = 0;
2887 // Update the toggle
2888         gui->lock_window("MWindow::hide_plugin");
2889         gui->update(0, 1, 0, 0, 0, 0, 0);
2890         gui->unlock_window();
2891
2892         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
2893         for(int i = 0; i < plugin_guis->total; i++)
2894         {
2895                 if(plugin_guis->get(i)->plugin == plugin)
2896                 {
2897                         PluginServer *ptr = plugin_guis->get(i);
2898                         plugin_guis->remove(ptr);
2899                         if(lock) plugin_gui_lock->unlock();
2900 // Last command executed in client side close
2901 // Schedule for deletion
2902                         ptr->hide_gui();
2903                         delete_plugin(ptr);
2904 //sleep(1);
2905                         return;
2906                 }
2907         }
2908         if(lock) plugin_gui_lock->unlock();
2909 }
2910
2911 void MWindow::delete_plugin(PluginServer *plugin)
2912 {
2913         dead_plugin_lock->lock("MWindow::delete_plugin");
2914         dead_plugins->append(plugin);
2915         dead_plugin_lock->unlock();
2916 }
2917
2918 void MWindow::hide_plugins()
2919 {
2920         plugin_gui_lock->lock("MWindow::hide_plugins 1");
2921         while(plugin_guis->size())
2922         {
2923                 PluginServer *ptr = plugin_guis->get(0);
2924                 plugin_guis->remove(ptr);
2925                 plugin_gui_lock->unlock();
2926 // Last command executed in client side close
2927 // Schedule for deletion
2928                 ptr->hide_gui();
2929                 delete_plugin(ptr);
2930                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
2931         }
2932         plugin_gui_lock->unlock();
2933
2934         hide_keyframe_guis();
2935 }
2936
2937 void MWindow::hide_keyframe_guis()
2938 {
2939         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
2940         for(int i = 0; i < keyframe_threads->size(); i++)
2941         {
2942                 keyframe_threads->get(i)->close_window();
2943         }
2944         keyframe_gui_lock->unlock();
2945 }
2946
2947 void MWindow::hide_keyframe_gui(Plugin *plugin)
2948 {
2949         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
2950         for(int i = 0; i < keyframe_threads->size(); i++)
2951         {
2952                 if(keyframe_threads->get(i)->plugin == plugin)
2953                 {
2954                         keyframe_threads->get(i)->close_window();
2955                         break;
2956                 }
2957         }
2958         keyframe_gui_lock->unlock();
2959 }
2960
2961 void MWindow::update_keyframe_guis()
2962 {
2963 // Send new configuration to keyframe GUI's
2964         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
2965         for(int i = 0; i < keyframe_threads->size(); i++)
2966         {
2967                 KeyFrameThread *ptr = keyframe_threads->get(i);
2968                 if(edl->tracks->plugin_exists(ptr->plugin))
2969                         ptr->update_gui(1);
2970                 else
2971                 {
2972                         ptr->close_window();
2973                 }
2974         }
2975         keyframe_gui_lock->unlock();
2976 }
2977
2978 void MWindow::update_plugin_guis(int do_keyframe_guis)
2979 {
2980 // Send new configuration to plugin GUI's
2981         plugin_gui_lock->lock("MWindow::update_plugin_guis");
2982
2983         for(int i = 0; i < plugin_guis->size(); i++)
2984         {
2985                 PluginServer *ptr = plugin_guis->get(i);
2986                 if(edl->tracks->plugin_exists(ptr->plugin))
2987                         ptr->update_gui();
2988                 else
2989                 {
2990 // Schedule for deletion if no plugin
2991                         plugin_guis->remove_number(i);
2992                         i--;
2993
2994                         ptr->hide_gui();
2995                         delete_plugin(ptr);
2996                 }
2997         }
2998
2999
3000 // Change plugin variable if not visible
3001         Track *track = edl->tracks->first;
3002         while(track)
3003         {
3004                 for(int i = 0; i < track->plugin_set.size(); i++)
3005                 {
3006                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3007                         while(plugin)
3008                         {
3009                                 int got_it = 0;
3010                                 for(int i = 0; i < plugin_guis->size(); i++)
3011                                 {
3012                                         PluginServer *server = plugin_guis->get(i);
3013                                         if(server->plugin == plugin)
3014                                         {
3015                                                 got_it = 1;
3016                                                 break;
3017                                         }
3018                                 }
3019
3020                                 if(!got_it) plugin->show = 0;
3021
3022                                 plugin = (Plugin*)plugin->next;
3023                         }
3024                 }
3025
3026                 track = track->next;
3027         }
3028
3029         plugin_gui_lock->unlock();
3030
3031
3032         if(do_keyframe_guis) update_keyframe_guis();
3033 }
3034
3035 int MWindow::plugin_gui_open(Plugin *plugin)
3036 {
3037         int result = 0;
3038         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3039         for(int i = 0; i < plugin_guis->total; i++)
3040         {
3041                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3042                 {
3043                         result = 1;
3044                         break;
3045                 }
3046         }
3047         plugin_gui_lock->unlock();
3048         return result;
3049 }
3050
3051 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3052 {
3053         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3054         for(int i = 0; i < plugin_guis->total; i++)
3055         {
3056                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3057                 {
3058                         plugin_guis->get(i)->render_gui(data);
3059                         break;
3060                 }
3061         }
3062         plugin_gui_lock->unlock();
3063 }
3064
3065 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3066 {
3067         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3068         for(int i = 0; i < plugin_guis->total; i++)
3069         {
3070                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3071                 {
3072                         plugin_guis->get(i)->render_gui(data, size);
3073                         break;
3074                 }
3075         }
3076         plugin_gui_lock->unlock();
3077 }
3078
3079
3080 void MWindow::update_plugin_states()
3081 {
3082         plugin_gui_lock->lock("MWindow::update_plugin_states");
3083         for(int i = 0; i < plugin_guis->total; i++)
3084         {
3085                 int result = 0;
3086 // Get a plugin GUI
3087                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
3088                 PluginServer *src_plugingui = plugin_guis->get(i);
3089
3090 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
3091                 for(Track *track = edl->tracks->first;
3092                         track && !result;
3093                         track = track->next)
3094                 {
3095                         for(int j = 0;
3096                                 j < track->plugin_set.total && !result;
3097                                 j++)
3098                         {
3099                                 PluginSet *plugin_set = track->plugin_set[j];
3100                                 for(Plugin *plugin = (Plugin*)plugin_set->first;
3101                                         plugin && !result;
3102                                         plugin = (Plugin*)plugin->next)
3103                                 {
3104                                         if(plugin == src_plugin &&
3105                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
3106                                 }
3107                         }
3108                 }
3109
3110
3111 // Doesn't exist anymore
3112                 if(!result)
3113                 {
3114                         hide_plugin(src_plugin, 0);
3115                         i--;
3116                 }
3117         }
3118         plugin_gui_lock->unlock();
3119 }
3120
3121
3122 void MWindow::update_plugin_titles()
3123 {
3124         for(int i = 0; i < plugin_guis->total; i++)
3125         {
3126                 plugin_guis->get(i)->update_title();
3127         }
3128 }
3129
3130 int MWindow::asset_to_edl(EDL *new_edl,
3131         Asset *new_asset,
3132         RecordLabels *labels)
3133 {
3134 const int debug = 0;
3135 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3136 __LINE__,
3137 new_asset->layers);
3138 // Keep frame rate, sample rate, and output size unchanged.
3139 // These parameters would revert the project if VWindow displayed an asset
3140 // of different size than the project.
3141         if(new_asset->video_data)
3142         {
3143                 new_edl->session->video_tracks = new_asset->layers;
3144         }
3145         else
3146                 new_edl->session->video_tracks = 0;
3147
3148 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3149
3150
3151
3152
3153
3154         if(new_asset->audio_data)
3155         {
3156                 new_edl->session->audio_tracks = new_asset->channels;
3157         }
3158         else
3159                 new_edl->session->audio_tracks = 0;
3160 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3161
3162 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3163         new_edl->create_default_tracks();
3164 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3165 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3166
3167
3168
3169 //printf("MWindow::asset_to_edl 3\n");
3170         new_edl->insert_asset(new_asset,
3171                 0,
3172                 0,
3173                 0,
3174                 labels);
3175 //printf("MWindow::asset_to_edl 3\n");
3176 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3177
3178 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3179         if(edl->session->cursor_on_frames)
3180         {
3181                 double length = new_edl->tracks->total_length();
3182                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3183                 new_edl->tracks->clear(length, edl_length, 1, 1);
3184         }
3185
3186
3187
3188
3189         char string[BCTEXTLEN];
3190         FileSystem fs;
3191         fs.extract_name(string, new_asset->path);
3192 //printf("MWindow::asset_to_edl 3\n");
3193
3194         strcpy(new_edl->local_session->clip_title, string);
3195 //printf("MWindow::asset_to_edl 4 %s\n", string);
3196 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3197
3198         return 0;
3199 }
3200
3201 int MWindow::edl_to_nested(EDL *new_edl,
3202         EDL *nested_edl)
3203 {
3204
3205 // Keep frame rate, sample rate, and output size unchanged.
3206 // These parameters would revert the project if VWindow displayed an asset
3207 // of different size than the project.
3208
3209
3210
3211 // Nest all video & audio outputs
3212         new_edl->session->video_tracks = 1;
3213         new_edl->session->audio_tracks = nested_edl->session->audio_channels;
3214         new_edl->create_default_tracks();
3215
3216
3217
3218         new_edl->insert_asset(0,
3219                 nested_edl,
3220                 0,
3221                 0,
3222                 0);
3223
3224         char string[BCTEXTLEN];
3225         FileSystem fs;
3226         fs.extract_name(string, nested_edl->path);
3227 //printf("MWindow::edl_to_nested %p %s\n", nested_edl, nested_edl->path);
3228
3229         strcpy(new_edl->local_session->clip_title, string);
3230
3231         return 0;
3232 }
3233
3234 // Reset everything after a load.
3235 void MWindow::update_project(int load_mode)
3236 {
3237         const int debug = 0;
3238
3239         if(debug) PRINT_TRACE
3240         init_brender();
3241         edl->tracks->update_y_pixels(theme);
3242
3243         if(debug) PRINT_TRACE
3244
3245         if(load_mode == LOADMODE_REPLACE ||
3246                 load_mode == LOADMODE_REPLACE_CONCATENATE)
3247         {
3248                 gui->load_panes();
3249         }
3250
3251         gui->update(1, 1, 1, 1, 1, 1, 1);
3252         if(debug) PRINT_TRACE
3253         gui->unlock_window();
3254
3255         cwindow->gui->lock_window("MWindow::update_project 1");
3256         cwindow->update(0, 0, 1, 1, 1);
3257         cwindow->gui->unlock_window();
3258
3259         if(debug) PRINT_TRACE
3260
3261 // Close all the vwindows
3262         if( load_mode == LOADMODE_REPLACE ||
3263             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3264                 if(debug) PRINT_TRACE
3265                 int first_vwindow = 0;
3266                 if(session->show_vwindow) first_vwindow = 1;
3267 // Change visible windows to no source
3268                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3269                         VWindow *vwindow = vwindows[i];
3270                         if( !vwindow->is_running() ) continue;
3271                         vwindow->change_source(-1);
3272                 }
3273
3274 // Close remaining windows
3275                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3276                         VWindow *vwindow = vwindows[i];
3277                         if( !vwindow->is_running() ) continue;
3278                         vwindow->close_window();
3279                 }
3280                 if(debug) PRINT_TRACE
3281                 select_zwindow(0);
3282                 close_mixers();
3283
3284                 for( int i=0; i<edl->mixers.size(); ++i ) {
3285                         Mixer *mixer = edl->mixers[i];
3286                         ZWindow *zwindow = get_mixer(mixer);
3287                         zwindow->set_title(mixer->title);
3288                         zwindow->start();
3289                 }
3290         }
3291         else {
3292                 if(vwindows.size()) {
3293                         VWindow *vwindow = vwindows[DEFAULT_VWINDOW];
3294                         if( vwindow->is_running() ) {
3295                                 vwindow->gui->lock_window("MWindow::update_project");
3296                                 vwindow->update(1);
3297                                 vwindow->gui->unlock_window();
3298                         }
3299                 }
3300         }
3301
3302         if(debug) PRINT_TRACE
3303         cwindow->gui->lock_window("MWindow::update_project 2");
3304         cwindow->gui->timebar->update(0);
3305         cwindow->gui->unlock_window();
3306
3307         if(debug) PRINT_TRACE
3308         cwindow->refresh_frame(CHANGE_ALL);
3309
3310         awindow->gui->async_update_assets();
3311         if(debug) PRINT_TRACE
3312
3313         gui->lock_window("MWindow::update_project");
3314         gui->update_mixers(0, 0);
3315         gui->flush();
3316         if(debug) PRINT_TRACE
3317 }
3318
3319 void MWindow::remove_indexfile(Indexable *indexable)
3320 {
3321         if( !indexable->is_asset ) return;
3322         Asset *asset = (Asset *)indexable;
3323 // Erase file
3324         IndexFile::delete_index(preferences, asset, ".toc");
3325         IndexFile::delete_index(preferences, asset, ".idx");
3326         IndexFile::delete_index(preferences, asset, ".mkr");
3327 }
3328
3329 void MWindow::rebuild_indices()
3330 {
3331         for(int i = 0; i < session->drag_assets->total; i++)
3332         {
3333                 Indexable *indexable = session->drag_assets->get(i);
3334 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3335                 remove_indexfile(indexable);
3336 // Schedule index build
3337                 IndexState *index_state = indexable->index_state;
3338                 index_state->index_status = INDEX_NOTTESTED;
3339                 if( indexable->is_asset ) {
3340                         Asset *asset = (Asset *)indexable;
3341                         if( asset->format != FILE_PCM ) {
3342                                 asset->format = FILE_UNKNOWN;
3343                                 asset->reset_audio();
3344                         }
3345                         asset->reset_video();
3346                         remove_asset_from_caches(asset);
3347 //                      File file; // re-probe the asset
3348 //                      file.open_file(preferences, asset, 1, 0);
3349                 }
3350                 mainindexes->add_next_asset(0, indexable);
3351         }
3352         mainindexes->start_build();
3353 }
3354
3355
3356 void MWindow::save_backup()
3357 {
3358         FileXML file;
3359         edl->optimize();
3360         edl->set_path(session->filename);
3361         char backup_path[BCTEXTLEN];
3362         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3363                 File::get_config_path(), BACKUP_FILE);
3364         edl->save_xml(&file, backup_path, 0, 0);
3365         file.terminate_string();
3366         FileSystem fs;
3367         fs.complete_path(backup_path);
3368
3369         if(file.write_to_file(backup_path))
3370         {
3371                 char string2[256];
3372                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
3373                 gui->show_message(string2);
3374         }
3375 }
3376
3377 void MWindow::load_backup()
3378 {
3379         ArrayList<char*> path_list;
3380         path_list.set_array_delete();
3381         char *out_path;
3382         char backup_path[BCTEXTLEN];
3383         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3384                 File::get_config_path(), BACKUP_FILE);
3385         FileSystem fs;
3386         fs.complete_path(backup_path);
3387
3388         path_list.append(out_path = new char[strlen(backup_path) + 1]);
3389         strcpy(out_path, backup_path);
3390
3391         load_filenames(&path_list, LOADMODE_REPLACE, 0);
3392         edl->local_session->clip_title[0] = 0;
3393 // This is unique to backups since the path of the backup is different than the
3394 // path of the project.
3395         set_filename(edl->path);
3396         path_list.remove_all_objects();
3397         save_backup();
3398 }
3399
3400 static inline int gcd(int m, int n)
3401 {
3402         int r;
3403         if( m < n ) { r = m;  m = n;  n = r; }
3404         while( (r = m % n) != 0 ) { m = n;  n = r; }
3405         return n;
3406 }
3407
3408 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
3409 {
3410         w = 1;  h = 1;
3411         if(!width || !height) return 1;
3412         if( width == 720 && (height == 480 || height == 576) ) {
3413                 w = 4;  h = 3;  return 0; // for NTSC and PAL
3414         }
3415         double ar = (double)width / height;
3416 // square-ish pixels
3417         if( EQUIV(ar, 1.0000) ) return 0;
3418         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
3419         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
3420         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
3421         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
3422         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
3423         int ww = width, hh = height;
3424         // numerator, denominator must be under mx
3425         int mx = 255, n = gcd(ww, hh);
3426         if( n > 1 ) { ww /= n; hh /= n; }
3427         // search near height in case extra/missing lines
3428         if( ww >= mx || hh >= mx ) {
3429                 double err = height;  // +/- 2 percent height
3430                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
3431                         int iw = width, ih = height+i;
3432                         if( (n=gcd(iw, ih)) > 1 ) {
3433                                 int u = iw/n;  if( u >= mx ) continue;
3434                                 int v = ih/n;  if( v >= mx ) continue;
3435                                 double r = (double) u/v, er = fabs(ar-r);
3436                                 if( er >= err ) continue;
3437                                 err = er;  ww = u;  hh = v;
3438                         }
3439                 }
3440         }
3441
3442         w = ww;  h = hh;
3443         return 0;
3444 }
3445
3446 void MWindow::reset_caches()
3447 {
3448         frame_cache->remove_all();
3449         wave_cache->remove_all();
3450         audio_cache->remove_all();
3451         video_cache->remove_all();
3452         if( cwindow->playback_engine ) {
3453                 if( cwindow->playback_engine->audio_cache )
3454                         cwindow->playback_engine->audio_cache->remove_all();
3455                 if( cwindow->playback_engine->video_cache )
3456                         cwindow->playback_engine->video_cache->remove_all();
3457         }
3458         for(int i = 0; i < vwindows.size(); i++) {
3459                 VWindow *vwindow = vwindows[i];
3460                 if( !vwindow->is_running() ) continue;
3461                 if( !vwindow->playback_engine ) continue;
3462                 if( vwindow->playback_engine->audio_cache )
3463                         vwindow->playback_engine->audio_cache->remove_all();
3464                 if( vwindow->playback_engine->video_cache )
3465                         vwindow->playback_engine->video_cache->remove_all();
3466         }
3467 }
3468
3469 void MWindow::remove_asset_from_caches(Asset *asset)
3470 {
3471         frame_cache->remove_asset(asset);
3472         wave_cache->remove_asset(asset);
3473         audio_cache->delete_entry(asset);
3474         video_cache->delete_entry(asset);
3475         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3476                 cwindow->playback_engine->audio_cache->delete_entry(asset);
3477         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3478                 cwindow->playback_engine->video_cache->delete_entry(asset);
3479         for(int i = 0; i < vwindows.size(); i++) {
3480                 VWindow *vwindow = vwindows[i];
3481                 if( !vwindow->is_running() ) continue;
3482                 if( !vwindow->playback_engine ) continue;
3483                 if( vwindow->playback_engine->audio_cache )
3484                         vwindow->playback_engine->audio_cache->delete_entry(asset);
3485                 if( vwindow->playback_engine->video_cache )
3486                         vwindow->playback_engine->video_cache->delete_entry(asset);
3487         }
3488 }
3489
3490
3491 void MWindow::remove_assets_from_project(int push_undo, int redraw,
3492                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
3493 {
3494         for(int i = 0; i < drag_assets->total; i++) {
3495                 Indexable *indexable = drag_assets->get(i);
3496                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
3497         }
3498
3499 // Remove from VWindow.
3500         for(int i = 0; i < session->drag_clips->total; i++) {
3501                 for(int j = 0; j < vwindows.size(); j++) {
3502                         VWindow *vwindow = vwindows[j];
3503                         if( !vwindow->is_running() ) continue;
3504                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
3505                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
3506                                 vwindow->delete_source(1, 1);
3507                                 vwindow->gui->unlock_window();
3508                         }
3509                 }
3510         }
3511
3512         for(int i = 0; i < drag_assets->size(); i++) {
3513                 for(int j = 0; j < vwindows.size(); j++) {
3514                         VWindow *vwindow = vwindows[j];
3515                         if( !vwindow->is_running() ) continue;
3516                         if(drag_assets->get(i) == vwindow->get_source()) {
3517                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
3518                                 vwindow->delete_source(1, 1);
3519                                 vwindow->gui->unlock_window();
3520                         }
3521                 }
3522         }
3523
3524         for(int i = 0; i < drag_assets->size(); i++) {
3525                 Indexable *indexable = drag_assets->get(i);
3526                 remove_indexfile(indexable);
3527         }
3528
3529 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3530         if(push_undo) undo->update_undo_before();
3531         if(drag_assets) edl->remove_from_project(drag_assets);
3532         if(drag_clips) edl->remove_from_project(drag_clips);
3533         if(redraw) save_backup();
3534         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
3535         if(redraw) {
3536                 restart_brender();
3537
3538                 gui->lock_window("MWindow::remove_assets_from_project 3");
3539                 gui->update(1, 1, 1, 1, 0, 1, 0);
3540                 gui->unlock_window();
3541
3542         // Removes from playback here
3543                 sync_parameters(CHANGE_ALL);
3544         }
3545
3546         awindow->gui->async_update_assets();
3547 }
3548
3549 void MWindow::remove_assets_from_disk()
3550 {
3551 // Remove from disk
3552         for(int i = 0; i < session->drag_assets->total; i++)
3553         {
3554                 remove(session->drag_assets->get(i)->path);
3555         }
3556
3557         remove_assets_from_project(1,
3558                 1,
3559                 session->drag_assets,
3560                 session->drag_clips);
3561 }
3562
3563 void MWindow::dump_plugins(FILE *fp)
3564 {
3565         if( !plugindb ) return;
3566         for(int i = 0; i < plugindb->total; i++)
3567         {
3568                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
3569                         " synth=%d transition=%d theme=%d %s\n",
3570                         plugindb->get(i)->plugin_type,
3571                         plugindb->get(i)->audio,
3572                         plugindb->get(i)->video,
3573                         plugindb->get(i)->realtime,
3574                         plugindb->get(i)->multichannel,
3575                         plugindb->get(i)->get_synthesis(),
3576                         plugindb->get(i)->transition,
3577                         plugindb->get(i)->theme,
3578                         plugindb->get(i)->title);
3579         }
3580 }
3581
3582 void MWindow::dump_edl(FILE *fp)
3583 {
3584         if( !edl ) return;
3585         edl->dump(fp);
3586 }
3587
3588 void MWindow::dump_undo(FILE *fp)
3589 {
3590         if( !undo ) return;
3591         undo->dump(fp);
3592 }
3593
3594 void MWindow::dump_exe(FILE *fp)
3595 {
3596         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
3597         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
3598
3599         int ret = -1, n = 100;
3600         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
3601                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
3602                 ret = 0;
3603         }
3604         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
3605
3606         struct stat st;
3607         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
3608         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
3609         struct tm *tm = localtime(&st.st_mtime);
3610         char mtime[256];
3611         strftime(mtime, sizeof(mtime), "%F %T", tm);
3612         fprintf(fp,"mtime: %s\n", mtime);
3613 #if 0
3614 // people hit ctl-c waiting for this
3615         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
3616         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
3617         uint8_t *bfr = 0;
3618         int64_t bfrsz = 0;
3619         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
3620         int64_t maxsz = 1024*pagsz;
3621         int64_t size = st.st_size, pos = 0;
3622         SHA1 sha1;
3623         while( (bfrsz = size-pos) > 0 ) {
3624                 if( bfrsz > maxsz ) bfrsz = maxsz;
3625                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
3626                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
3627                 if( bfr == MAP_FAILED ) break;
3628                 sha1.addBytes(bfr, bfrsz);
3629                 munmap(bfr, bfrsz);
3630                 pos += bfrsz;
3631         }
3632         close(fd);
3633         ret = pos < size ? EIO : 0;
3634         fprintf(fp, "SHA1: ");
3635         uint8_t digest[20];  sha1.computeHash(digest);
3636         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
3637         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
3638         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
3639 #endif
3640         fprintf(fp, "\n");
3641 }
3642
3643 void MWindow::trap_hook(FILE *fp, void *vp)
3644 {
3645         MWindow *mwindow = (MWindow *)vp;
3646 //      fprintf(fp, "\nPLUGINS:\n");
3647 //      mwindow->dump_plugins(fp);
3648         fprintf(fp, "\nEDL:\n");
3649         mwindow->dump_edl(fp);
3650         fprintf(fp, "\nUNDO:\n");
3651         mwindow->dump_undo(fp);
3652         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
3653         mwindow->dump_exe(fp);
3654 }
3655
3656
3657
3658
3659
3660
3661 int MWindow::save_defaults()
3662 {
3663         gui->save_defaults(defaults);
3664         edl->save_defaults(defaults);
3665         session->save_defaults(defaults);
3666         preferences->save_defaults(defaults);
3667
3668         for(int i = 0; i < plugin_guis->total; i++)
3669         {
3670 // Pointer comparison
3671                 plugin_guis->get(i)->save_defaults();
3672         }
3673         awindow->save_defaults(defaults);
3674
3675         defaults->save();
3676         return 0;
3677 }
3678
3679 int MWindow::run_script(FileXML *script)
3680 {
3681         int result = 0, result2 = 0;
3682         while(!result && !result2)
3683         {
3684                 result = script->read_tag();
3685                 if(!result)
3686                 {
3687                         if(script->tag.title_is("new_project"))
3688                         {
3689 // Run new in immediate mode.
3690 //                              gui->mainmenu->new_project->run_script(script);
3691                         }
3692                         else
3693                         if(script->tag.title_is("record"))
3694                         {
3695 // Run record as a thread.  It is a terminal command.
3696                                 ;
3697 // Will read the complete scipt file without letting record read it if not
3698 // terminated.
3699                                 result2 = 1;
3700                         }
3701                         else
3702                         {
3703                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
3704                         }
3705                 }
3706         }
3707         return result2;
3708 }
3709
3710 // ================================= synchronization
3711
3712
3713 int MWindow::interrupt_indexes()
3714 {
3715         mainprogress->cancelled = 1;
3716         mainindexes->interrupt_build();
3717         return 0;
3718 }
3719
3720
3721
3722 void MWindow::next_time_format()
3723 {
3724         switch(edl->session->time_format)
3725         {
3726                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
3727                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
3728                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3729                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
3730                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
3731                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
3732                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
3733         }
3734
3735         time_format_common();
3736 }
3737
3738 void MWindow::prev_time_format()
3739 {
3740         switch(edl->session->time_format)
3741         {
3742                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
3743                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
3744                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
3745                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3746                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
3747                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
3748                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
3749         }
3750
3751         time_format_common();
3752 }
3753
3754 void MWindow::time_format_common()
3755 {
3756         gui->lock_window("MWindow::next_time_format");
3757         gui->redraw_time_dependancies();
3758
3759
3760         char string[BCTEXTLEN], string2[BCTEXTLEN];
3761         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
3762         gui->show_message(string);
3763         gui->flush();
3764         gui->unlock_window();
3765 }
3766
3767
3768 int MWindow::set_filename(const char *filename)
3769 {
3770         if( filename != session->filename )
3771                 strcpy(session->filename, filename);
3772         if( filename != edl->path )
3773                 strcpy(edl->path, filename);
3774
3775         if(gui)
3776         {
3777                 if(filename[0] == 0)
3778                 {
3779                         gui->set_title(PROGRAM_NAME);
3780                 }
3781                 else
3782                 {
3783                         FileSystem dir;
3784                         char string[BCTEXTLEN], string2[BCTEXTLEN];
3785                         dir.extract_name(string, filename);
3786                         sprintf(string2, PROGRAM_NAME ": %s", string);
3787                         gui->set_title(string2);
3788                 }
3789         }
3790         return 0;
3791 }
3792
3793
3794
3795
3796
3797
3798
3799
3800 int MWindow::set_loop_boundaries()
3801 {
3802         double start = edl->local_session->get_selectionstart();
3803         double end = edl->local_session->get_selectionend();
3804
3805         if(start !=
3806                 end)
3807         {
3808                 ;
3809         }
3810         else
3811         if(edl->tracks->total_length())
3812         {
3813                 start = 0;
3814                 end = edl->tracks->total_length();
3815         }
3816         else
3817         {
3818                 start = end = 0;
3819         }
3820
3821         if(edl->local_session->loop_playback && start != end)
3822         {
3823                 edl->local_session->loop_start = start;
3824                 edl->local_session->loop_end = end;
3825         }
3826         return 0;
3827 }
3828
3829
3830
3831
3832
3833
3834
3835 int MWindow::reset_meters()
3836 {
3837         cwindow->gui->lock_window("MWindow::reset_meters 1");
3838         cwindow->gui->meters->reset_meters();
3839         cwindow->gui->unlock_window();
3840
3841         for(int j = 0; j < vwindows.size(); j++) {
3842                 VWindow *vwindow = vwindows[j];
3843                 if( !vwindow->is_running() ) continue;
3844                 vwindow->gui->lock_window("MWindow::reset_meters 2");
3845                 vwindow->gui->meters->reset_meters();
3846                 vwindow->gui->unlock_window();
3847         }
3848
3849         lwindow->gui->lock_window("MWindow::reset_meters 3");
3850         lwindow->gui->panel->reset_meters();
3851         lwindow->gui->unlock_window();
3852
3853         gui->lock_window("MWindow::reset_meters 4");
3854         gui->reset_meters();
3855         gui->unlock_window();
3856         return 0;
3857 }
3858
3859
3860 void MWindow::resync_guis()
3861 {
3862 // Update GUIs
3863         restart_brender();
3864         gui->lock_window("MWindow::resync_guis");
3865         gui->update(1, 1, 1, 1, 1, 1, 0);
3866         gui->unlock_window();
3867
3868         cwindow->gui->lock_window("MWindow::resync_guis");
3869         cwindow->gui->resize_event(cwindow->gui->get_w(),
3870                 cwindow->gui->get_h());
3871         int channels = edl->session->audio_channels;
3872         cwindow->gui->meters->set_meters(channels, 1);
3873         cwindow->gui->flush();
3874         cwindow->gui->unlock_window();
3875
3876         for(int i = 0; i < vwindows.size(); i++) {
3877                 VWindow *vwindow = vwindows[i];
3878                 if( !vwindow->is_running() ) continue;
3879                 vwindow->gui->lock_window("MWindow::resync_guis");
3880                 vwindow->gui->resize_event(vwindow->gui->get_w(),
3881                         vwindow->gui->get_h());
3882                 vwindow->gui->meters->set_meters(channels, 1);
3883                 vwindow->gui->flush();
3884                 vwindow->gui->unlock_window();
3885         }
3886
3887         lwindow->gui->lock_window("MWindow::resync_guis");
3888         lwindow->gui->panel->set_meters(channels, 1);
3889         lwindow->gui->flush();
3890         lwindow->gui->unlock_window();
3891
3892 // Warn user
3893         if(((edl->session->output_w % 4) ||
3894                 (edl->session->output_h % 4)) &&
3895                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
3896         {
3897                 MainError::show_error(
3898                         _("This project's dimensions are not multiples of 4 so\n"
3899                         "it can't be rendered by OpenGL."));
3900         }
3901
3902
3903 // Flash frame
3904         sync_parameters(CHANGE_ALL);
3905 }
3906
3907 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
3908 {
3909         File *file = new File;
3910         EDLSession *session = edl->session;
3911         double old_framerate = session->frame_rate;
3912         double old_samplerate = session->sample_rate;
3913         int old_auto_keyframes = session->auto_keyframes;
3914         session->auto_keyframes = 0;
3915         int result = file->open_file(preferences, asset, 1, 0);
3916         if( !result && delete_tracks > 0 )
3917                 undo->update_undo_before();
3918         int video_layers = asset->get_video_layers();
3919         if( !result && asset->video_data && vstream < video_layers ) {
3920                 // try to get asset up to date, may fail
3921                 file->select_video_stream(asset, vstream);
3922                 // either way use what was/is there.
3923                 double framerate = asset->get_frame_rate();
3924                 int width = asset->get_w();
3925                 int height = asset->get_h();
3926                 // must be multiple of 4 for opengl
3927                 width = (width+3) & ~3;  height = (height+3) & ~3;
3928                 int driver = session->playback_config->vconfig->driver;
3929                 int color_model = file->get_best_colormodel(asset, driver);
3930 //              color_model = BC_CModels::is_yuv(color_model) ?
3931 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
3932 //                      BC_CModels::is_float(color_model) ?
3933 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
3934 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
3935 // have alpha for now
3936                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
3937                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
3938                 session->color_model = color_model;
3939                 session->output_w = width;
3940                 session->output_h = height;
3941                 session->frame_rate = framerate;
3942                 // not, asset->actual_width/actual_height
3943                 asset->width = session->output_w;
3944                 asset->height = session->output_h;
3945                 asset->frame_rate = session->frame_rate;
3946                 create_aspect_ratio(session->aspect_w, session->aspect_h,
3947                         session->output_w, session->output_h);
3948                 Track *track = edl->tracks->first;
3949                 for( Track *next_track=0; track; track=next_track ) {
3950                         next_track = track->next;
3951                         if( track->data_type != TRACK_VIDEO ) continue;
3952                         if( delete_tracks ) {
3953                                 Edit *edit = track->edits->first;
3954                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
3955                                         next_edit = edit->next;
3956                                         if( edit->channel != vstream ||
3957                                             !edit->asset || !edit->asset->is_asset ||
3958                                             !asset->equivalent(*edit->asset,1,1,edl) )
3959                                                 delete edit;
3960                                 }
3961                         }
3962                         if( track->edits->first ) {
3963                                 track->track_w = edl->session->output_w;
3964                                 track->track_h = edl->session->output_h;
3965                         }
3966                         else if( delete_tracks )
3967                                 edl->tracks->delete_track(track);
3968                 }
3969                 edl->retrack();
3970                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
3971         }
3972         if( !result && asset->audio_data && asset->channels > 0 ) {
3973                 session->sample_rate = asset->get_sample_rate();
3974                 int64_t channel_mask = 0;
3975                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
3976                         file->get_audio_for_video(vstream, astream, channel_mask);
3977                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
3978                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
3979                 int channels = 0;
3980                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
3981                 if( channels < 1 ) channels = 1;
3982                 if( channels > 6 ) channels = 6;
3983                 session->audio_tracks = session->audio_channels = channels;
3984
3985                 int *achannel_positions = preferences->channel_positions[session->audio_channels-1];
3986                 memcpy(&session->achannel_positions, achannel_positions, sizeof(session->achannel_positions));
3987                 remap_audio(MWindow::AUDIO_1_TO_1);
3988
3989                 if( delete_tracks ) {
3990                         Track *track = edl->tracks->first;
3991                         for( Track *next_track=0; track; track=next_track ) {
3992                                 next_track = track->next;
3993                                 if( track->data_type != TRACK_AUDIO ) continue;
3994                                 Edit *edit = track->edits->first;
3995                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
3996                                         next_edit = edit->next;
3997                                         if( !((1<<edit->channel) & channel_mask) ||
3998                                             !edit->asset || !edit->asset->is_asset ||
3999                                             !asset->equivalent(*edit->asset,1,1,edl) )
4000                                                 delete edit;
4001                                 }
4002                                 if( !track->edits->first )
4003                                         edl->tracks->delete_track(track);
4004                         }
4005                 }
4006                 edl->rechannel();
4007                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
4008         }
4009         delete file;
4010         session->auto_keyframes = old_auto_keyframes;
4011         if( !result && delete_tracks > 0 ) {
4012                 save_backup();
4013                 undo->update_undo_after(_("select asset"), LOAD_ALL);
4014         }
4015         resync_guis();
4016         return result;
4017 }
4018
4019 int MWindow::select_asset(int vtrack, int delete_tracks)
4020 {
4021         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
4022         if( !track )
4023                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
4024         if( !track ) return 1;
4025         Edit *edit = track->edits->first;
4026         if( !edit ) return 1;
4027         Asset *asset = edit->asset;
4028         if( !asset || !asset->is_asset ) return 1;
4029         return select_asset(asset, edit->channel, 0, delete_tracks);
4030 }
4031
4032 void MWindow::dump_plugindb(FILE *fp)
4033 {
4034         if( !plugindb ) return;
4035         for(int i = 0; i < plugindb->total; i++)
4036                 plugindb->get(i)->dump(fp);
4037 }
4038
4039 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
4040 {
4041         Auto *current = 0;
4042         double unit_position = edl->local_session->get_selectionstart(1);
4043         unit_position = patch->track->to_units(unit_position, 0);
4044
4045         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
4046         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4047 }
4048
4049 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
4050 {
4051         Auto *current = 0;
4052         double unit_position = edl->local_session->get_selectionstart(1);
4053         unit_position = patch->track->to_units(unit_position, 0);
4054
4055         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
4056         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4057 }
4058
4059 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
4060 {
4061         Auto *current = 0;
4062         double unit_position = edl->local_session->get_selectionstart(1);
4063         unit_position = patch->track->to_units(unit_position, 0);
4064
4065         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
4066         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4067 }
4068
4069 PatchGUI *MWindow::get_patchgui(Track *track)
4070 {
4071         PatchGUI *patchgui = 0;
4072         TimelinePane **panes = gui->pane;
4073         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
4074                 if( !panes[i] ) continue;
4075                 PatchBay *patchbay = panes[i]->patchbay;
4076                 if( !patchbay ) continue;
4077                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
4078                         if( patchbay->patches.values[j]->track == track )
4079                                 patchgui = patchbay->patches.values[j];
4080                 }
4081         }
4082         return patchgui;
4083 }
4084