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