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