ffmpeg filter memory leak, cursor hopper fix, added leaker.C, misc fixes
[goodguy/history.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 "asset.h"
22 #include "assets.h"
23 #include "atrack.h"
24 #include "audioalsa.h"
25 #include "autos.h"
26 #include "awindowgui.h"
27 #include "awindow.h"
28 #include "batchrender.h"
29 #include "bcdisplayinfo.h"
30 #include "bcsignals.h"
31 #include "bctimer.h"
32 #include "bctrace.h"
33 #include "bdcreate.h"
34 #include "brender.h"
35 #include "cache.h"
36 #include "channel.h"
37 #include "channeldb.h"
38 #include "channelinfo.h"
39 #include "clip.h"
40 #include "bccmodels.h"
41 #include "commercials.h"
42 #include "cplayback.h"
43 #include "ctimebar.h"
44 #include "cwindowgui.h"
45 #include "cwindow.h"
46 #include "cwindowtool.h"
47 #include "bchash.h"
48 #include "devicedvbinput.inc"
49 #include "dvdcreate.h"
50 #include "editpanel.h"
51 #include "edl.h"
52 #include "edlsession.h"
53 #include "errorbox.h"
54 #include "fileformat.h"
55 #include "file.h"
56 #include "filesystem.h"
57 #include "filexml.h"
58 #include "floatautos.h"
59 #include "framecache.h"
60 #include "gwindow.h"
61 #include "gwindowgui.h"
62 #include "keyframegui.h"
63 #include "indexfile.h"
64 #include "intautos.h"
65 #include "interlacemodes.h"
66 #include "language.h"
67 #include "levelwindowgui.h"
68 #include "levelwindow.h"
69 #include "loadfile.inc"
70 #include "localsession.h"
71 #include "maincursor.h"
72 #include "mainerror.h"
73 #include "mainindexes.h"
74 #include "mainmenu.h"
75 #include "mainprogress.h"
76 #include "mainsession.h"
77 #include "mainundo.h"
78 #include "mbuttons.h"
79 #include "mutex.h"
80 #include "mwindowgui.h"
81 #include "mwindow.h"
82 #include "nestededls.h"
83 #include "new.h"
84 #include "panautos.h"
85 #include "patchbay.h"
86 #include "playback3d.h"
87 #include "playbackengine.h"
88 #include "plugin.h"
89 #include "pluginserver.h"
90 #include "pluginset.h"
91 #include "preferences.h"
92 #include "record.h"
93 #include "recordmonitor.h"
94 #include "recordlabel.h"
95 #include "removefile.h"
96 #include "render.h"
97 #include "resourcethread.h"
98 #include "samplescroll.h"
99 #include "sha1.h"
100 #include "sighandler.h"
101 #include "splashgui.h"
102 #include "statusbar.h"
103 #include "theme.h"
104 #include "threadloader.h"
105 #include "timebar.h"
106 #include "tipwindow.h"
107 #include "trackcanvas.h"
108 #include "track.h"
109 #include "tracking.h"
110 #include "trackscroll.h"
111 #include "tracks.h"
112 #include "transition.h"
113 #include "transportque.h"
114 #include "vframe.h"
115 #include "vtrack.h"
116 #include "versioninfo.h"
117 #include "videodevice.inc"
118 #include "videowindow.h"
119 #include "vplayback.h"
120 #include "vwindowgui.h"
121 #include "vwindow.h"
122 #include "wavecache.h"
123 #include "wwindow.h"
124 #include "zoombar.h"
125 #include "exportedl.h"
126
127 #include "defaultformats.h"
128 #include "ntsczones.h"
129
130 #include <stdint.h>
131 #include <stdlib.h>
132 #include <unistd.h>
133 #include <fcntl.h>
134 #include <string.h>
135 #include <sys/types.h>
136 #include <sys/stat.h>
137 #include <sys/time.h>
138 #include <sys/mman.h>
139 #include <limits.h>
140 #include <errno.h>
141
142
143 extern "C"
144 {
145
146
147
148
149 // Hack for libdv to remove glib dependancy
150
151 // void
152 // g_log (const char    *log_domain,
153 //        int  log_level,
154 //        const char    *format,
155 //        ...)
156 // {
157 // }
158 //
159 // void
160 // g_logv (const char    *log_domain,
161 //        int  log_level,
162 //        const char    *format,
163 //        ...)
164 // {
165 // }
166 //
167
168 }
169
170
171
172 ArrayList<PluginServer*>* MWindow::plugindb = 0;
173 Commercials* MWindow::commercials = 0;
174
175
176 MWindow::MWindow()
177  : Thread(1, 0, 0)
178 {
179         run_lock = new Mutex("MWindow::run_lock");
180         plugin_gui_lock = new Mutex("MWindow::plugin_gui_lock");
181         dead_plugin_lock = new Mutex("MWindow::dead_plugin_lock");
182         vwindows_lock = new Mutex("MWindow::vwindows_lock");
183         brender_lock = new Mutex("MWindow::brender_lock");
184         keyframe_gui_lock = new Mutex("MWindow::keyframe_gui_lock");
185
186         playback_3d = 0;
187         splash_window = 0;
188         undo = 0;
189         defaults = 0;
190         assets = 0;
191         //commercials = 0;
192         commercial_active = 0;
193         audio_cache = 0;
194         video_cache = 0;
195         frame_cache = 0;
196         wave_cache = 0;
197         preferences = 0;
198         session = 0;
199         theme = 0;
200         mainindexes = 0;
201         mainprogress = 0;
202         brender = 0;
203         brender_active = 0;
204         strcpy(cin_lang,"en");
205         channeldb_buz =  new ChannelDB;
206         channeldb_v4l2jpeg =  new ChannelDB;
207         //file_server = 0;
208         plugin_guis = 0;
209         dead_plugins = 0;
210         keyframe_threads = 0;
211         create_bd = 0;
212         create_dvd = 0;
213         batch_render = 0;
214         render = 0;
215         edl = 0;
216         gui = 0;
217         cwindow = 0;
218         awindow = 0;
219         gwindow = 0;
220         twindow = 0;
221         wwindow = 0;
222         lwindow = 0;
223         sighandler = 0;
224         restart_status = 0;
225         screens = 1;
226         in_destructor = 0;
227 }
228
229
230 // Need to delete brender temporary here.
231 MWindow::~MWindow()
232 {
233         run_lock->lock("MWindow::~MWindow");
234         stop_playback(1);
235         in_destructor = 1;
236 //printf("MWindow::~MWindow %d\n", __LINE__);
237         gui->stop_drawing();
238         gui->remote_control->deactivate();
239         gui->record->stop();
240 #ifdef HAVE_DVB
241         gui->channel_info->stop();
242 #endif
243         delete create_bd;       create_bd = 0;
244         delete create_dvd;      create_dvd = 0;
245         delete batch_render;    batch_render = 0;
246         delete render;          render = 0;
247         commit_commercial();
248         if( commercials && !commercials->remove_user() ) commercials = 0;
249
250 // Save defaults for open plugins
251         plugin_gui_lock->lock("MWindow::~MWindow");
252         for(int i = 0; i < plugin_guis->size(); i++) {
253                 plugin_guis->get(i)->hide_gui();
254                 delete_plugin(plugin_guis->get(i));
255         }
256         plugin_gui_lock->unlock();
257         hide_keyframe_guis();
258         clean_indexes();
259         save_defaults();
260 // Give up and go to a movie
261 //  cant run valgrind if this is used
262
263         gui->del_keyboard_listener(
264                 (int (BC_WindowBase::*)(BC_WindowBase *))
265                 &MWindowGUI::keyboard_listener);
266 #if 0
267 // release the hounds
268         if( awindow && awindow->gui ) awindow->gui->close(0);
269         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
270         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
271         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
272         if( twindow && twindow->is_running() ) twindow->close_window();
273         if( wwindow && wwindow->is_running() ) wwindow->close_window();
274         vwindows.remove_all_objects();
275         gui->close(0);
276         if( awindow ) awindow->join();
277         if( cwindow ) cwindow->join();
278         if( lwindow ) lwindow->join();
279         if( twindow ) twindow->join();
280         if( wwindow ) wwindow->join();
281         if( gwindow ) gwindow->join();
282         join();
283 #else
284 // one at a time, or nouveau chokes
285 #define close_gui(win) if( win ) { \
286   if( win->gui ) win->gui->close(0); \
287   win->join(); }
288         close_gui(awindow);
289         close_gui(cwindow);
290         close_gui(lwindow);
291         close_gui(gwindow);
292         close_gui(twindow);
293         close_gui(wwindow);
294         vwindows.remove_all_objects();
295         gui->close(0);
296         join();
297 #endif
298         reset_caches();
299         dead_plugins->remove_all_objects();
300         delete_plugins();
301         finit_error();
302         keyframe_threads->remove_all_objects();
303         colormodels.remove_all_objects();
304         delete awindow;         awindow = 0;
305         delete lwindow;         lwindow = 0;
306         delete twindow;         twindow = 0;
307         delete wwindow;         wwindow = 0;
308         delete gwindow;         gwindow = 0;
309         delete cwindow;         cwindow = 0;
310         delete gui;             gui = 0;
311         //delete file_server;  file_server = 0; // reusable
312         delete mainindexes;     mainindexes = 0;
313         delete mainprogress;    mainprogress = 0;
314         delete audio_cache;     audio_cache = 0;  // delete the cache after the assets
315         delete video_cache;     video_cache = 0;  // delete the cache after the assets
316         delete frame_cache;     frame_cache = 0;
317         delete wave_cache;      wave_cache = 0;
318         delete plugin_guis;     plugin_guis = 0;
319         delete dead_plugins;    dead_plugins = 0;
320         delete keyframe_threads;  keyframe_threads = 0;
321         delete undo;            undo = 0;
322         delete preferences;     preferences = 0;
323         delete exportedl;       exportedl = 0;
324         delete session;         session = 0;
325         delete defaults;        defaults = 0;
326         delete assets;          assets = 0;
327         delete splash_window;   splash_window = 0;
328 //      delete theme;           theme = 0;      // deleted by delete_plugins
329         if( !edl->Garbage::remove_user() ) edl = 0;
330         delete channeldb_buz;
331         delete channeldb_v4l2jpeg;
332 // This must be last thread to exit
333         delete playback_3d;     playback_3d = 0;
334         delete dead_plugin_lock;
335         delete plugin_gui_lock;
336         delete vwindows_lock;
337         delete brender_lock;
338         delete keyframe_gui_lock;
339         colormodels.remove_all_objects();
340         interlace_project_modes.remove_all_objects();
341         interlace_asset_modes.remove_all_objects();
342         interlace_asset_fixmethods.remove_all_objects();
343         sighandler->terminate();
344         delete sighandler;
345         delete run_lock;
346 }
347
348
349 void MWindow::quit()
350 {
351         gui->set_done(0);
352 }
353
354 void MWindow::init_error()
355 {
356         MainError::init_error(this);
357 }
358
359 void MWindow::finit_error()
360 {
361         MainError::finit_error();
362 }
363
364 void MWindow::create_defaults_path(char *string, const char *config_file)
365 {
366 // set the .bcast path
367         FileSystem fs;
368
369         sprintf(string, "%s/", File::get_config_path());
370         fs.complete_path(string);
371         if(!fs.is_dir(string))
372                 fs.create_dir(string);
373
374 // load the defaults
375         strcat(string, config_file);
376 }
377 const char *MWindow::default_std()
378 {
379         char buf[BCTEXTLEN], *p = 0;
380
381         int fd = open(TIMEZONE_NAME, O_RDONLY);
382         if( fd >= 0 ) {
383                 int l = read(fd, buf, sizeof(buf)-1);
384                 close(fd);
385                 if( l > 0 ) {
386                         if( buf[l-1] == '\n' ) --l;
387                         buf[l] = 0;
388                         p = buf;
389                 }
390         }
391         if( !p ) {
392                 int l = readlink(LOCALTIME_LINK, buf, sizeof(buf)-1);
393                 if( l > 0 ) {
394                         buf[l] = 0;
395                         if( !(p=strstr(buf, ZONEINFO_STR)) != 0 ) return "PAL";
396                         p += strlen(ZONEINFO_STR);
397                 }
398         }
399
400         if( p ) {
401                 for( int i=0; ntsc_zones[i]; ++i ) {
402                         if( !strcmp(ntsc_zones[i], p) )
403                                 return "NTSC";
404                 }
405         }
406
407         p = getenv("TZ");
408         if( p ) {
409                 for( int i=0; ntsc_zones[i]; ++i ) {
410                         if( !strcmp(ntsc_zones[i], p) )
411                                 return "NTSC";
412                 }
413         }
414
415 //__timezone: Seconds west of UTC.  240sec/deg
416         double tz_deg = -__timezone / 240.;
417 // from Honolulu = -10, to New York = -5, 15deg/hr   lat -150..-75
418         return tz_deg >= -10*15 && tz_deg <= -5*15 ? "NTSC" : "PAL";
419 }
420
421 void MWindow::fill_preset_defaults(const char *preset, EDLSession *session)
422 {
423         struct formatpresets *fpr;
424
425         for(fpr = &format_presets[0]; fpr->name; fpr++)
426         {
427                 if(strcmp(_(fpr->name), preset) == 0)
428                 {
429                         session->audio_channels = fpr->audio_channels;
430                         session->audio_tracks = fpr->audio_tracks;
431                         session->sample_rate = fpr->sample_rate;
432                         session->video_channels = fpr->video_channels;
433                         session->video_tracks = fpr->video_tracks;
434                         session->frame_rate = fpr->frame_rate;
435                         session->output_w = fpr->output_w;
436                         session->output_h = fpr->output_h;
437                         session->aspect_w = fpr->aspect_w;
438                         session->aspect_h = fpr->aspect_h;
439                         session->interlace_mode = fpr->interlace_mode;
440                         session->color_model = fpr->color_model;
441                         return;
442                 }
443         }
444 }
445
446 const char *MWindow::get_preset_name(int index)
447 {
448         if(index < 0 || index >= (int)MAX_NUM_PRESETS)
449                 return "Error";
450         return _(format_presets[index].name);
451 }
452
453
454 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
455 {
456         char path[BCTEXTLEN];
457 // Use user supplied path
458         if(config_path[0])
459                 strcpy(path, config_path);
460         else
461                 create_defaults_path(path, CONFIG_FILE);
462
463         defaults = new BC_Hash(path);
464         defaults->load();
465 }
466
467
468 void MWindow::check_language()
469 {
470         char curr_lang[BCTEXTLEN]; curr_lang[0] = 0;
471         const char *env_lang = getenv("LANGUAGE");
472         if( !env_lang ) env_lang = getenv("LC_ALL");
473         if( !env_lang ) env_lang = getenv("LANG");
474         if( !env_lang ) {
475                 snprintf(curr_lang, sizeof(curr_lang), "%s_%s-%s",
476                         BC_Resources::language, BC_Resources::region, BC_Resources::encoding);
477                 env_lang = curr_lang;
478         }
479         char last_lang[BCTEXTLEN]; last_lang[0] = 0;
480         defaults->get("LAST_LANG",last_lang);
481         if( strcmp(env_lang,last_lang)) {
482                 printf("lang changed from '%s' to '%s'\n", last_lang, env_lang);
483                 defaults->update("LAST_LANG",env_lang);
484                 char plugin_path[BCTEXTLEN];
485                 create_defaults_path(plugin_path, PLUGIN_FILE);
486                 ::remove(plugin_path);
487                 char ladspa_path[BCTEXTLEN];
488                 create_defaults_path(ladspa_path, LADSPA_FILE);
489                 ::remove(ladspa_path);
490                 defaults->save();
491         }
492         if( strlen(env_lang) > 1 &&
493             ( env_lang[2] == 0 || env_lang[2] == '_'  || env_lang[2] == '.' ) ) {
494                 cin_lang[0] = env_lang[0];  cin_lang[1] = env_lang[1];  cin_lang[2] = 0;
495         }
496         else
497                 strcpy(cin_lang, "en");
498 }
499
500 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
501 {
502         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
503         if( plug_dir ) {
504                 const char *dp = plug_dir;
505                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
506                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
507         }
508         strcpy(path, bp);
509         delete [] base_path;
510 }
511
512 int MWindow::load_plugin_index(MWindow *mwindow, const char *index_path, const char *plugin_dir)
513 {
514 // load index
515         FILE *fp = fopen(index_path, "r");
516         if( !fp ) return -1;
517
518         int ret = 0;
519         char index_line[BCTEXTLEN];
520         int index_version = -1, len = strlen(plugin_dir);
521         if( !fgets(index_line, BCTEXTLEN, fp) ||
522             sscanf(index_line, "%d", &index_version) != 1 ||
523             index_version != PLUGIN_FILE_VERSION ||
524             !fgets(index_line, BCTEXTLEN, fp) ||
525             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
526             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
527
528         ArrayList<PluginServer*> plugins;
529         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
530                 if( index_line[0] == ';' ) continue;
531                 if( index_line[0] == '#' ) continue;
532                 int type = PLUGIN_TYPE_UNKNOWN;
533                 char path[BCTEXTLEN], title[BCTEXTLEN];
534                 int64_t mtime = 0;
535                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
536                         ret = 1; continue;
537                 }
538                 PluginServer *server = 0;
539                 switch( type ) {
540                 case PLUGIN_TYPE_BUILTIN:
541                 case PLUGIN_TYPE_EXECUTABLE:
542                 case PLUGIN_TYPE_LADSPA: {
543                         char plugin_path[BCTEXTLEN];  struct stat st;
544                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
545                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
546                                 ret = 1; continue;
547                         }
548                         server = new PluginServer(mwindow, plugin_path, type);
549                         break; }
550                 case PLUGIN_TYPE_FFMPEG: {
551                         server = new_ffmpeg_server(mwindow, path);
552                         break; }
553                 }
554                 if( !server ) continue;
555                 plugins.append(server);
556 // Create plugin server from index entry
557                 server->set_title(title);
558                 if( server->read_table(index_line) ) {
559                         ret = 1;  continue;
560                 }
561         }
562         fclose(fp);
563
564         if( !ret )
565                 ret = check_plugin_index(plugins, plugin_dir, ".");
566
567         if( !ret )
568                 add_plugins(plugins);
569         else
570                 plugins.remove_all_objects();
571
572         return ret;
573 }
574
575 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
576         const char *plug_dir, const char *plug_path)
577 {
578         char plugin_path[BCTEXTLEN];
579         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
580         FileSystem fs;
581         fs.set_filter( "[*.plugin][*.so]" );
582         if( fs.update(plugin_path) )
583                 return 1;
584
585         for( int i=0; i<fs.dir_list.total; ++i ) {
586                 char fs_path[BCTEXTLEN];
587                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
588                 if( fs.is_dir(fs_path) ) {
589                         get_plugin_path(plugin_path, plug_dir, fs_path);
590                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
591                                 return 1;
592                 }
593                 else if( !plugin_exists(fs_path, plugins) )
594                         return 1;
595         }
596         return 0;
597 }
598
599
600 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
601 {
602         if( !plugindb )
603                 plugindb = new ArrayList<PluginServer*>;
604         init_ffmpeg();
605         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
606         create_defaults_path(index_path, PLUGIN_FILE);
607         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
608         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
609         if( !load_plugin_index(mwindow, index_path, plugin_path) ) return 1;
610         printf("init plugin index: %s\n", plugin_path);
611         FILE *fp = fopen(index_path,"w");
612         if( !fp ) {
613                 fprintf(stderr,_("MWindow::init_plugins: "
614                         "can't create plugin index: %s\n"), index_path);
615                 return 1;
616         }
617         fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
618         fprintf(fp, "%s\n", plugin_path);
619         init_plugin_index(mwindow, preferences, fp, plugin_path);
620         init_ffmpeg_index(mwindow, preferences, fp);
621         fclose(fp);
622         return load_plugin_index(mwindow, index_path, plugin_path);
623 }
624
625 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
626 {
627         char *path = getenv("LADSPA_PATH");
628         char ladspa_path[BCTEXTLEN];
629         if( !path ) {
630                 strncpy(ladspa_path, File::get_ladspa_path(), sizeof(ladspa_path));
631                 path = ladspa_path;
632         }
633         for( int len=0; *path; path+=len ) {
634                 char *cp = strchr(path,':');
635                 len = !cp ? strlen(path) : cp-path;
636                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
637                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
638                 if( cp ) ++len;
639                 char *plugin_dir = FileSystem::basepath(plugin_path);
640                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
641                 create_defaults_path(index_path, LADSPA_FILE);
642                 cp = index_path + strlen(index_path);
643                 for( char *bp=plugin_path; *bp!=0; ++bp )
644                         *cp++ = *bp=='/' ? '_' : *bp;
645                 *cp = 0;
646                 if( !load_plugin_index(mwindow, index_path, plugin_path) ) continue;
647                 if( init_ladspa_index(mwindow, preferences, index_path, plugin_path) ) continue;
648                 load_plugin_index(mwindow, index_path, plugin_path);
649         }
650         return 1;
651 }
652
653 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
654         FILE *fp, const char *plugin_dir)
655 {
656         int idx = PLUGIN_IDS;
657         if( plugindb ) {
658                 for( int i=0; i<plugindb->size(); ++i ) {
659                         PluginServer *server = plugindb->get(i);
660                         if( server->dir_idx >= idx )
661                                 idx = server->dir_idx+1;
662                 }
663         }
664         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
665 }
666
667 int MWindow::init_ladspa_index(MWindow *mwindow, Preferences *preferences,
668         const char *index_path, const char *plugin_dir)
669 {
670         char plugin_path[BCTEXTLEN], *path = FileSystem::basepath(plugin_dir);
671         strcpy(plugin_path, path);  delete [] path;
672         printf("init ladspa index: %s\n", plugin_dir);
673         FILE *fp = fopen(index_path,"w");
674         if( !fp ) {
675                 fprintf(stderr,_("MWindow::init_ladspa_index: "
676                         "can't create plugin index: %s\n"), index_path);
677                 return 1;
678         }
679         fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
680         fprintf(fp, "%s\n", plugin_dir);
681         init_plugin_index(mwindow, preferences, fp, plugin_path);
682         fclose(fp);
683         return 0;
684 }
685
686 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
687         const char *plug_dir, const char *plug_path, int &idx)
688 {
689         char plugin_path[BCTEXTLEN];
690         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
691         FileSystem fs;
692         fs.set_filter( "[*.plugin][*.so]" );
693         int result = fs.update(plugin_path);
694         if( result || !fs.dir_list.total ) return;
695         int vis_id = idx++;
696
697         for( int i=0; i<fs.dir_list.total; ++i ) {
698                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
699                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
700                 get_plugin_path(path, plug_dir, fs_path);
701                 if( fs.is_dir(fs_path) ) {
702                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
703                         continue;
704                 }
705                 if( plugin_exists(path) ) continue;
706                 struct stat st;
707                 if( stat(fs_path, &st) ) continue;
708                 int64_t mtime = st.st_mtime;
709                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
710                 result = server.open_plugin(1, preferences, 0, 0);
711                 if( !result ) {
712                         server.write_table(fp, path, vis_id, mtime);
713                         server.close_plugin();
714                 }
715                 else if( result == PLUGINSERVER_IS_LAD ) {
716                         int lad_index = 0;
717                         for(;;) {
718                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
719                                 ladspa.set_lad_index(lad_index++);
720                                 result = ladspa.open_plugin(1, preferences, 0, 0);
721                                 if( result ) break;
722                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
723                                 ladspa.close_plugin();
724                         }
725                 }
726         }
727 }
728
729 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
730 {
731         for( int i=0; i<plugins.size(); ++i )
732                 plugindb->append(plugins[i]);
733         plugins.remove_all();
734 }
735
736 void MWindow::init_plugin_tips(ArrayList<PluginServer*> &plugins)
737 {
738         const char *cfg_path = File::get_cindat_path();
739         char msg_path[BCTEXTLEN];  int txt = 0;
740         FILE *fp = 0;
741         if( BC_Resources::language[0] ) {
742                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.%s",
743                         cfg_path, BC_Resources::language);
744                 fp = fopen(msg_path, "r");
745         }
746         if( !fp ) {
747                 txt = 1;
748                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.txt",
749                         cfg_path);
750                 fp = fopen(msg_path, "r");
751         }
752         if( !fp ) return;
753         char text[BCTEXTLEN];
754         char *tp = text, *ep = tp + sizeof(text)-1;
755         char title[BCTEXTLEN];
756         title[0] = 0;
757         int no = 0;
758         for(;;) {
759                 ++no;  int done = 1;
760                 char line[BCTEXTLEN], *cp = line;
761                 if( fgets(line,sizeof(line)-1,fp) ) {
762                         if( *cp == '#' ) continue;
763                         done = *cp == ' ' || *cp == '\t' ? 0 : -1;
764                 }
765                 if( done ) {
766                         if( tp > text && *--tp == '\n' ) *tp = 0;
767                         if( title[0] ) {
768                                 tp = !txt ? title : _(title);
769                                 int idx = plugins.size();
770                                 while( --idx>=0 && strcmp(plugins[idx]->title, tp) );
771                                 if( idx >= 0 ) {
772                                         delete [] plugins[idx]->tip;
773                                         plugins[idx]->tip = cstrdup(text);
774                                 }
775                                 title[0] = 0;
776                         }
777                         if( done > 0 ) break;
778                         tp = text;  *tp = 0;
779                         char *dp = strchr(cp, ':');
780                         if( !dp ) {
781                                 printf("plugin tips: error on line %d\n", no);
782                                 continue;
783                         }
784                         char *bp = title;
785                         while( cp < dp ) *bp++ = *cp++;
786                         *bp = 0;
787                         ++cp;
788                 }
789
790                 while( *cp == ' ' || *cp == '\t' ) ++cp;
791                 for( ; tp<ep && (*tp=*cp)!=0; ++tp,++cp );
792         }
793         fclose(fp);
794 }
795
796 void MWindow::delete_plugins()
797 {
798         plugindb->remove_all_objects();
799         delete plugindb;
800         plugindb = 0;
801 }
802
803 void MWindow::search_plugindb(int do_audio,
804                 int do_video,
805                 int is_realtime,
806                 int is_transition,
807                 int is_theme,
808                 ArrayList<PluginServer*> &results)
809 {
810 // Get plugins
811         for(int i = 0; i < MWindow::plugindb->total; i++)
812         {
813                 PluginServer *current = MWindow::plugindb->get(i);
814
815                 if(current->audio == do_audio &&
816                         current->video == do_video &&
817                         (current->realtime == is_realtime || is_realtime < 0) &&
818                         current->transition == is_transition &&
819                         current->theme == is_theme)
820                         results.append(current);
821         }
822
823 // Alphabetize list by title
824         int done = 0;
825         while(!done)
826         {
827                 done = 1;
828
829                 for(int i = 0; i < results.total - 1; i++)
830                 {
831                         PluginServer *value1 = results[i];
832                         PluginServer *value2 = results[i + 1];
833                         if(strcmp(_(value1->title), _(value2->title)) > 0)
834                         {
835                                 done = 0;
836                                 results[i] = value2;
837                                 results[i + 1] = value1;
838                         }
839                 }
840         }
841 }
842
843 PluginServer* MWindow::scan_plugindb(char *title,
844                 int data_type)
845 {
846 //      if(data_type < 0)
847 //      {
848 //              printf("MWindow::scan_plugindb data_type < 0\n");
849 //              return 0;
850 //      }
851
852         for(int i = 0; i < plugindb->total; i++)
853         {
854                 PluginServer *server = plugindb->get(i);
855                 if(server->title &&
856                         !strcasecmp(server->title, title) &&
857                         (data_type < 0 ||
858                                 (data_type == TRACK_AUDIO && server->audio) ||
859                                 (data_type == TRACK_VIDEO && server->video)))
860                         return plugindb->get(i);
861         }
862         return 0;
863 }
864
865 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
866 {
867         for( int i=0; i<plugins.size(); ++i )
868                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
869         return 0;
870 }
871
872 int MWindow::plugin_exists(char *plugin_path)
873 {
874         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
875 }
876
877 void MWindow::init_preferences()
878 {
879         preferences = new Preferences;
880         preferences->load_defaults(defaults);
881         session = new MainSession(this);
882         session->load_defaults(defaults);
883         // set x11_host, screens, window_config
884         screens = session->set_default_x11_host();
885         BC_Signals::set_trap_hook(trap_hook, this);
886         BC_Signals::set_catch_segv(preferences->trap_sigsegv);
887         BC_Signals::set_catch_intr(preferences->trap_sigintr);
888         if( preferences->trap_sigsegv || preferences->trap_sigintr ) {
889                 BC_Trace::enable_locks();
890         }
891         else {
892                 BC_Trace::disable_locks();
893         }
894         BC_WindowBase::get_resources()->popupmenu_btnup = preferences->popupmenu_btnup;
895         BC_WindowBase::get_resources()->textbox_focus_policy = preferences->textbox_focus_policy;
896 }
897
898 void MWindow::clean_indexes()
899 {
900         FileSystem fs;
901         int total_excess;
902         long oldest = 0;
903         int oldest_item = -1;
904         int result;
905         char string[BCTEXTLEN];
906         char string2[BCTEXTLEN];
907
908 // Delete extra indexes
909         fs.set_filter("*.idx");
910         fs.complete_path(preferences->index_directory);
911         fs.update(preferences->index_directory);
912 //printf("MWindow::clean_indexes 1 %d\n", fs.dir_list.total);
913
914 // Eliminate directories
915         result = 1;
916         while(result)
917         {
918                 result = 0;
919                 for(int i = 0; i < fs.dir_list.total && !result; i++)
920                 {
921                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
922                         if(fs.is_dir(string))
923                         {
924                                 delete fs.dir_list[i];
925                                 fs.dir_list.remove_number(i);
926                                 result = 1;
927                         }
928                 }
929         }
930         total_excess = fs.dir_list.total - preferences->index_count;
931
932 //printf("MWindow::clean_indexes 2 %d\n", fs.dir_list.total);
933         while(total_excess > 0)
934         {
935 // Get oldest
936                 for(int i = 0; i < fs.dir_list.total; i++)
937                 {
938                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
939
940                         if(i == 0 || fs.get_date(string) <= oldest)
941                         {
942                                 oldest = fs.get_date(string);
943                                 oldest_item = i;
944                         }
945                 }
946
947                 if(oldest_item >= 0)
948                 {
949 // Remove index file
950                         fs.join_names(string,
951                                 preferences->index_directory,
952                                 fs.dir_list[oldest_item]->name);
953 //printf("MWindow::clean_indexes 1 %s\n", string);
954                         if(remove(string))
955                                 perror("delete_indexes");
956                         delete fs.dir_list[oldest_item];
957                         fs.dir_list.remove_number(oldest_item);
958
959 // Remove table of contents if it exists
960                         strcpy(string2, string);
961                         char *ptr = strrchr(string2, '.');
962                         if(ptr)
963                         {
964 //printf("MWindow::clean_indexes 2 %s\n", string2);
965                                 sprintf(ptr, ".toc");
966                                 remove(string2);
967                                 sprintf(ptr, ".mkr");
968                                 remove(string2);
969                         }
970                 }
971
972                 total_excess--;
973         }
974 }
975
976 void MWindow::init_awindow()
977 {
978         awindow = new AWindow(this);
979         awindow->create_objects();
980 }
981
982 void MWindow::init_gwindow()
983 {
984         gwindow = new GWindow(this);
985         gwindow->create_objects();
986 }
987
988 void MWindow::init_tipwindow()
989 {
990         TipWindow::load_tips(cin_lang);
991         if( !twindow )
992                 twindow = new TipWindow(this);
993         twindow->start();
994 }
995
996 void MWindow::show_warning(int *do_warning, const char *text)
997 {
998         if( do_warning && !*do_warning ) return;
999         if( !wwindow )
1000                 wwindow = new WWindow(this);
1001         wwindow->show_warning(do_warning, text);
1002 }
1003
1004 int MWindow::wait_warning()
1005 {
1006         return wwindow->wait_result();
1007 }
1008
1009 void MWindow::init_theme()
1010 {
1011         Timer timer;
1012         theme = 0;
1013
1014         PluginServer *theme_plugin = 0;
1015         for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1016                 if( plugindb->get(i)->theme &&
1017                     !strcasecmp(preferences->theme, plugindb->get(i)->title) )
1018                         theme_plugin = plugindb->get(i);
1019         }
1020
1021         if( !theme_plugin )
1022                 fprintf(stderr, _("MWindow::init_theme: prefered theme %s not found.\n"),
1023                          preferences->theme);
1024
1025         const char *default_theme = _(DEFAULT_THEME);
1026         if( !theme_plugin && strcasecmp(preferences->theme, default_theme) ) {
1027                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
1028                         default_theme);
1029                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1030                         if( plugindb->get(i)->theme &&
1031                             !strcasecmp(default_theme, plugindb->get(i)->title) )
1032                                 theme_plugin = plugindb->get(i);
1033                 }
1034         }
1035
1036         if(!theme_plugin) {
1037                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
1038                 exit(1);
1039         }
1040
1041         PluginServer *plugin = new PluginServer(*theme_plugin);
1042         if( plugin->open_plugin(0, preferences, 0, 0) ) {
1043                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
1044                         theme_plugin->title);
1045                 exit(1);
1046         }
1047
1048         theme = plugin->new_theme();
1049         theme->mwindow = this;
1050         strcpy(theme->path, plugin->path);
1051         delete plugin;
1052
1053 // Load default images & settings
1054         theme->Theme::initialize();
1055 // Load user images & settings
1056         theme->initialize();
1057 // Create menus with user colors
1058         theme->build_menus();
1059         init_menus();
1060
1061         theme->check_used();
1062
1063 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1064 }
1065
1066 void MWindow::init_3d()
1067 {
1068         playback_3d = new Playback3D(this);
1069         playback_3d->create_objects();
1070 }
1071
1072 void MWindow::init_edl()
1073 {
1074         edl = new EDL;
1075         edl->create_objects();
1076         fill_preset_defaults(default_standard, edl->session);
1077         edl->load_defaults(defaults);
1078         edl->session->brender_start = edl->session->brender_end = 0;
1079         edl->create_default_tracks();
1080         edl->tracks->update_y_pixels(theme);
1081 }
1082
1083 void MWindow::init_compositor()
1084 {
1085         cwindow = new CWindow(this);
1086         cwindow->create_objects();
1087 }
1088
1089 void MWindow::init_levelwindow()
1090 {
1091         lwindow = new LevelWindow(this);
1092         lwindow->create_objects();
1093 }
1094
1095 VWindow *MWindow::get_viewer(int start_it, int idx)
1096 {
1097         vwindows_lock->lock("MWindow::get_viewer");
1098         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
1099         if( !vwindow ) idx = vwindows.size();
1100         while( !vwindow && --idx >= 0 ) {
1101                 VWindow *vwin = vwindows[idx];
1102                 if( !vwin->is_running() || !vwin->get_edl() )
1103                         vwindow = vwin;
1104         }
1105         if( !vwindow ) {
1106                 vwindow = new VWindow(this);
1107                 vwindow->load_defaults();
1108                 vwindow->create_objects();
1109                 vwindows.append(vwindow);
1110         }
1111         vwindows_lock->unlock();
1112         if( start_it ) vwindow->start();
1113         return vwindow;
1114 }
1115
1116 void MWindow::init_cache()
1117 {
1118         audio_cache = new CICache(preferences);
1119         video_cache = new CICache(preferences);
1120         frame_cache = new FrameCache;
1121         wave_cache = new WaveCache;
1122 }
1123
1124 void MWindow::init_channeldb()
1125 {
1126         channeldb_buz->load("channeldb_buz");
1127         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1128 }
1129
1130 void MWindow::init_menus()
1131 {
1132         char string[BCTEXTLEN];
1133
1134         // Color Models
1135         BC_CModels::to_text(string, BC_RGB888);
1136         colormodels.append(new ColormodelItem(string, BC_RGB888));
1137         BC_CModels::to_text(string, BC_RGBA8888);
1138         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1139 //      BC_CModels::to_text(string, BC_RGB161616);
1140 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1141 //      BC_CModels::to_text(string, BC_RGBA16161616);
1142 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1143         BC_CModels::to_text(string, BC_RGB_FLOAT);
1144         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1145         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1146         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1147         BC_CModels::to_text(string, BC_YUV888);
1148         colormodels.append(new ColormodelItem(string, BC_YUV888));
1149         BC_CModels::to_text(string, BC_YUVA8888);
1150         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1151 //      BC_CModels::to_text(string, BC_YUV161616);
1152 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1153 //      BC_CModels::to_text(string, BC_YUVA16161616);
1154 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1155
1156 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1157                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1158
1159 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1160                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1161
1162 #define ILACEFIXMETHODLISTADD(x) ilacefixmethod_to_text(string, x); \
1163                            interlace_asset_fixmethods.append(new InterlacefixmethodItem(string, x));
1164
1165         // Interlacing Modes
1166         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1167
1168         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1169         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1170
1171         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1172         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1173
1174         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1175         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1176
1177         // Interlacing Fixing Methods
1178         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_NONE);
1179         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_UPONE);
1180         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_DOWNONE);
1181 }
1182
1183 void MWindow::init_indexes()
1184 {
1185         mainindexes = new MainIndexes(this);
1186         mainindexes->start_loop();
1187 }
1188
1189 void MWindow::init_gui()
1190 {
1191         gui = new MWindowGUI(this);
1192         gui->lock_window("MWindow::init_gui");
1193         gui->create_objects();
1194         gui->unlock_window();
1195         gui->load_defaults(defaults);
1196 }
1197
1198 void MWindow::init_signals()
1199 {
1200         sighandler = new SigHandler;
1201         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1202 ENABLE_BUFFER
1203 }
1204
1205 void MWindow::init_render()
1206 {
1207         render = new Render(this);
1208         create_bd = new CreateBD_Thread(this);
1209         create_dvd = new CreateDVD_Thread(this);
1210         batch_render = new BatchRenderThread(this);
1211 }
1212
1213 void MWindow::init_exportedl()
1214 {
1215         exportedl = new ExportEDL(this);
1216 }
1217
1218 void MWindow::init_brender()
1219 {
1220         if(preferences->use_brender && !brender)
1221         {
1222                 brender_lock->lock("MWindow::init_brender 1");
1223                 brender = new BRender(this);
1224                 brender->initialize();
1225                 session->brender_end = 0;
1226                 brender_lock->unlock();
1227         }
1228         else
1229         if(!preferences->use_brender && brender)
1230         {
1231                 brender_lock->lock("MWindow::init_brender 2");
1232                 delete brender;
1233                 brender = 0;
1234                 session->brender_end = 0;
1235                 brender_lock->unlock();
1236         }
1237         brender_active = 0;
1238         stop_brender();
1239 }
1240
1241 void MWindow::restart_brender()
1242 {
1243 //printf("MWindow::restart_brender 1\n");
1244         if( !brender_active || !preferences->use_brender ) return;
1245         if( !brender ) return;
1246         int locked  = gui->get_window_lock();
1247         if( locked ) gui->unlock_window();
1248         brender->restart(edl);
1249         if( locked ) gui->lock_window("MWindow::restart_brender");
1250 }
1251
1252 void MWindow::stop_brender()
1253 {
1254         if( !brender ) return;
1255         int locked  = gui->get_window_lock();
1256         if( locked ) gui->unlock_window();
1257         brender->stop();
1258         if( locked ) gui->lock_window("MWindow::stop_brender");
1259 }
1260
1261 int MWindow::brender_available(int position)
1262 {
1263         int result = 0;
1264         brender_lock->lock("MWindow::brender_available 1");
1265         if(brender && brender_active)
1266         {
1267                 if(brender->map_valid)
1268                 {
1269                         brender->map_lock->lock("MWindow::brender_available 2");
1270                         if(position < brender->map_size &&
1271                                 position >= 0)
1272                         {
1273 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1274                                 if(brender->map[position] == BRender::RENDERED)
1275                                         result = 1;
1276                         }
1277                         brender->map_lock->unlock();
1278                 }
1279         }
1280         brender_lock->unlock();
1281         return result;
1282 }
1283
1284 void MWindow::set_brender_active(int v, int update)
1285 {
1286         if( !preferences->use_brender ) v = 0;
1287         brender_active = v;
1288         gui->mainmenu->brender_active->set_checked(v);
1289         if( v != 0 ) {
1290                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1291                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1292
1293                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1294                         edl->session->brender_end = edl->tracks->total_video_length();
1295                 }
1296                 restart_brender();
1297         }
1298         else {
1299                 edl->session->brender_start = edl->session->brender_end = 0;
1300                 stop_brender();
1301         }
1302         if( update ) {
1303                 gui->update_timebar(0);
1304                 gui->draw_overlays(1);
1305         }
1306 }
1307
1308 int MWindow::has_commercials()
1309 {
1310         return theme->use_commercials;
1311 }
1312
1313 void MWindow::init_commercials()
1314 {
1315         if( !commercials ) {
1316                 commercials = new Commercials(this);
1317                 commercial_active = 0;
1318         }
1319         else
1320                 commercials->add_user();
1321 }
1322
1323 void MWindow::commit_commercial()
1324 {
1325         if( !commercial_active ) return;
1326         commercial_active = 0;
1327         if( !commercials ) return;
1328         commercials->commitDb();
1329 }
1330
1331 void MWindow::undo_commercial()
1332 {
1333         if( !commercial_active ) return;
1334         commercial_active = 0;
1335         if( !commercials ) return;
1336         commercials->undoDb();
1337 }
1338
1339 int MWindow::put_commercial()
1340 {
1341         double start = edl->local_session->get_selectionstart();
1342         double end = edl->local_session->get_selectionend();
1343         if( start >= end ) return 0;
1344
1345         const char *errmsg = 0;
1346         int count = 0;
1347         Tracks *tracks = edl->tracks;
1348         int result = 0;
1349         //check it
1350         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1351                 if( track->data_type != TRACK_VIDEO ) continue;
1352                 if( !track->record ) continue;
1353                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1354                 ++count;
1355                 int64_t units_start = track->to_units(start,0);
1356                 int64_t units_end = track->to_units(end,0);
1357                 Edits *edits = track->edits;
1358                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1359                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1360                 if(!edit1 && !edit2) continue;  // nothing selected
1361                 if(!edit2) {                    // edit2 beyond end of track
1362                         edit2 = edits->last;
1363                         units_end = edits->length();
1364                 }
1365                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1366                 Indexable *indexable = edit1->get_source();
1367                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1368         }
1369         //run it
1370         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1371                 if( track->data_type != TRACK_VIDEO ) continue;
1372                 if( !track->record ) continue;
1373                 int64_t units_start = track->to_units(start,0);
1374                 int64_t units_end = track->to_units(end,0);
1375                 Edits *edits = track->edits;
1376                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1377                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1378                 if(!edit1 && !edit2) continue;  // nothing selected
1379                 if(!edit2) {                    // edit2 beyond end of track
1380                         edit2 = edits->last;
1381                         units_end = edits->length();
1382                 }
1383                 Indexable *indexable = edit1->get_source();
1384                 Asset *asset = (Asset *)indexable;
1385                 File *file = video_cache->check_out(asset, edl);
1386                 if( !file ) { errmsg = _("no file"); break; }
1387                 int64_t edit_length = units_end - units_start;
1388                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1389                 result = commercials->put_clip(file, edit1->channel,
1390                         track->from_units(edit_start), track->from_units(edit_length));
1391                 video_cache->check_in(asset);
1392                 if( result ) { errmsg = _("db failed"); break; }
1393         }
1394         if( errmsg ) {
1395                 char string[BCTEXTLEN];
1396                 sprintf(string, _("put_commercial: %s"), errmsg);
1397                 MainError::show_error(string);
1398                 undo_commercial();
1399                 result = 1;
1400         }
1401         return result;
1402 }
1403
1404 void MWindow::stop_playback(int wait)
1405 {
1406         int locked  = gui->get_window_lock();
1407         if( locked ) gui->unlock_window();
1408
1409         cwindow->playback_engine->stop_playback();
1410
1411         for(int i = 0; i < vwindows.size(); i++) {
1412                 VWindow *vwindow = vwindows[i];
1413                 if( !vwindow->is_running() ) continue;
1414                 vwindow->playback_engine->stop_playback();
1415         }
1416         if( locked ) gui->lock_window("MWindow::stop_playback");
1417 }
1418
1419 int MWindow::load_filenames(ArrayList<char*> *filenames,
1420         int load_mode,
1421         int update_filename)
1422 {
1423         ArrayList<EDL*> new_edls;
1424         ArrayList<Asset*> new_assets;
1425         ArrayList<File*> new_files;
1426         const int debug = 0;
1427 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1428
1429 //      save_defaults();
1430         gui->start_hourglass();
1431
1432 // Need to stop playback since tracking depends on the EDL not getting
1433 // deleted.
1434         stop_playback(1);
1435
1436 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1437         undo->update_undo_before();
1438
1439
1440 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1441
1442 // Define new_edls and new_assets to load
1443         int result = 0, ftype = -1;
1444         for(int i = 0; i < filenames->size(); i++)
1445         {
1446 // Get type of file
1447                 File *new_file = new File;
1448                 Asset *new_asset = new Asset(filenames->get(i));
1449                 EDL *new_edl = new EDL;
1450                 char string[BCTEXTLEN];
1451
1452                 new_edl->create_objects();
1453                 new_edl->copy_session(edl);
1454                 new_file->set_program(edl->session->program_no);
1455
1456                 sprintf(string, _("Loading %s"), new_asset->path);
1457                 gui->show_message(string);
1458 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1459
1460                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1461 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1462
1463                 result = 1;
1464                 switch(ftype)
1465                 {
1466 // Convert media file to EDL
1467                         case FILE_OK:
1468 // Warn about odd image dimensions
1469                                 if(new_asset->video_data &&
1470                                         ((new_asset->width % 2) ||
1471                                         (new_asset->height % 2)))
1472                                 {
1473                                         char string[BCTEXTLEN];
1474                                         sprintf(string, _("%s's resolution is %dx%d.\nImages with odd dimensions may not decode properly."),
1475                                                 new_asset->path,
1476                                                 new_asset->width,
1477                                                 new_asset->height);
1478                                         MainError::show_error(string);
1479                                 }
1480
1481                                 if(new_asset->program >= 0 &&
1482                                         edl->session->program_no != new_asset->program)
1483                                 {
1484                                         char string[BCTEXTLEN];
1485                                         sprintf(string, _("%s's index was built for program number %d\n"
1486                                                 "Playback preference is %d.\n  Using program %d."),
1487                                                 new_asset->path, new_asset->program,
1488                                                 edl->session->program_no, new_asset->program);
1489                                         MainError::show_error(string);
1490                                 }
1491
1492
1493                                 if(load_mode != LOADMODE_RESOURCESONLY)
1494                                 {
1495 SET_TRACE
1496                                         RecordLabels *labels = edl->session->label_cells ?
1497                                                 new RecordLabels(new_file) : 0;
1498 SET_TRACE
1499                                         asset_to_edl(new_edl, new_asset, labels);
1500 SET_TRACE
1501                                         new_edls.append(new_edl);
1502 SET_TRACE
1503                                         new_asset->Garbage::remove_user();
1504                                         delete labels;
1505                                         new_asset = 0;
1506                                 }
1507                                 else
1508                                 {
1509                                         new_assets.append(new_asset);
1510                                         new_asset = 0;
1511                                 }
1512
1513 // Set filename to nothing for assets since save EDL would overwrite them.
1514                                 if(load_mode == LOADMODE_REPLACE ||
1515                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
1516                                 {
1517                                         set_filename("");
1518 // Reset timeline position
1519                                         for(int i = 0; i < TOTAL_PANES; i++)
1520                                         {
1521                                                 new_edl->local_session->view_start[i] = 0;
1522                                                 new_edl->local_session->track_start[i] = 0;
1523                                         }
1524                                 }
1525
1526                                 result = 0;
1527                                 break;
1528
1529 // File not found
1530                         case FILE_NOT_FOUND:
1531                                 sprintf(string, _("Failed to open %s"), new_asset->path);
1532                                 gui->show_message(string, theme->message_error);
1533                                 gui->update_default_message();
1534                                 break;
1535
1536 // Unknown format
1537                         case FILE_UNRECOGNIZED_CODEC:
1538                         {
1539 // Test index file
1540                                 {       IndexFile indexfile(this, new_asset);
1541                                         if( !(result = indexfile.open_index()) )
1542                                                 indexfile.close_index();
1543                                 }
1544
1545 // Test existing EDLs
1546                                 for(int j = 0; result && j <= new_edls.total; j++) {
1547                                         Asset *old_asset = j < new_edls.total ?
1548                                                 new_edls[j]->assets->get_asset(new_asset->path) :
1549                                                 edl->assets->get_asset(new_asset->path);
1550                                         if( old_asset ) {
1551                                                 new_asset->copy_from(old_asset,1);
1552                                                 result = 0;
1553                                         }
1554                                 }
1555
1556 // Prompt user
1557                                 if(result)
1558                                 {
1559                                         char string[BCTEXTLEN];
1560                                         FileSystem fs;
1561                                         fs.extract_name(string, new_asset->path);
1562
1563                                         strcat(string, _("'s format couldn't be determined."));
1564                                         new_asset->audio_data = 1;
1565                                         new_asset->format = FILE_PCM;
1566                                         new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
1567                                         new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
1568                                         new_asset->bits = defaults->get("AUDIO_BITS", 16);
1569                                         new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
1570                                         new_asset->signed_ = defaults->get("SIGNED_", 1);
1571                                         new_asset->header = defaults->get("HEADER", 0);
1572
1573                                         FileFormat fwindow(this);
1574                                         fwindow.create_objects(new_asset, string);
1575                                         result = fwindow.run_window();
1576
1577
1578                                         defaults->update("AUDIO_CHANNELS", new_asset->channels);
1579                                         defaults->update("SAMPLE_RATE", new_asset->sample_rate);
1580                                         defaults->update("AUDIO_BITS", new_asset->bits);
1581                                         defaults->update("BYTE_ORDER", new_asset->byte_order);
1582                                         defaults->update("SIGNED_", new_asset->signed_);
1583                                         defaults->update("HEADER", new_asset->header);
1584                                         save_defaults();
1585                                 }
1586
1587 // Append to list
1588                                 if(!result)
1589                                 {
1590 // Recalculate length
1591                                         delete new_file;
1592                                         new_file = new File;
1593                                         result = new_file->open_file(preferences, new_asset, 1, 0);
1594
1595                                         if(load_mode != LOADMODE_RESOURCESONLY)
1596                                         {
1597                                                 RecordLabels *labels = edl->session->label_cells ?
1598                                                         new RecordLabels(new_file) : 0;
1599                                                 asset_to_edl(new_edl, new_asset, labels);
1600                                                 new_edls.append(new_edl);
1601                                                 new_asset->Garbage::remove_user();
1602                                                 delete labels;
1603                                                 new_asset = 0;
1604                                         }
1605                                         else
1606                                         {
1607                                                 new_assets.append(new_asset);
1608                                                 new_asset = 0;
1609                                         }
1610                                 }
1611                                 else
1612                                 {
1613                                         result = 1;
1614                                 }
1615                                 break;
1616                         }
1617
1618                         case FILE_IS_XML:
1619                         {
1620                                 FileXML xml_file;
1621 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1622                                 xml_file.read_from_file(filenames->get(i));
1623 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1624                                 const char *cin_version = 0;
1625                                 while( !xml_file.read_tag() ) {
1626                                         if( xml_file.tag.title_is("EDL") ) {
1627                                                 cin_version = xml_file.tag.get_property("VERSION");
1628                                                 break;
1629                                         }
1630                                 }
1631                                 xml_file.rewind();
1632                                 if( !cin_version ) {
1633                                         eprintf(_("XML file %s\n not from cinelerra."),filenames->get(i));
1634                                         char string[BCTEXTLEN];
1635                                         sprintf(string,_("Unknown %s"), filenames->get(i));
1636                                         gui->show_message(string);
1637                                         result = 1;
1638                                         break;
1639                                 }
1640                                 if( strcmp(cin_version, CINELERRA_VERSION) ) {
1641                                         char string[BCTEXTLEN];
1642                                         snprintf(string, sizeof(string),
1643                                                  _("Warning: XML from cinelerra version %s\n"
1644                                                 "Session data may be incompatible."), cin_version);
1645                                         show_warning(&preferences->warn_version, string);
1646                                 }
1647                                 if(load_mode == LOADMODE_NESTED)
1648                                 {
1649 // Load temporary EDL for nesting.
1650                                         EDL *nested_edl = new EDL;
1651                                         nested_edl->create_objects();
1652                                         nested_edl->set_path(filenames->get(i));
1653                                         nested_edl->load_xml(&xml_file, LOAD_ALL);
1654 //printf("MWindow::load_filenames %p %s\n", nested_edl, nested_edl->project_path);
1655                                         edl_to_nested(new_edl, nested_edl);
1656                                         nested_edl->Garbage::remove_user();
1657                                 }
1658                                 else
1659                                 {
1660 // Load EDL for pasting
1661                                         new_edl->load_xml(&xml_file, LOAD_ALL);
1662 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1663                                         test_plugins(new_edl, filenames->get(i));
1664 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1665
1666                                         if(load_mode == LOADMODE_REPLACE ||
1667                                                 load_mode == LOADMODE_REPLACE_CONCATENATE)
1668                                         {
1669                                                 strcpy(session->filename, filenames->get(i));
1670                                                 strcpy(new_edl->local_session->clip_title,
1671                                                         filenames->get(i));
1672                                                 if(update_filename)
1673                                                         set_filename(new_edl->local_session->clip_title);
1674                                         }
1675                                         else
1676                                         if( load_mode == LOADMODE_RESOURCESONLY ) {
1677                                                 strcpy(new_edl->local_session->clip_title,
1678                                                         filenames->get(i));
1679                                                 struct stat st;
1680                                                 time_t t = !stat(filenames->get(i),&st) ?
1681                                                         st.st_mtime : time(&t);
1682                                                 ctime_r(&t, new_edl->local_session->clip_notes);
1683                                         }
1684                                 }
1685
1686                                 new_edls.append(new_edl);
1687                                 result = 0;
1688                                 break;
1689                         }
1690                 }
1691
1692 // edls are in new_edls
1693                 if( result && new_edl ) new_edl->Garbage::remove_user();
1694 // assets are copied
1695                 if( new_asset ) new_asset->Garbage::remove_user();
1696
1697 // Store for testing index
1698                 new_files.append(new_file);
1699         }
1700
1701 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1702
1703
1704         if(!result) {
1705                 gui->reset_default_message();
1706                 gui->default_message();
1707         }
1708
1709
1710 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1711
1712 // Paste them.
1713 // Don't back up here.
1714         if(new_edls.size())
1715         {
1716 // For pasting, clear the active region
1717                 if(load_mode == LOADMODE_PASTE ||
1718                         load_mode == LOADMODE_NESTED)
1719                 {
1720                         double start = edl->local_session->get_selectionstart();
1721                         double end = edl->local_session->get_selectionend();
1722                         if(!EQUIV(start, end))
1723                                 edl->clear(start,
1724                                         end,
1725                                         edl->session->labels_follow_edits,
1726                                         edl->session->plugins_follow_edits,
1727                                         edl->session->autos_follow_edits);
1728                 }
1729
1730                 paste_edls(&new_edls, load_mode, 0, -1,
1731                         edl->session->labels_follow_edits,
1732                         edl->session->plugins_follow_edits,
1733                         edl->session->autos_follow_edits,
1734                         0); // overwrite
1735         }
1736
1737
1738
1739
1740 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1741
1742 // Add new assets to EDL and schedule assets for index building.
1743         int got_indexes = 0;
1744         for(int i = 0; i < new_edls.size(); i++)
1745         {
1746                 EDL *new_edl = new_edls[i];
1747                 for(int j = 0; j < new_edl->nested_edls->size(); j++)
1748                 {
1749                         mainindexes->add_next_asset(0,
1750                                 new_edl->nested_edls->get(j));
1751                         got_indexes = 1;
1752                         edl->nested_edls->update_index(new_edl->nested_edls->get(j));
1753                 }
1754
1755         }
1756
1757 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1758         for(int i = 0; i < new_assets.size(); i++)
1759         {
1760                 Asset *new_asset = new_assets[i];
1761
1762                 File *new_file = 0;
1763                 int got_it = 0;
1764                 for(int j = 0; j < new_files.size(); j++)
1765                 {
1766                         new_file = new_files[j];
1767                         if(!strcmp(new_file->asset->path,
1768                                 new_asset->path))
1769                         {
1770                                 got_it = 1;
1771                                 break;
1772                         }
1773                 }
1774
1775                 mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
1776                 got_indexes = 1;
1777                 edl->assets->update(new_asset);
1778         }
1779 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1780
1781 // Start examining next batch of index files
1782         if(got_indexes) mainindexes->start_build();
1783 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1784
1785 // Open plugin GUIs
1786         Track *track = edl->tracks->first;
1787         while(track)
1788         {
1789                 for(int j = 0; j < track->plugin_set.size(); j++)
1790                 {
1791                         PluginSet *plugins = track->plugin_set[j];
1792                         Plugin *plugin = plugins->get_first_plugin();
1793
1794                         while(plugin)
1795                         {
1796                                 if(load_mode == LOADMODE_REPLACE ||
1797                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
1798                                 {
1799                                         if(plugin->plugin_type == PLUGIN_STANDALONE &&
1800                                                 plugin->show)
1801                                         {
1802                                                 show_plugin(plugin);
1803                                         }
1804                                 }
1805
1806                                 plugin = (Plugin*)plugin->next;
1807                         }
1808                 }
1809
1810                 track = track->next;
1811         }
1812
1813         // if just opening one new resource in replace mode
1814         if( ftype != FILE_IS_XML &&
1815             ( load_mode == LOADMODE_REPLACE ||
1816               load_mode == LOADMODE_REPLACE_CONCATENATE ) ) {
1817                 select_asset(0, 0);
1818                 edl->local_session->preview_start = 0;
1819                 edl->local_session->preview_end = edl->tracks->total_playable_length();
1820                 edl->local_session->loop_playback = 0;
1821                 edl->local_session->set_selectionstart(0);
1822                 edl->local_session->set_selectionend(0);
1823                 set_brender_active(0, 0);
1824                 fit_selection();
1825                 goto_start();
1826         }
1827
1828 // need to update undo before project, since mwindow is unlocked & a new load
1829 // can begin here.  Should really prevent loading until we're done.
1830 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1831         undo->update_undo_after(_("load"), LOAD_ALL);
1832
1833         for(int i = 0; i < new_edls.size(); i++)
1834         {
1835                 new_edls[i]->remove_user();
1836         }
1837 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1838
1839         new_edls.remove_all();
1840
1841         for(int i = 0; i < new_assets.size(); i++)
1842         {
1843                 new_assets[i]->Garbage::remove_user();
1844         }
1845
1846         new_assets.remove_all();
1847         new_files.remove_all_objects();
1848
1849
1850 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1851         if(load_mode == LOADMODE_REPLACE ||
1852                 load_mode == LOADMODE_REPLACE_CONCATENATE)
1853         {
1854                 session->changes_made = 0;
1855         }
1856         else
1857         {
1858                 session->changes_made = 1;
1859         }
1860
1861         gui->stop_hourglass();
1862
1863
1864 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1865         update_project(load_mode);
1866
1867 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1868
1869         return 0;
1870 }
1871
1872
1873
1874
1875 void MWindow::test_plugins(EDL *new_edl, char *path)
1876 {
1877         char string[BCTEXTLEN];
1878
1879 // Do a check weather plugins exist
1880         for(Track *track = new_edl->tracks->first; track; track = track->next)
1881         {
1882                 for(int k = 0; k < track->plugin_set.total; k++)
1883                 {
1884                         PluginSet *plugin_set = track->plugin_set[k];
1885                         for(Plugin *plugin = (Plugin*)plugin_set->first;
1886                                 plugin;
1887                                 plugin = (Plugin*)plugin->next)
1888                         {
1889                                 if(plugin->plugin_type == PLUGIN_STANDALONE)
1890                                 {
1891 // ok we need to find it in plugindb
1892                                         int plugin_found = 0;
1893
1894                                         for(int j = 0; j < plugindb->size(); j++)
1895                                         {
1896                                                 PluginServer *server = plugindb->get(j);
1897                                                 if(server->title &&
1898                                                         !strcasecmp(server->title, plugin->title) &&
1899                                                         ((track->data_type == TRACK_AUDIO && server->audio) ||
1900                                                         (track->data_type == TRACK_VIDEO && server->video)) &&
1901                                                         (!server->transition))
1902                                                         plugin_found = 1;
1903                                         }
1904
1905                                         if (!plugin_found)
1906                                         {
1907                                                 sprintf(string,
1908         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
1909           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
1910                                                         "effect", plugin->title,
1911                                                         path);
1912                                                 MainError::show_error(string);
1913                                         }
1914                                 }
1915                         }
1916                 }
1917
1918                 for(Edit *edit = (Edit*)track->edits->first;
1919                         edit;
1920                         edit = (Edit*)edit->next)
1921                 {
1922                         if (edit->transition)
1923                         {
1924 // ok we need to find transition in plugindb
1925
1926                                 int transition_found = 0;
1927                                 for(int j = 0; j < plugindb->size(); j++)
1928                                 {
1929                                         PluginServer *server = plugindb->get(j);
1930                                         if(server->title &&
1931                                                 !strcasecmp(server->title, edit->transition->title) &&
1932                                                 ((track->data_type == TRACK_AUDIO && server->audio) ||
1933                                                 (track->data_type == TRACK_VIDEO && server->video)) &&
1934                                                 (server->transition))
1935                                                 transition_found = 1;
1936                                 }
1937
1938                                 if (!transition_found)
1939                                 {
1940                                         sprintf(string,
1941         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
1942           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
1943                                                 "transition", edit->transition->title,
1944                                                 path);
1945                                         MainError::show_error(string);
1946                                 }
1947                         }
1948                 }
1949         }
1950 }
1951
1952
1953 void MWindow::init_shm()
1954 {
1955 // Fix shared memory
1956         FILE *fd = fopen("/proc/sys/kernel/shmmax", "w");
1957         if(fd) {
1958                 fprintf(fd, "0x7fffffff");
1959                 fclose(fd);
1960         }
1961         fd = 0;
1962
1963         fd = fopen("/proc/sys/kernel/shmmax", "r");
1964         if(!fd) {
1965                 MainError::show_error("MWindow::init_shm: couldn't open /proc/sys/kernel/shmmax for reading.\n");
1966                 return;
1967         }
1968
1969         int64_t result = 0;
1970         fscanf(fd, "%jd", &result);
1971         fclose(fd);
1972         fd = 0;
1973         if(result < 0x7fffffff) {
1974                 eprintf(_("MWindow::init_shm: /proc/sys/kernel/shmmax is %p.\n"
1975                         "you probably need to be root, or:\n"
1976                         "as root, run: echo 0x7fffffff > /proc/sys/kernel/shmmax\n"
1977                         "before trying to start cinelerra.\n"
1978                         "It should be at least 0x7fffffff for Cinelerra.\n"), (void *)result);
1979         }
1980 }
1981
1982 void MWindow::create_objects(int want_gui,
1983         int want_new,
1984         char *config_path)
1985 {
1986         FileSystem fs;
1987         const int debug = 0;
1988         if(debug) PRINT_TRACE
1989
1990 // For some reason, init_signals must come after show_splash or the signals won't
1991 // get trapped.
1992         init_signals();
1993         if(debug) PRINT_TRACE
1994         init_3d();
1995
1996         if(debug) PRINT_TRACE
1997         show_splash();
1998
1999         if(debug) PRINT_TRACE
2000         default_standard = default_std();
2001         init_defaults(defaults, config_path);
2002         check_language();
2003         init_preferences();
2004         if(splash_window)
2005                 splash_window->operation->update(_("Initializing Plugins"));
2006         init_plugins(this, preferences);
2007         if(debug) PRINT_TRACE
2008         init_ladspa_plugins(this, preferences);
2009         if(debug) PRINT_TRACE
2010         init_plugin_tips(*plugindb);
2011         if(splash_window)
2012                 splash_window->operation->update(_("Initializing GUI"));
2013         if(debug) PRINT_TRACE
2014         init_theme();
2015
2016         if(debug) PRINT_TRACE
2017         init_error();
2018
2019         if(splash_window)
2020                 splash_window->operation->update(_("Initializing Fonts"));
2021         char string[BCTEXTLEN];
2022         strcpy(string, preferences->plugin_dir);
2023         strcat(string, "/" FONT_SEARCHPATH);
2024         BC_Resources::init_fontconfig(string);
2025         if(debug) PRINT_TRACE
2026
2027 // Initialize before too much else is running
2028 // Preferences & theme are required for building MPEG table of contents
2029
2030 // Default project created here
2031         init_edl();
2032         if(debug) PRINT_TRACE
2033
2034         init_cache();
2035         if(debug) PRINT_TRACE
2036
2037         Timer timer;
2038
2039         init_awindow();
2040         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2041
2042         init_compositor();
2043         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2044
2045 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2046         if(session->show_vwindow)
2047                 get_viewer(1, DEFAULT_VWINDOW);
2048         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2049
2050         init_gui();
2051         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2052
2053         init_levelwindow();
2054         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2055
2056         init_indexes();
2057         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2058
2059         init_channeldb();
2060         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2061
2062         init_gwindow();
2063         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2064
2065         init_render();
2066         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2067
2068         init_brender();
2069         init_exportedl();
2070         init_commercials();
2071         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2072         mainprogress = new MainProgress(this, gui);
2073         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2074         undo = new MainUndo(this);
2075
2076         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2077
2078         plugin_guis = new ArrayList<PluginServer*>;
2079         dead_plugins = new ArrayList<PluginServer*>;
2080         keyframe_threads = new ArrayList<KeyFrameThread*>;
2081
2082         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2083                 __LINE__,
2084                 vwindows.size(),
2085                 session->show_vwindow);
2086
2087 // Show all vwindows
2088 //      if(session->show_vwindow) {
2089 //              for(int j = 0; j < vwindows.size(); j++) {
2090 //                      VWindow *vwindow = vwindows[j];
2091 //                      if( !vwindow->is_running() ) continue;
2092 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2093 //                              __LINE__,
2094 //                              vwindow);
2095 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2096 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2097 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2098 //                      vwindow->gui->show_window();
2099 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2100 //                      vwindow->gui->unlock_window();
2101 //              }
2102 //      }
2103
2104
2105         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2106
2107         if(session->show_cwindow)
2108         {
2109                 cwindow->gui->lock_window("MWindow::create_objects 1");
2110                 cwindow->gui->show_window();
2111                 cwindow->gui->unlock_window();
2112         }
2113
2114         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2115         if(session->show_awindow)
2116         {
2117                 awindow->gui->lock_window("MWindow::create_objects 1");
2118                 awindow->gui->show_window();
2119                 awindow->gui->unlock_window();
2120         }
2121
2122         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2123         if(session->show_lwindow)
2124         {
2125                 lwindow->gui->lock_window("MWindow::create_objects 1");
2126                 lwindow->gui->show_window();
2127                 lwindow->gui->unlock_window();
2128         }
2129
2130         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2131                 __LINE__,
2132                 (int)timer.get_difference(),
2133                 gwindow->gui);
2134         if(session->show_gwindow)
2135         {
2136                 gwindow->gui->lock_window("MWindow::create_objects 1");
2137                 gwindow->gui->show_window();
2138                 gwindow->gui->unlock_window();
2139         }
2140
2141         if(debug) PRINT_TRACE
2142
2143         gui->lock_window("MWindow::create_objects 1");
2144         gui->mainmenu->load_defaults(defaults);
2145         gui->mainmenu->update_toggles(0);
2146         gui->update_patchbay();
2147         gui->draw_canvas(0, 0);
2148         gui->draw_cursor(1);
2149         gui->show_window();
2150         gui->raise_window();
2151         gui->unlock_window();
2152
2153         if(debug) PRINT_TRACE
2154
2155         if(preferences->use_tipwindow)
2156                 init_tipwindow();
2157         if(debug) PRINT_TRACE
2158
2159         gui->add_keyboard_listener(
2160                 (int (BC_WindowBase::*)(BC_WindowBase *))
2161                 &MWindowGUI::keyboard_listener);
2162
2163         hide_splash();
2164         init_shm();
2165         if(debug) PRINT_TRACE
2166
2167         BC_WindowBase::get_resources()->vframe_shm = 1;
2168 }
2169
2170
2171 void MWindow::show_splash()
2172 {
2173 #include "data/heroine_logo9_png.h"
2174         VFrame *frame = new VFramePng(heroine_logo9_png);
2175         BC_DisplayInfo dpyi;
2176         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2177         int rr = (rw < rh ? rw : rh) / 4;
2178         splash_window = new SplashGUI(frame, rr, rr);
2179         splash_window->create_objects();
2180 }
2181
2182 void MWindow::hide_splash()
2183 {
2184         if(splash_window)
2185                 delete splash_window;
2186         splash_window = 0;
2187 }
2188
2189
2190 void MWindow::start()
2191 {
2192 ENABLE_BUFFER
2193 //PRINT_TRACE
2194 //      vwindows[DEFAULT_VWINDOW]->start();
2195         awindow->start();
2196 //PRINT_TRACE
2197         cwindow->start();
2198 //PRINT_TRACE
2199         lwindow->start();
2200 //PRINT_TRACE
2201         gwindow->start();
2202 //PRINT_TRACE
2203 //      Thread::start();
2204 //PRINT_TRACE
2205         playback_3d->start();
2206 //PRINT_TRACE
2207 }
2208
2209 void MWindow::run()
2210 {
2211         run_lock->lock("MWindow::run");
2212         gui->run_window();
2213         stop_playback(1);
2214
2215         brender_lock->lock("MWindow::run 1");
2216         delete brender;         brender = 0;
2217         brender_lock->unlock();
2218
2219         interrupt_indexes();
2220         clean_indexes();
2221         save_defaults();
2222         run_lock->unlock();
2223 }
2224
2225 void MWindow::show_vwindow()
2226 {
2227         int total_running = 0;
2228         session->show_vwindow = 1;
2229
2230 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2231 // Raise all windows which are visible
2232         for(int j = 0; j < vwindows.size(); j++) {
2233                 VWindow *vwindow = vwindows[j];
2234                 if( !vwindow->is_running() ) continue;
2235                 vwindow->gui->lock_window("MWindow::show_vwindow");
2236                 vwindow->gui->show_window(0);
2237                 vwindow->gui->raise_window();
2238                 vwindow->gui->flush();
2239                 vwindow->gui->unlock_window();
2240                 total_running++;
2241         }
2242
2243 // If no windows visible
2244         if(!total_running)
2245         {
2246                 get_viewer(1, DEFAULT_VWINDOW);
2247         }
2248
2249         gui->mainmenu->show_vwindow->set_checked(1);
2250 }
2251
2252 void MWindow::show_awindow()
2253 {
2254         session->show_awindow = 1;
2255         awindow->gui->lock_window("MWindow::show_awindow");
2256         awindow->gui->show_window();
2257         awindow->gui->raise_window();
2258         awindow->gui->flush();
2259         awindow->gui->unlock_window();
2260         gui->mainmenu->show_awindow->set_checked(1);
2261 }
2262
2263 char *MWindow::get_cwindow_display()
2264 {
2265         char *x11_host = screens < 2 || session->window_config == 0 ?
2266                 session->a_x11_host : session->b_x11_host;
2267         return *x11_host ? x11_host : 0;
2268 }
2269
2270 void MWindow::show_cwindow()
2271 {
2272         session->show_cwindow = 1;
2273         cwindow->show_window();
2274         gui->mainmenu->show_cwindow->set_checked(1);
2275 }
2276
2277 void MWindow::show_gwindow()
2278 {
2279         session->show_gwindow = 1;
2280
2281         gwindow->gui->lock_window("MWindow::show_gwindow");
2282         gwindow->gui->show_window();
2283         gwindow->gui->raise_window();
2284         gwindow->gui->flush();
2285         gwindow->gui->unlock_window();
2286
2287         gui->mainmenu->show_gwindow->set_checked(1);
2288 }
2289 void MWindow::hide_gwindow()
2290 {
2291         session->show_gwindow = 0;
2292
2293         gwindow->gui->lock_window("MWindow::show_gwindow");
2294         gwindow->gui->hide_window();
2295         gwindow->gui->unlock_window();
2296 }
2297
2298 void MWindow::show_lwindow()
2299 {
2300         session->show_lwindow = 1;
2301         lwindow->gui->lock_window("MWindow::show_lwindow");
2302         lwindow->gui->show_window();
2303         lwindow->gui->raise_window();
2304         lwindow->gui->flush();
2305         lwindow->gui->unlock_window();
2306         gui->mainmenu->show_lwindow->set_checked(1);
2307 }
2308
2309 int MWindow::tile_windows(int window_config)
2310 {
2311         int need_reload = 0;
2312         int play_config = window_config==0 ? 0 : 1;
2313         edl->session->playback_config->load_defaults(defaults, play_config);
2314         session->default_window_positions(window_config);
2315         if( screens == 1 ) {
2316                 gui->default_positions();
2317                 sync_parameters(CHANGE_ALL);
2318         }
2319         else
2320                 need_reload = 1;
2321         return need_reload;
2322 }
2323
2324 void MWindow::toggle_loop_playback()
2325 {
2326         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2327         set_loop_boundaries();
2328         save_backup();
2329
2330         gui->draw_overlays(1);
2331         sync_parameters(CHANGE_PARAMS);
2332 }
2333
2334 //void MWindow::set_titles(int value)
2335 //{
2336 //      edl->session->show_titles = value;
2337 //      trackmovement(edl->local_session->track_start);
2338 //}
2339
2340 void MWindow::set_screens(int value)
2341 {
2342         screens = value;
2343 }
2344
2345 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2346 {
2347         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2348         edl->session->auto_keyframes = value;
2349         gui->mbuttons->edit_panel->keyframe->update(value);
2350         gui->flush();
2351         if(lock_mwindow) gui->unlock_window();
2352
2353         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2354         cwindow->gui->edit_panel->keyframe->update(value);
2355         cwindow->gui->flush();
2356         if(lock_cwindow) cwindow->gui->unlock_window();
2357 }
2358
2359 void MWindow::set_auto_visibility(Autos *autos, int value)
2360 {
2361         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2362                 edl->session->auto_conf->plugins = value;
2363         else if( autos->autoidx >= 0 )
2364                 edl->session->auto_conf->autos[autos->autoidx] = value;
2365         else
2366                 return;
2367
2368         gui->update(0, 1, 0, 0, 0, 0, 0);
2369         gui->mainmenu->update_toggles(1);
2370         gui->unlock_window();
2371         gwindow->gui->update_toggles(1);
2372         gui->lock_window("MWindow::set_auto_visibility");
2373 }
2374
2375 void MWindow::set_keyframe_type(int mode)
2376 {
2377         gui->lock_window("MWindow::set_keyframe_type");
2378         edl->local_session->floatauto_type = mode;
2379         gui->mainmenu->update_toggles(0);
2380         gui->unlock_window();
2381 }
2382
2383 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
2384 {
2385         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
2386         edl->session->editing_mode = new_editing_mode;
2387         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
2388         gui->mbuttons->edit_panel->update();
2389         gui->set_editing_mode(1);
2390         if(lock_mwindow) gui->unlock_window();
2391
2392
2393         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
2394         cwindow->gui->edit_panel->update();
2395         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
2396         if(lock_cwindow) cwindow->gui->unlock_window();
2397         return 0;
2398 }
2399
2400 void MWindow::toggle_editing_mode()
2401 {
2402         int mode = edl->session->editing_mode;
2403         if( mode == EDITING_ARROW )
2404                 set_editing_mode(EDITING_IBEAM, 0, 1);
2405         else
2406                 set_editing_mode(EDITING_ARROW, 0, 1);
2407 }
2408
2409
2410 void MWindow::set_labels_follow_edits(int value)
2411 {
2412         gui->lock_window("MWindow::set_labels_follow_edits");
2413         edl->session->labels_follow_edits = value;
2414         gui->mbuttons->edit_panel->locklabels->update(value);
2415         gui->mainmenu->labels_follow_edits->set_checked(value);
2416         gui->flush();
2417         gui->unlock_window();
2418 }
2419
2420 void MWindow::sync_parameters(int change_type)
2421 {
2422         if( in_destructor ) return;
2423
2424 // Sync engines which are playing back
2425         if(cwindow->playback_engine->is_playing_back)
2426         {
2427                 if(change_type == CHANGE_PARAMS)
2428                 {
2429 // TODO: block keyframes until synchronization is done
2430                         cwindow->playback_engine->sync_parameters(edl);
2431                 }
2432                 else
2433 // Stop and restart
2434                 {
2435                         int command = cwindow->playback_engine->command->command;
2436                         cwindow->playback_engine->que->send_command(STOP,
2437                                 CHANGE_NONE,
2438                                 0,
2439                                 0);
2440 // Waiting for tracking to finish would make the restart position more
2441 // accurate but it can't lock the window to stop tracking for some reason.
2442 // Not waiting for tracking gives a faster response but restart position is
2443 // only as accurate as the last tracking update.
2444                         cwindow->playback_engine->interrupt_playback(0);
2445                         cwindow->playback_engine->que->send_command(command,
2446                                         change_type,
2447                                         edl,
2448                                         1,
2449                                         0);
2450                 }
2451         }
2452         else
2453         {
2454                 cwindow->playback_engine->que->send_command(CURRENT_FRAME,
2455                                                         change_type,
2456                                                         edl,
2457                                                         1);
2458         }
2459 }
2460
2461 void MWindow::age_caches()
2462 {
2463 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
2464 // __LINE__,
2465 // preferences->cache_size,
2466 // audio_cache->get_memory_usage(1),
2467 // video_cache->get_memory_usage(1),
2468 // frame_cache->get_memory_usage(),
2469 // wave_cache->get_memory_usage(),
2470 // memory_usage);
2471         frame_cache->age_cache(512);
2472         wave_cache->age_cache(8192);
2473
2474         int64_t memory_usage;
2475         int64_t prev_memory_usage = 0;
2476         int result = 0;
2477         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
2478         while( !result && prev_memory_usage !=
2479                 (memory_usage=video_cache->get_memory_usage(1)) &&
2480                 memory_usage > video_size ) {
2481                 video_cache->delete_oldest();
2482                 prev_memory_usage = memory_usage;
2483         }
2484
2485         prev_memory_usage = 0;
2486         result = 0;
2487         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
2488         while( !result && prev_memory_usage !=
2489                 (memory_usage=audio_cache->get_memory_usage(1)) &&
2490                 memory_usage > audio_size ) {
2491                 audio_cache->delete_oldest();
2492                 prev_memory_usage = memory_usage;
2493         }
2494 }
2495
2496 void MWindow::reset_android_remote()
2497 {
2498         gui->use_android_remote(preferences->android_remote);
2499 }
2500
2501
2502 void MWindow::show_keyframe_gui(Plugin *plugin)
2503 {
2504         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
2505 // Find existing thread
2506         for(int i = 0; i < keyframe_threads->size(); i++)
2507         {
2508                 if(keyframe_threads->get(i)->plugin == plugin)
2509                 {
2510                         keyframe_threads->get(i)->start_window(plugin, 0);
2511                         keyframe_gui_lock->unlock();
2512                         return;
2513                 }
2514         }
2515
2516 // Find unused thread
2517         for(int i = 0; i < keyframe_threads->size(); i++)
2518         {
2519                 if(!keyframe_threads->get(i)->plugin)
2520                 {
2521                         keyframe_threads->get(i)->start_window(plugin, 0);
2522                         keyframe_gui_lock->unlock();
2523                         return;
2524                 }
2525         }
2526
2527 // Create new thread
2528         KeyFrameThread *thread = new KeyFrameThread(this);
2529         keyframe_threads->append(thread);
2530         thread->start_window(plugin, 0);
2531
2532         keyframe_gui_lock->unlock();
2533 }
2534
2535
2536
2537
2538
2539 void MWindow::show_plugin(Plugin *plugin)
2540 {
2541         int done = 0;
2542
2543 SET_TRACE
2544 // Remove previously deleted plugin GUIs
2545         dead_plugin_lock->lock("MWindow::show_plugin");
2546         dead_plugins->remove_all_objects();
2547         dead_plugin_lock->unlock();
2548
2549 //printf("MWindow::show_plugin %d\n", __LINE__);
2550 SET_TRACE
2551
2552
2553         plugin_gui_lock->lock("MWindow::show_plugin");
2554         for(int i = 0; i < plugin_guis->total; i++)
2555         {
2556 // Pointer comparison
2557                 if(plugin_guis->get(i)->plugin == plugin)
2558                 {
2559                         plugin_guis->get(i)->raise_window();
2560                         done = 1;
2561                         break;
2562                 }
2563         }
2564 SET_TRACE
2565
2566 //printf("MWindow::show_plugin 1\n");
2567         if(!done)
2568         {
2569                 if(!plugin->track)
2570                 {
2571                         printf("MWindow::show_plugin track not defined.\n");
2572                 }
2573                 PluginServer *server = scan_plugindb(plugin->title,
2574                         plugin->track->data_type);
2575
2576 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
2577                 if(server && server->uses_gui)
2578                 {
2579                         PluginServer *gui = new PluginServer(*server);
2580                         plugin_guis->append(gui);
2581 // Needs mwindow to do GUI
2582                         gui->set_mwindow(this);
2583                         gui->open_plugin(0, preferences, edl, plugin);
2584                         plugin->show = 1;
2585                         gui->show_gui();
2586                 }
2587         }
2588         plugin_gui_lock->unlock();
2589 //printf("MWindow::show_plugin %d\n", __LINE__);
2590 SET_TRACE
2591 //sleep(1);
2592 //printf("MWindow::show_plugin 2\n");
2593 }
2594
2595 void MWindow::hide_plugin(Plugin *plugin, int lock)
2596 {
2597         plugin->show = 0;
2598 // Update the toggle
2599         gui->lock_window("MWindow::hide_plugin");
2600         gui->update(0, 1, 0, 0, 0, 0, 0);
2601         gui->unlock_window();
2602
2603         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
2604         for(int i = 0; i < plugin_guis->total; i++)
2605         {
2606                 if(plugin_guis->get(i)->plugin == plugin)
2607                 {
2608                         PluginServer *ptr = plugin_guis->get(i);
2609                         plugin_guis->remove(ptr);
2610                         if(lock) plugin_gui_lock->unlock();
2611 // Last command executed in client side close
2612 // Schedule for deletion
2613                         ptr->hide_gui();
2614                         delete_plugin(ptr);
2615 //sleep(1);
2616                         return;
2617                 }
2618         }
2619         if(lock) plugin_gui_lock->unlock();
2620 }
2621
2622 void MWindow::delete_plugin(PluginServer *plugin)
2623 {
2624         dead_plugin_lock->lock("MWindow::delete_plugin");
2625         dead_plugins->append(plugin);
2626         dead_plugin_lock->unlock();
2627 }
2628
2629 void MWindow::hide_plugins()
2630 {
2631         plugin_gui_lock->lock("MWindow::hide_plugins 1");
2632         while(plugin_guis->size())
2633         {
2634                 PluginServer *ptr = plugin_guis->get(0);
2635                 plugin_guis->remove(ptr);
2636                 plugin_gui_lock->unlock();
2637 // Last command executed in client side close
2638 // Schedule for deletion
2639                 ptr->hide_gui();
2640                 delete_plugin(ptr);
2641                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
2642         }
2643         plugin_gui_lock->unlock();
2644
2645         hide_keyframe_guis();
2646 }
2647
2648 void MWindow::hide_keyframe_guis()
2649 {
2650         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
2651         for(int i = 0; i < keyframe_threads->size(); i++)
2652         {
2653                 keyframe_threads->get(i)->close_window();
2654         }
2655         keyframe_gui_lock->unlock();
2656 }
2657
2658 void MWindow::hide_keyframe_gui(Plugin *plugin)
2659 {
2660         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
2661         for(int i = 0; i < keyframe_threads->size(); i++)
2662         {
2663                 if(keyframe_threads->get(i)->plugin == plugin)
2664                 {
2665                         keyframe_threads->get(i)->close_window();
2666                         break;
2667                 }
2668         }
2669         keyframe_gui_lock->unlock();
2670 }
2671
2672 void MWindow::update_keyframe_guis()
2673 {
2674 // Send new configuration to keyframe GUI's
2675         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
2676         for(int i = 0; i < keyframe_threads->size(); i++)
2677         {
2678                 KeyFrameThread *ptr = keyframe_threads->get(i);
2679                 if(edl->tracks->plugin_exists(ptr->plugin))
2680                         ptr->update_gui(1);
2681                 else
2682                 {
2683                         ptr->close_window();
2684                 }
2685         }
2686         keyframe_gui_lock->unlock();
2687 }
2688
2689 void MWindow::update_plugin_guis(int do_keyframe_guis)
2690 {
2691 // Send new configuration to plugin GUI's
2692         plugin_gui_lock->lock("MWindow::update_plugin_guis");
2693
2694         for(int i = 0; i < plugin_guis->size(); i++)
2695         {
2696                 PluginServer *ptr = plugin_guis->get(i);
2697                 if(edl->tracks->plugin_exists(ptr->plugin))
2698                         ptr->update_gui();
2699                 else
2700                 {
2701 // Schedule for deletion if no plugin
2702                         plugin_guis->remove_number(i);
2703                         i--;
2704
2705                         ptr->hide_gui();
2706                         delete_plugin(ptr);
2707                 }
2708         }
2709
2710
2711 // Change plugin variable if not visible
2712         Track *track = edl->tracks->first;
2713         while(track)
2714         {
2715                 for(int i = 0; i < track->plugin_set.size(); i++)
2716                 {
2717                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
2718                         while(plugin)
2719                         {
2720                                 int got_it = 0;
2721                                 for(int i = 0; i < plugin_guis->size(); i++)
2722                                 {
2723                                         PluginServer *server = plugin_guis->get(i);
2724                                         if(server->plugin == plugin)
2725                                         {
2726                                                 got_it = 1;
2727                                                 break;
2728                                         }
2729                                 }
2730
2731                                 if(!got_it) plugin->show = 0;
2732
2733                                 plugin = (Plugin*)plugin->next;
2734                         }
2735                 }
2736
2737                 track = track->next;
2738         }
2739
2740         plugin_gui_lock->unlock();
2741
2742
2743         if(do_keyframe_guis) update_keyframe_guis();
2744 }
2745
2746 int MWindow::plugin_gui_open(Plugin *plugin)
2747 {
2748         int result = 0;
2749         plugin_gui_lock->lock("MWindow::plugin_gui_open");
2750         for(int i = 0; i < plugin_guis->total; i++)
2751         {
2752                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2753                 {
2754                         result = 1;
2755                         break;
2756                 }
2757         }
2758         plugin_gui_lock->unlock();
2759         return result;
2760 }
2761
2762 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
2763 {
2764         plugin_gui_lock->lock("MWindow::render_plugin_gui");
2765         for(int i = 0; i < plugin_guis->total; i++)
2766         {
2767                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2768                 {
2769                         plugin_guis->get(i)->render_gui(data);
2770                         break;
2771                 }
2772         }
2773         plugin_gui_lock->unlock();
2774 }
2775
2776 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
2777 {
2778         plugin_gui_lock->lock("MWindow::render_plugin_gui");
2779         for(int i = 0; i < plugin_guis->total; i++)
2780         {
2781                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2782                 {
2783                         plugin_guis->get(i)->render_gui(data, size);
2784                         break;
2785                 }
2786         }
2787         plugin_gui_lock->unlock();
2788 }
2789
2790
2791 void MWindow::update_plugin_states()
2792 {
2793         plugin_gui_lock->lock("MWindow::update_plugin_states");
2794         for(int i = 0; i < plugin_guis->total; i++)
2795         {
2796                 int result = 0;
2797 // Get a plugin GUI
2798                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
2799                 PluginServer *src_plugingui = plugin_guis->get(i);
2800
2801 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
2802                 for(Track *track = edl->tracks->first;
2803                         track && !result;
2804                         track = track->next)
2805                 {
2806                         for(int j = 0;
2807                                 j < track->plugin_set.total && !result;
2808                                 j++)
2809                         {
2810                                 PluginSet *plugin_set = track->plugin_set[j];
2811                                 for(Plugin *plugin = (Plugin*)plugin_set->first;
2812                                         plugin && !result;
2813                                         plugin = (Plugin*)plugin->next)
2814                                 {
2815                                         if(plugin == src_plugin &&
2816                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
2817                                 }
2818                         }
2819                 }
2820
2821
2822 // Doesn't exist anymore
2823                 if(!result)
2824                 {
2825                         hide_plugin(src_plugin, 0);
2826                         i--;
2827                 }
2828         }
2829         plugin_gui_lock->unlock();
2830 }
2831
2832
2833 void MWindow::update_plugin_titles()
2834 {
2835         for(int i = 0; i < plugin_guis->total; i++)
2836         {
2837                 plugin_guis->get(i)->update_title();
2838         }
2839 }
2840
2841 int MWindow::asset_to_edl(EDL *new_edl,
2842         Asset *new_asset,
2843         RecordLabels *labels)
2844 {
2845 const int debug = 0;
2846 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
2847 __LINE__,
2848 new_asset->layers);
2849 // Keep frame rate, sample rate, and output size unchanged.
2850 // These parameters would revert the project if VWindow displayed an asset
2851 // of different size than the project.
2852         if(new_asset->video_data)
2853         {
2854                 new_edl->session->video_tracks = new_asset->layers;
2855         }
2856         else
2857                 new_edl->session->video_tracks = 0;
2858
2859 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2860
2861
2862
2863
2864
2865         if(new_asset->audio_data)
2866         {
2867                 new_edl->session->audio_tracks = new_asset->channels;
2868         }
2869         else
2870                 new_edl->session->audio_tracks = 0;
2871 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
2872
2873 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2874         new_edl->create_default_tracks();
2875 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
2876 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2877
2878
2879
2880 //printf("MWindow::asset_to_edl 3\n");
2881         new_edl->insert_asset(new_asset,
2882                 0,
2883                 0,
2884                 0,
2885                 labels);
2886 //printf("MWindow::asset_to_edl 3\n");
2887 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2888
2889 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
2890         if(edl->session->cursor_on_frames)
2891         {
2892                 double length = new_edl->tracks->total_length();
2893                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
2894                 new_edl->tracks->clear(length, edl_length, 1, 1);
2895         }
2896
2897
2898
2899
2900         char string[BCTEXTLEN];
2901         FileSystem fs;
2902         fs.extract_name(string, new_asset->path);
2903 //printf("MWindow::asset_to_edl 3\n");
2904
2905         strcpy(new_edl->local_session->clip_title, string);
2906 //printf("MWindow::asset_to_edl 4 %s\n", string);
2907 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2908
2909         return 0;
2910 }
2911
2912 int MWindow::edl_to_nested(EDL *new_edl,
2913         EDL *nested_edl)
2914 {
2915
2916 // Keep frame rate, sample rate, and output size unchanged.
2917 // These parameters would revert the project if VWindow displayed an asset
2918 // of different size than the project.
2919
2920
2921
2922 // Nest all video & audio outputs
2923         new_edl->session->video_tracks = 1;
2924         new_edl->session->audio_tracks = nested_edl->session->audio_channels;
2925         new_edl->create_default_tracks();
2926
2927
2928
2929         new_edl->insert_asset(0,
2930                 nested_edl,
2931                 0,
2932                 0,
2933                 0);
2934
2935         char string[BCTEXTLEN];
2936         FileSystem fs;
2937         fs.extract_name(string, nested_edl->path);
2938 //printf("MWindow::edl_to_nested %p %s\n", nested_edl, nested_edl->path);
2939
2940         strcpy(new_edl->local_session->clip_title, string);
2941
2942         return 0;
2943 }
2944
2945 // Reset everything after a load.
2946 void MWindow::update_project(int load_mode)
2947 {
2948         const int debug = 0;
2949
2950         if(debug) PRINT_TRACE
2951         init_brender();
2952         edl->tracks->update_y_pixels(theme);
2953
2954         if(debug) PRINT_TRACE
2955
2956         if(load_mode == LOADMODE_REPLACE ||
2957                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2958         {
2959                 gui->load_panes();
2960         }
2961
2962         gui->update(1, 1, 1, 1, 1, 1, 1);
2963         if(debug) PRINT_TRACE
2964         gui->unlock_window();
2965
2966         cwindow->gui->lock_window("MWindow::update_project 1");
2967         cwindow->update(0, 0, 1, 1, 1);
2968         cwindow->gui->unlock_window();
2969
2970         if(debug) PRINT_TRACE
2971
2972 // Close all the vwindows
2973         if(load_mode == LOADMODE_REPLACE ||
2974                 load_mode == LOADMODE_REPLACE_CONCATENATE) {
2975                 if(debug) PRINT_TRACE
2976                 int first_vwindow = 0;
2977                 if(session->show_vwindow) first_vwindow = 1;
2978 // Change visible windows to no source
2979                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
2980                         VWindow *vwindow = vwindows[i];
2981                         if( !vwindow->is_running() ) continue;
2982                         vwindow->change_source(-1);
2983                 }
2984
2985 // Close remaining windows
2986                 for(int i = first_vwindow; i < vwindows.size(); i++) {
2987                         VWindow *vwindow = vwindows[i];
2988                         if( !vwindow->is_running() ) continue;
2989                         vwindow->close_window();
2990                 }
2991                 if(debug) PRINT_TRACE
2992         }
2993         else if(vwindows.size()) {
2994                 VWindow *vwindow = vwindows[DEFAULT_VWINDOW];
2995                 if( vwindow->is_running() ) {
2996                         vwindow->gui->lock_window("MWindow::update_project");
2997                         vwindow->update(1);
2998                         vwindow->gui->unlock_window();
2999                 }
3000         }
3001
3002         if(debug) PRINT_TRACE
3003         cwindow->gui->lock_window("MWindow::update_project 2");
3004         cwindow->gui->timebar->update(0);
3005         cwindow->gui->unlock_window();
3006
3007         if(debug) PRINT_TRACE
3008         cwindow->playback_engine->que->send_command(CURRENT_FRAME,
3009                 CHANGE_ALL,
3010                 edl,
3011                 1);
3012
3013         awindow->gui->async_update_assets();
3014         if(debug) PRINT_TRACE
3015
3016         gui->lock_window("MWindow::update_project");
3017         gui->flush();
3018         if(debug) PRINT_TRACE
3019 }
3020
3021 void MWindow::remove_indexfile(Indexable *indexable)
3022 {
3023         if( !indexable->is_asset ) return;
3024         Asset *asset = (Asset *)indexable;
3025 // Erase file
3026         IndexFile::delete_index(preferences, asset, ".toc");
3027         IndexFile::delete_index(preferences, asset, ".idx");
3028         IndexFile::delete_index(preferences, asset, ".mkr");
3029 }
3030
3031 void MWindow::rebuild_indices()
3032 {
3033         for(int i = 0; i < session->drag_assets->total; i++)
3034         {
3035                 Indexable *indexable = session->drag_assets->get(i);
3036 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3037                 remove_indexfile(indexable);
3038 // Schedule index build
3039                 IndexState *index_state = indexable->index_state;
3040                 index_state->index_status = INDEX_NOTTESTED;
3041                 if( indexable->is_asset ) {
3042                         Asset *asset = (Asset *)indexable;
3043                         if( asset->format != FILE_PCM ) {
3044                                 asset->format = FILE_UNKNOWN;
3045                                 asset->reset_audio();
3046                         }
3047                         asset->reset_video();
3048 //                      File file; // re-probe the asset
3049 //                      file.open_file(preferences, asset, 1, 0);
3050                 }
3051                 mainindexes->add_next_asset(0, indexable);
3052         }
3053         mainindexes->start_build();
3054 }
3055
3056
3057 void MWindow::save_backup()
3058 {
3059         FileXML file;
3060         edl->optimize();
3061         edl->set_path(session->filename);
3062         char backup_path[BCTEXTLEN];
3063         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3064                 File::get_config_path(), BACKUP_FILE);
3065         edl->save_xml(&file, backup_path, 0, 0);
3066         file.terminate_string();
3067         FileSystem fs;
3068         fs.complete_path(backup_path);
3069
3070         if(file.write_to_file(backup_path))
3071         {
3072                 char string2[256];
3073                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
3074                 gui->show_message(string2);
3075         }
3076 }
3077
3078 void MWindow::load_backup()
3079 {
3080         ArrayList<char*> path_list;
3081         path_list.set_array_delete();
3082         char *out_path;
3083         char backup_path[BCTEXTLEN];
3084         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3085                 File::get_config_path(), BACKUP_FILE);
3086         FileSystem fs;
3087         fs.complete_path(backup_path);
3088
3089         path_list.append(out_path = new char[strlen(backup_path) + 1]);
3090         strcpy(out_path, backup_path);
3091
3092         load_filenames(&path_list, LOADMODE_REPLACE, 0);
3093         edl->local_session->clip_title[0] = 0;
3094 // This is unique to backups since the path of the backup is different than the
3095 // path of the project.
3096         set_filename(edl->path);
3097         path_list.remove_all_objects();
3098         save_backup();
3099 }
3100
3101 static inline int gcd(int m, int n)
3102 {
3103         int r;
3104         if( m < n ) { r = m;  m = n;  n = r; }
3105         while( (r = m % n) != 0 ) { m = n;  n = r; }
3106         return n;
3107 }
3108
3109 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
3110 {
3111         w = 1;  h = 1;
3112         if(!width || !height) return 1;
3113         if( width == 720 && (height == 480 || height == 576) ) {
3114                 w = 4;  h = 3;  return 0; // for NTSC and PAL
3115         }
3116         double ar = (double)width / height;
3117 // square-ish pixels
3118         if( EQUIV(ar, 1.0000) ) return 0;
3119         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
3120         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
3121         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
3122         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
3123         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
3124         int ww = width, hh = height;
3125         // numerator, denominator must be under mx
3126         int mx = 255, n = gcd(ww, hh);
3127         if( n > 1 ) { ww /= n; hh /= n; }
3128         // search near height in case extra/missing lines
3129         if( ww >= mx || hh >= mx ) {
3130                 double err = height;  // +/- 2 percent height
3131                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
3132                         int iw = width, ih = height+i;
3133                         if( (n=gcd(iw, ih)) > 1 ) {
3134                                 int u = iw/n;  if( u >= mx ) continue;
3135                                 int v = ih/n;  if( v >= mx ) continue;
3136                                 double r = (double) u/v, er = fabs(ar-r);
3137                                 if( er >= err ) continue;
3138                                 err = er;  ww = u;  hh = v;
3139                         }
3140                 }
3141         }
3142
3143         w = ww;  h = hh;
3144         return 0;
3145 }
3146
3147 void MWindow::reset_caches()
3148 {
3149         frame_cache->remove_all();
3150         wave_cache->remove_all();
3151         audio_cache->remove_all();
3152         video_cache->remove_all();
3153         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3154                 cwindow->playback_engine->audio_cache->remove_all();
3155         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3156                 cwindow->playback_engine->video_cache->remove_all();
3157
3158         for(int i = 0; i < vwindows.size(); i++) {
3159                 VWindow *vwindow = vwindows[i];
3160                 if( !vwindow->is_running() ) continue;
3161                 if(vwindow->playback_engine && vwindow->playback_engine->audio_cache)
3162                         vwindow->playback_engine->audio_cache->remove_all();
3163                 if(vwindow->playback_engine && vwindow->playback_engine->video_cache)
3164                         vwindow->playback_engine->video_cache->remove_all();
3165         }
3166 }
3167
3168 void MWindow::remove_asset_from_caches(Asset *asset)
3169 {
3170         gui->resource_thread->get_video_source(0);
3171         gui->resource_thread->get_audio_source(0);
3172         frame_cache->remove_asset(asset);
3173         wave_cache->remove_asset(asset);
3174         audio_cache->delete_entry(asset);
3175         video_cache->delete_entry(asset);
3176         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3177                 cwindow->playback_engine->audio_cache->delete_entry(asset);
3178         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3179                 cwindow->playback_engine->video_cache->delete_entry(asset);
3180         for(int i = 0; i < vwindows.size(); i++) {
3181                 VWindow *vwindow = vwindows[i];
3182                 if( !vwindow->is_running() ) continue;
3183                 if(vwindow->playback_engine && vwindow->playback_engine->audio_cache)
3184                         vwindow->playback_engine->audio_cache->delete_entry(asset);
3185                 if(vwindow->playback_engine && vwindow->playback_engine->video_cache)
3186                         vwindow->playback_engine->video_cache->delete_entry(asset);
3187         }
3188 }
3189
3190
3191 void MWindow::remove_assets_from_project(int push_undo, int redraw,
3192                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
3193 {
3194         for(int i = 0; i < drag_assets->total; i++) {
3195                 Indexable *indexable = drag_assets->get(i);
3196                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
3197         }
3198
3199 // Remove from VWindow.
3200         for(int i = 0; i < session->drag_clips->total; i++) {
3201                 for(int j = 0; j < vwindows.size(); j++) {
3202                         VWindow *vwindow = vwindows[j];
3203                         if( !vwindow->is_running() ) continue;
3204                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
3205                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
3206                                 vwindow->delete_source(1, 1);
3207                                 vwindow->gui->unlock_window();
3208                         }
3209                 }
3210         }
3211
3212         for(int i = 0; i < drag_assets->size(); i++) {
3213                 for(int j = 0; j < vwindows.size(); j++) {
3214                         VWindow *vwindow = vwindows[j];
3215                         if( !vwindow->is_running() ) continue;
3216                         if(drag_assets->get(i) == vwindow->get_source()) {
3217                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
3218                                 vwindow->delete_source(1, 1);
3219                                 vwindow->gui->unlock_window();
3220                         }
3221                 }
3222         }
3223
3224         for(int i = 0; i < drag_assets->size(); i++) {
3225                 Indexable *indexable = drag_assets->get(i);
3226                 remove_indexfile(indexable);
3227         }
3228
3229 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3230         if(push_undo) undo->update_undo_before();
3231         if(drag_assets) edl->remove_from_project(drag_assets);
3232         if(drag_clips) edl->remove_from_project(drag_clips);
3233         if(redraw) save_backup();
3234         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
3235         if(redraw) {
3236                 restart_brender();
3237
3238                 gui->lock_window("MWindow::remove_assets_from_project 3");
3239                 gui->update(1, 1, 1, 1, 0, 1, 0);
3240                 gui->unlock_window();
3241
3242         // Removes from playback here
3243                 sync_parameters(CHANGE_ALL);
3244         }
3245
3246         awindow->gui->async_update_assets();
3247 }
3248
3249 void MWindow::remove_assets_from_disk()
3250 {
3251 // Remove from disk
3252         for(int i = 0; i < session->drag_assets->total; i++)
3253         {
3254                 remove(session->drag_assets->get(i)->path);
3255         }
3256
3257         remove_assets_from_project(1,
3258                 1,
3259                 session->drag_assets,
3260                 session->drag_clips);
3261 }
3262
3263 void MWindow::dump_plugins(FILE *fp)
3264 {
3265         if( !plugindb ) return;
3266         for(int i = 0; i < plugindb->total; i++)
3267         {
3268                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
3269                         " synth=%d transition=%d theme=%d %s\n",
3270                         plugindb->get(i)->plugin_type,
3271                         plugindb->get(i)->audio,
3272                         plugindb->get(i)->video,
3273                         plugindb->get(i)->realtime,
3274                         plugindb->get(i)->multichannel,
3275                         plugindb->get(i)->get_synthesis(),
3276                         plugindb->get(i)->transition,
3277                         plugindb->get(i)->theme,
3278                         plugindb->get(i)->title);
3279         }
3280 }
3281
3282 void MWindow::dump_edl(FILE *fp)
3283 {
3284         if( !edl ) return;
3285         edl->dump(fp);
3286 }
3287
3288 void MWindow::dump_undo(FILE *fp)
3289 {
3290         if( !undo ) return;
3291         undo->dump(fp);
3292 }
3293
3294 void MWindow::dump_exe(FILE *fp)
3295 {
3296         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
3297         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
3298
3299         int ret = -1, n = 100;
3300         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
3301                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
3302                 ret = 0;
3303         }
3304         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
3305
3306         struct stat st;
3307         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
3308         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
3309         struct tm *tm = localtime(&st.st_mtime);
3310         char mtime[256];
3311         strftime(mtime, sizeof(mtime), "%F %T", tm);
3312         fprintf(fp,"mtime: %s\n", mtime);
3313
3314         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
3315         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
3316         uint8_t *bfr = 0;
3317         int64_t bfrsz = 0;
3318         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
3319         int64_t maxsz = 1024*pagsz;
3320         int64_t size = st.st_size, pos = 0;
3321         SHA1 sha1;
3322         while( (bfrsz = size-pos) > 0 ) {
3323                 if( bfrsz > maxsz ) bfrsz = maxsz;
3324                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
3325                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
3326                 if( bfr == MAP_FAILED ) break;
3327                 sha1.addBytes(bfr, bfrsz);
3328                 munmap(bfr, bfrsz);
3329                 pos += bfrsz;
3330         }
3331         close(fd);
3332         ret = pos < size ? EIO : 0;
3333         fprintf(fp, "SHA1: ");
3334         uint8_t digest[20];  sha1.computeHash(digest);
3335         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
3336         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
3337         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
3338         fprintf(fp, "\n");
3339 }
3340
3341 void MWindow::trap_hook(FILE *fp, void *vp)
3342 {
3343         MWindow *mwindow = (MWindow *)vp;
3344 //      fprintf(fp, "\nPLUGINS:\n");
3345 //      mwindow->dump_plugins(fp);
3346         fprintf(fp, "\nEDL:\n");
3347         mwindow->dump_edl(fp);
3348         fprintf(fp, "\nUNDO:\n");
3349         mwindow->dump_undo(fp);
3350         fprintf(fp, "\nEXE:\n");
3351         mwindow->dump_exe(fp);
3352 }
3353
3354
3355
3356
3357
3358
3359 int MWindow::save_defaults()
3360 {
3361         gui->save_defaults(defaults);
3362         edl->save_defaults(defaults);
3363         session->save_defaults(defaults);
3364         preferences->save_defaults(defaults);
3365
3366         for(int i = 0; i < plugin_guis->total; i++)
3367         {
3368 // Pointer comparison
3369                 plugin_guis->get(i)->save_defaults();
3370         }
3371         awindow->save_defaults(defaults);
3372
3373         defaults->save();
3374         return 0;
3375 }
3376
3377 int MWindow::run_script(FileXML *script)
3378 {
3379         int result = 0, result2 = 0;
3380         while(!result && !result2)
3381         {
3382                 result = script->read_tag();
3383                 if(!result)
3384                 {
3385                         if(script->tag.title_is("new_project"))
3386                         {
3387 // Run new in immediate mode.
3388 //                              gui->mainmenu->new_project->run_script(script);
3389                         }
3390                         else
3391                         if(script->tag.title_is("record"))
3392                         {
3393 // Run record as a thread.  It is a terminal command.
3394                                 ;
3395 // Will read the complete scipt file without letting record read it if not
3396 // terminated.
3397                                 result2 = 1;
3398                         }
3399                         else
3400                         {
3401                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
3402                         }
3403                 }
3404         }
3405         return result2;
3406 }
3407
3408 // ================================= synchronization
3409
3410
3411 int MWindow::interrupt_indexes()
3412 {
3413         mainprogress->cancelled = 1;
3414         mainindexes->interrupt_build();
3415         return 0;
3416 }
3417
3418
3419
3420 void MWindow::next_time_format()
3421 {
3422         switch(edl->session->time_format)
3423         {
3424                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
3425                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
3426                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3427                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
3428                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
3429                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
3430                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
3431         }
3432
3433         time_format_common();
3434 }
3435
3436 void MWindow::prev_time_format()
3437 {
3438         switch(edl->session->time_format)
3439         {
3440                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
3441                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
3442                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
3443                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3444                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
3445                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
3446                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
3447         }
3448
3449         time_format_common();
3450 }
3451
3452 void MWindow::time_format_common()
3453 {
3454         gui->lock_window("MWindow::next_time_format");
3455         gui->redraw_time_dependancies();
3456
3457
3458         char string[BCTEXTLEN], string2[BCTEXTLEN];
3459         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
3460         gui->show_message(string);
3461         gui->flush();
3462         gui->unlock_window();
3463 }
3464
3465
3466 int MWindow::set_filename(const char *filename)
3467 {
3468         if( filename != session->filename )
3469                 strcpy(session->filename, filename);
3470         if( filename != edl->path )
3471                 strcpy(edl->path, filename);
3472
3473         if(gui)
3474         {
3475                 if(filename[0] == 0)
3476                 {
3477                         gui->set_title(PROGRAM_NAME);
3478                 }
3479                 else
3480                 {
3481                         FileSystem dir;
3482                         char string[BCTEXTLEN], string2[BCTEXTLEN];
3483                         dir.extract_name(string, filename);
3484                         sprintf(string2, PROGRAM_NAME ": %s", string);
3485                         gui->set_title(string2);
3486                 }
3487         }
3488         return 0;
3489 }
3490
3491
3492
3493
3494
3495
3496
3497
3498 int MWindow::set_loop_boundaries()
3499 {
3500         double start = edl->local_session->get_selectionstart();
3501         double end = edl->local_session->get_selectionend();
3502
3503         if(start !=
3504                 end)
3505         {
3506                 ;
3507         }
3508         else
3509         if(edl->tracks->total_length())
3510         {
3511                 start = 0;
3512                 end = edl->tracks->total_length();
3513         }
3514         else
3515         {
3516                 start = end = 0;
3517         }
3518
3519         if(edl->local_session->loop_playback && start != end)
3520         {
3521                 edl->local_session->loop_start = start;
3522                 edl->local_session->loop_end = end;
3523         }
3524         return 0;
3525 }
3526
3527
3528
3529
3530
3531
3532
3533 int MWindow::reset_meters()
3534 {
3535         cwindow->gui->lock_window("MWindow::reset_meters 1");
3536         cwindow->gui->meters->reset_meters();
3537         cwindow->gui->unlock_window();
3538
3539         for(int j = 0; j < vwindows.size(); j++) {
3540                 VWindow *vwindow = vwindows[j];
3541                 if( !vwindow->is_running() ) continue;
3542                 vwindow->gui->lock_window("MWindow::reset_meters 2");
3543                 vwindow->gui->meters->reset_meters();
3544                 vwindow->gui->unlock_window();
3545         }
3546
3547         lwindow->gui->lock_window("MWindow::reset_meters 3");
3548         lwindow->gui->panel->reset_meters();
3549         lwindow->gui->unlock_window();
3550
3551         gui->lock_window("MWindow::reset_meters 4");
3552         gui->reset_meters();
3553         gui->unlock_window();
3554         return 0;
3555 }
3556
3557
3558 void MWindow::resync_guis()
3559 {
3560 // Update GUIs
3561         restart_brender();
3562         gui->lock_window("MWindow::resync_guis");
3563         gui->update(1, 1, 1, 1, 1, 1, 0);
3564         gui->unlock_window();
3565
3566         cwindow->gui->lock_window("MWindow::resync_guis");
3567         cwindow->gui->resize_event(cwindow->gui->get_w(),
3568                 cwindow->gui->get_h());
3569         int channels = edl->session->audio_channels;
3570         cwindow->gui->meters->set_meters(channels, 1);
3571         cwindow->gui->flush();
3572         cwindow->gui->unlock_window();
3573
3574         for(int i = 0; i < vwindows.size(); i++) {
3575                 VWindow *vwindow = vwindows[i];
3576                 if( !vwindow->is_running() ) continue;
3577                 vwindow->gui->lock_window("MWindow::resync_guis");
3578                 vwindow->gui->resize_event(vwindow->gui->get_w(),
3579                         vwindow->gui->get_h());
3580                 vwindow->gui->meters->set_meters(channels, 1);
3581                 vwindow->gui->flush();
3582                 vwindow->gui->unlock_window();
3583         }
3584
3585         lwindow->gui->lock_window("MWindow::resync_guis");
3586         lwindow->gui->panel->set_meters(channels, 1);
3587         lwindow->gui->flush();
3588         lwindow->gui->unlock_window();
3589
3590 // Warn user
3591         if(((edl->session->output_w % 4) ||
3592                 (edl->session->output_h % 4)) &&
3593                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
3594         {
3595                 MainError::show_error(
3596                         _("This project's dimensions are not multiples of 4 so\n"
3597                         "it can't be rendered by OpenGL."));
3598         }
3599
3600
3601 // Flash frame
3602         sync_parameters(CHANGE_ALL);
3603 }
3604
3605 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
3606 {
3607         File *file = new File;
3608         EDLSession *session = edl->session;
3609         double old_framerate = session->frame_rate;
3610         double old_samplerate = session->sample_rate;
3611         int old_auto_keyframes = session->auto_keyframes;
3612         session->auto_keyframes = 0;
3613         int result = file->open_file(preferences, asset, 1, 0);
3614         if( !result && delete_tracks > 0 )
3615                 undo->update_undo_before();
3616         if( !result && asset->video_data && asset->get_video_layers() > 0 ) {
3617                 // try to get asset up to date, may fail
3618                 file->select_video_stream(asset, vstream);
3619                 // either way use what was/is there.
3620                 double framerate = asset->get_frame_rate();
3621                 int width = asset->get_w();
3622                 int height = asset->get_h();
3623                 // must be multiple of 4 for opengl
3624                 width = (width+3) & ~3;  height = (height+3) & ~3;
3625                 int driver = session->playback_config->vconfig->driver;
3626                 int color_model = file->get_best_colormodel(asset, driver);
3627 //              color_model = BC_CModels::is_yuv(color_model) ?
3628 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
3629 //                      BC_CModels::is_float(color_model) ?
3630 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
3631 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
3632 // have alpha for now
3633                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
3634                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
3635                 session->color_model = color_model;
3636                 session->output_w = width;
3637                 session->output_h = height;
3638                 session->frame_rate = framerate;
3639                 // not, asset->actual_width/actual_height
3640                 asset->width = session->output_w;
3641                 asset->height = session->output_h;
3642                 asset->frame_rate = session->frame_rate;
3643                 create_aspect_ratio(session->aspect_w, session->aspect_h,
3644                         session->output_w, session->output_h);
3645                 Track *track = edl->tracks->first;
3646                 for( Track *next_track=0; track; track=next_track ) {
3647                         next_track = track->next;
3648                         if( track->data_type != TRACK_VIDEO ) continue;
3649                         if( delete_tracks ) {
3650                                 Edit *edit = track->edits->first;
3651                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
3652                                         next_edit = edit->next;
3653                                         if( edit->channel != vstream ||
3654                                             !edit->asset || !edit->asset->is_asset ||
3655                                             !asset->equivalent(*edit->asset,1,1,edl) )
3656                                                 delete edit;
3657                                 }
3658                         }
3659                         if( track->edits->first ) {
3660                                 track->track_w = edl->session->output_w;
3661                                 track->track_h = edl->session->output_h;
3662                         }
3663                         else if( delete_tracks )
3664                                 edl->tracks->delete_track(track);
3665                 }
3666                 edl->retrack();
3667                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
3668         }
3669         if( !result && asset->audio_data && asset->channels > 0 ) {
3670                 session->sample_rate = asset->get_sample_rate();
3671                 int64_t channel_mask = 0;
3672                 int astrm = !asset->video_data ? -1 :
3673                         file->get_audio_for_video(vstream, astream, channel_mask);
3674                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
3675                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
3676                 int channels = 0;
3677                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
3678                 if( channels < 1 ) channels = 1;
3679                 if( channels > 6 ) channels = 6;
3680                 session->audio_tracks = session->audio_channels = channels;
3681                 switch( channels ) {
3682                 case 6:
3683                         session->achannel_positions[0] = 90;
3684                         session->achannel_positions[1] = 150;
3685                         session->achannel_positions[2] = 30;
3686                         session->achannel_positions[3] = 210;
3687                         session->achannel_positions[4] = 330;
3688                         session->achannel_positions[5] = 270;
3689                         break;
3690                 case 2:
3691                         session->achannel_positions[0] = 180;
3692                         session->achannel_positions[1] = 0;
3693                         break;
3694                 case 1:
3695                         session->achannel_positions[1] = 90;
3696                         break;
3697                 default: {
3698                         if( !channels ) break;
3699                         double t = 0, dt = 360./channels;
3700                         for( int i=channels; --i>=0; t+=dt )
3701                                 session->achannel_positions[i] = int(t+0.5);
3702                         break; }
3703                 }
3704                 remap_audio(MWindow::AUDIO_1_TO_1);
3705
3706                 if( delete_tracks ) {
3707                         Track *track = edl->tracks->first;
3708                         for( Track *next_track=0; track; track=next_track ) {
3709                                 next_track = track->next;
3710                                 if( track->data_type != TRACK_AUDIO ) continue;
3711                                 Edit *edit = track->edits->first;
3712                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
3713                                         next_edit = edit->next;
3714                                         if( !((1<<edit->channel) & channel_mask) ||
3715                                             !edit->asset || !edit->asset->is_asset ||
3716                                             !asset->equivalent(*edit->asset,1,1,edl) )
3717                                                 delete edit;
3718                                 }
3719                                 if( !track->edits->first )
3720                                         edl->tracks->delete_track(track);
3721                         }
3722                 }
3723                 edl->rechannel();
3724                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
3725         }
3726         delete file;
3727         session->auto_keyframes = old_auto_keyframes;
3728         if( !result && delete_tracks > 0 ) {
3729                 save_backup();
3730                 undo->update_undo_after(_("select asset"), LOAD_ALL);
3731         }
3732         resync_guis();
3733         return result;
3734 }
3735
3736 int MWindow::select_asset(int vtrack, int delete_tracks)
3737 {
3738         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
3739         if( !track )
3740                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
3741         if( !track ) return 1;
3742         Edit *edit = track->edits->first;
3743         if( !edit ) return 1;
3744         Asset *asset = edit->asset;
3745         if( !asset || !asset->is_asset ) return 1;
3746         return select_asset(asset, edit->channel, 0, delete_tracks);
3747 }
3748
3749 void MWindow::dump_plugindb(FILE *fp)
3750 {
3751         if( !plugindb ) return;
3752         for(int i = 0; i < plugindb->total; i++)
3753                 plugindb->get(i)->dump(fp);
3754 }
3755
3756 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
3757 {
3758         Auto *current = 0;
3759         double unit_position = edl->local_session->get_selectionstart(1);
3760         unit_position = patch->track->to_units(unit_position, 0);
3761
3762         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
3763         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
3764 }
3765
3766 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
3767 {
3768         Auto *current = 0;
3769         double unit_position = edl->local_session->get_selectionstart(1);
3770         unit_position = patch->track->to_units(unit_position, 0);
3771
3772         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
3773         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
3774 }
3775
3776 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
3777 {
3778         Auto *current = 0;
3779         double unit_position = edl->local_session->get_selectionstart(1);
3780         unit_position = patch->track->to_units(unit_position, 0);
3781
3782         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
3783         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
3784 }
3785
3786