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