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