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