picon dirs, new cinfinity picons, plugin info, rework text drawing, show msg, compres...
[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         if( !theme_plugin && strcasecmp(preferences->theme, DEFAULT_THEME) ) {
1026                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
1027                         DEFAULT_THEME);
1028                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1029                         if( plugindb->get(i)->theme &&
1030                             !strcasecmp(DEFAULT_THEME, plugindb->get(i)->title) )
1031                                 theme_plugin = plugindb->get(i);
1032                 }
1033         }
1034
1035         if(!theme_plugin) {
1036                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
1037                 exit(1);
1038         }
1039
1040         PluginServer *plugin = new PluginServer(*theme_plugin);
1041         if( plugin->open_plugin(0, preferences, 0, 0) ) {
1042                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
1043                         theme_plugin->title);
1044                 exit(1);
1045         }
1046
1047         theme = plugin->new_theme();
1048         theme->mwindow = this;
1049         strcpy(theme->path, plugin->path);
1050         delete plugin;
1051
1052 // Load default images & settings
1053         theme->Theme::initialize();
1054 // Load user images & settings
1055         theme->initialize();
1056 // Create menus with user colors
1057         theme->build_menus();
1058         init_menus();
1059
1060         theme->check_used();
1061
1062 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1063 }
1064
1065 void MWindow::init_3d()
1066 {
1067         playback_3d = new Playback3D(this);
1068         playback_3d->create_objects();
1069 }
1070
1071 void MWindow::init_edl()
1072 {
1073         edl = new EDL;
1074         edl->create_objects();
1075         fill_preset_defaults(default_standard, edl->session);
1076         edl->load_defaults(defaults);
1077         edl->session->brender_start = edl->session->brender_end = 0;
1078         edl->create_default_tracks();
1079         edl->tracks->update_y_pixels(theme);
1080 }
1081
1082 void MWindow::init_compositor()
1083 {
1084         cwindow = new CWindow(this);
1085         cwindow->create_objects();
1086 }
1087
1088 void MWindow::init_levelwindow()
1089 {
1090         lwindow = new LevelWindow(this);
1091         lwindow->create_objects();
1092 }
1093
1094 VWindow *MWindow::get_viewer(int start_it, int idx)
1095 {
1096         vwindows_lock->lock("MWindow::get_viewer");
1097         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
1098         if( !vwindow ) idx = vwindows.size();
1099         while( !vwindow && --idx >= 0 ) {
1100                 VWindow *vwin = vwindows[idx];
1101                 if( !vwin->is_running() || !vwin->get_edl() )
1102                         vwindow = vwin;
1103         }
1104         if( !vwindow ) {
1105                 vwindow = new VWindow(this);
1106                 vwindow->load_defaults();
1107                 vwindow->create_objects();
1108                 vwindows.append(vwindow);
1109         }
1110         vwindows_lock->unlock();
1111         if( start_it ) vwindow->start();
1112         return vwindow;
1113 }
1114
1115 void MWindow::init_cache()
1116 {
1117         audio_cache = new CICache(preferences);
1118         video_cache = new CICache(preferences);
1119         frame_cache = new FrameCache;
1120         wave_cache = new WaveCache;
1121 }
1122
1123 void MWindow::init_channeldb()
1124 {
1125         channeldb_buz->load("channeldb_buz");
1126         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1127 }
1128
1129 void MWindow::init_menus()
1130 {
1131         char string[BCTEXTLEN];
1132
1133         // Color Models
1134         BC_CModels::to_text(string, BC_RGB888);
1135         colormodels.append(new ColormodelItem(string, BC_RGB888));
1136         BC_CModels::to_text(string, BC_RGBA8888);
1137         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1138 //      BC_CModels::to_text(string, BC_RGB161616);
1139 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1140 //      BC_CModels::to_text(string, BC_RGBA16161616);
1141 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1142         BC_CModels::to_text(string, BC_RGB_FLOAT);
1143         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1144         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1145         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1146         BC_CModels::to_text(string, BC_YUV888);
1147         colormodels.append(new ColormodelItem(string, BC_YUV888));
1148         BC_CModels::to_text(string, BC_YUVA8888);
1149         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1150 //      BC_CModels::to_text(string, BC_YUV161616);
1151 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1152 //      BC_CModels::to_text(string, BC_YUVA16161616);
1153 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1154
1155 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1156                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1157
1158 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1159                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1160
1161 #define ILACEFIXMETHODLISTADD(x) ilacefixmethod_to_text(string, x); \
1162                            interlace_asset_fixmethods.append(new InterlacefixmethodItem(string, x));
1163
1164         // Interlacing Modes
1165         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1166
1167         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1168         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1169
1170         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1171         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1172
1173         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1174         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1175
1176         // Interlacing Fixing Methods
1177         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_NONE);
1178         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_UPONE);
1179         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_DOWNONE);
1180 }
1181
1182 void MWindow::init_indexes()
1183 {
1184         mainindexes = new MainIndexes(this);
1185         mainindexes->start_loop();
1186 }
1187
1188 void MWindow::init_gui()
1189 {
1190         gui = new MWindowGUI(this);
1191         gui->lock_window("MWindow::init_gui");
1192         gui->create_objects();
1193         gui->unlock_window();
1194         gui->load_defaults(defaults);
1195 }
1196
1197 void MWindow::init_signals()
1198 {
1199         sighandler = new SigHandler;
1200         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1201 ENABLE_BUFFER
1202 }
1203
1204 void MWindow::init_render()
1205 {
1206         render = new Render(this);
1207         create_bd = new CreateBD_Thread(this);
1208         create_dvd = new CreateDVD_Thread(this);
1209         batch_render = new BatchRenderThread(this);
1210 }
1211
1212 void MWindow::init_exportedl()
1213 {
1214         exportedl = new ExportEDL(this);
1215 }
1216
1217 void MWindow::init_brender()
1218 {
1219         if(preferences->use_brender && !brender)
1220         {
1221                 brender_lock->lock("MWindow::init_brender 1");
1222                 brender = new BRender(this);
1223                 brender->initialize();
1224                 session->brender_end = 0;
1225                 brender_lock->unlock();
1226         }
1227         else
1228         if(!preferences->use_brender && brender)
1229         {
1230                 brender_lock->lock("MWindow::init_brender 2");
1231                 delete brender;
1232                 brender = 0;
1233                 session->brender_end = 0;
1234                 brender_lock->unlock();
1235         }
1236         brender_active = 0;
1237         stop_brender();
1238 }
1239
1240 void MWindow::restart_brender()
1241 {
1242 //printf("MWindow::restart_brender 1\n");
1243         if( !brender_active || !preferences->use_brender ) return;
1244         if( !brender ) return;
1245         int locked  = gui->get_window_lock();
1246         if( locked ) gui->unlock_window();
1247         brender->restart(edl);
1248         if( locked ) gui->lock_window("MWindow::restart_brender");
1249 }
1250
1251 void MWindow::stop_brender()
1252 {
1253         if( !brender ) return;
1254         int locked  = gui->get_window_lock();
1255         if( locked ) gui->unlock_window();
1256         brender->stop();
1257         if( locked ) gui->lock_window("MWindow::stop_brender");
1258 }
1259
1260 int MWindow::brender_available(int position)
1261 {
1262         int result = 0;
1263         brender_lock->lock("MWindow::brender_available 1");
1264         if(brender && brender_active)
1265         {
1266                 if(brender->map_valid)
1267                 {
1268                         brender->map_lock->lock("MWindow::brender_available 2");
1269                         if(position < brender->map_size &&
1270                                 position >= 0)
1271                         {
1272 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1273                                 if(brender->map[position] == BRender::RENDERED)
1274                                         result = 1;
1275                         }
1276                         brender->map_lock->unlock();
1277                 }
1278         }
1279         brender_lock->unlock();
1280         return result;
1281 }
1282
1283 void MWindow::set_brender_active(int v, int update)
1284 {
1285         if( !preferences->use_brender ) v = 0;
1286         brender_active = v;
1287         gui->mainmenu->brender_active->set_checked(v);
1288         if( v != 0 ) {
1289                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1290                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1291
1292                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1293                         edl->session->brender_end = edl->tracks->total_video_length();
1294                 }
1295                 restart_brender();
1296         }
1297         else {
1298                 edl->session->brender_start = edl->session->brender_end = 0;
1299                 stop_brender();
1300         }
1301         if( update ) {
1302                 gui->update_timebar(0);
1303                 gui->draw_overlays(1);
1304         }
1305 }
1306
1307 int MWindow::has_commercials()
1308 {
1309         return theme->use_commercials;
1310 }
1311
1312 void MWindow::init_commercials()
1313 {
1314         if( !commercials ) {
1315                 commercials = new Commercials(this);
1316                 commercial_active = 0;
1317         }
1318         else
1319                 commercials->add_user();
1320 }
1321
1322 void MWindow::commit_commercial()
1323 {
1324         if( !commercial_active ) return;
1325         commercial_active = 0;
1326         if( !commercials ) return;
1327         commercials->commitDb();
1328 }
1329
1330 void MWindow::undo_commercial()
1331 {
1332         if( !commercial_active ) return;
1333         commercial_active = 0;
1334         if( !commercials ) return;
1335         commercials->undoDb();
1336 }
1337
1338 int MWindow::put_commercial()
1339 {
1340         double start = edl->local_session->get_selectionstart();
1341         double end = edl->local_session->get_selectionend();
1342         if( start >= end ) return 0;
1343
1344         const char *errmsg = 0;
1345         int count = 0;
1346         Tracks *tracks = edl->tracks;
1347         int result = 0;
1348         //check it
1349         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1350                 if( track->data_type != TRACK_VIDEO ) continue;
1351                 if( !track->record ) continue;
1352                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1353                 ++count;
1354                 int64_t units_start = track->to_units(start,0);
1355                 int64_t units_end = track->to_units(end,0);
1356                 Edits *edits = track->edits;
1357                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1358                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1359                 if(!edit1 && !edit2) continue;  // nothing selected
1360                 if(!edit2) {                    // edit2 beyond end of track
1361                         edit2 = edits->last;
1362                         units_end = edits->length();
1363                 }
1364                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1365                 Indexable *indexable = edit1->get_source();
1366                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1367         }
1368         //run it
1369         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1370                 if( track->data_type != TRACK_VIDEO ) continue;
1371                 if( !track->record ) continue;
1372                 int64_t units_start = track->to_units(start,0);
1373                 int64_t units_end = track->to_units(end,0);
1374                 Edits *edits = track->edits;
1375                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1376                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1377                 if(!edit1 && !edit2) continue;  // nothing selected
1378                 if(!edit2) {                    // edit2 beyond end of track
1379                         edit2 = edits->last;
1380                         units_end = edits->length();
1381                 }
1382                 Indexable *indexable = edit1->get_source();
1383                 Asset *asset = (Asset *)indexable;
1384                 File *file = video_cache->check_out(asset, edl);
1385                 if( !file ) { errmsg = _("no file"); break; }
1386                 int64_t edit_length = units_end - units_start;
1387                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1388                 result = commercials->put_clip(file, edit1->channel,
1389                         track->from_units(edit_start), track->from_units(edit_length));
1390                 video_cache->check_in(asset);
1391                 if( result ) { errmsg = _("db failed"); break; }
1392         }
1393         if( errmsg ) {
1394                 char string[BCTEXTLEN];
1395                 sprintf(string, _("put_commercial: %s"), errmsg);
1396                 MainError::show_error(string);
1397                 undo_commercial();
1398                 result = 1;
1399         }
1400         return result;
1401 }
1402
1403 void MWindow::stop_playback(int wait)
1404 {
1405         int locked  = gui->get_window_lock();
1406         if( locked ) gui->unlock_window();
1407
1408         cwindow->playback_engine->stop_playback();
1409
1410         for(int i = 0; i < vwindows.size(); i++) {
1411                 VWindow *vwindow = vwindows[i];
1412                 if( !vwindow->is_running() ) continue;
1413                 vwindow->playback_engine->stop_playback();
1414         }
1415         if( locked ) gui->lock_window("MWindow::stop_playback");
1416 }
1417
1418 int MWindow::load_filenames(ArrayList<char*> *filenames,
1419         int load_mode,
1420         int update_filename)
1421 {
1422         ArrayList<EDL*> new_edls;
1423         ArrayList<Asset*> new_assets;
1424         ArrayList<File*> new_files;
1425         const int debug = 0;
1426 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1427
1428 //      save_defaults();
1429         gui->start_hourglass();
1430
1431 // Need to stop playback since tracking depends on the EDL not getting
1432 // deleted.
1433         stop_playback(1);
1434
1435 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1436         undo->update_undo_before();
1437
1438
1439 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1440
1441 // Define new_edls and new_assets to load
1442         int result = 0, ftype = -1;
1443         for(int i = 0; i < filenames->size(); i++)
1444         {
1445 // Get type of file
1446                 File *new_file = new File;
1447                 Asset *new_asset = new Asset(filenames->get(i));
1448                 EDL *new_edl = new EDL;
1449                 char string[BCTEXTLEN];
1450
1451                 new_edl->create_objects();
1452                 new_edl->copy_session(edl);
1453                 new_file->set_program(edl->session->program_no);
1454
1455                 sprintf(string, _("Loading %s"), new_asset->path);
1456                 gui->show_message(string);
1457 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1458
1459                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1460 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1461
1462                 result = 1;
1463                 switch(ftype)
1464                 {
1465 // Convert media file to EDL
1466                         case FILE_OK:
1467 // Warn about odd image dimensions
1468                                 if(new_asset->video_data &&
1469                                         ((new_asset->width % 2) ||
1470                                         (new_asset->height % 2)))
1471                                 {
1472                                         char string[BCTEXTLEN];
1473                                         sprintf(string, _("%s's resolution is %dx%d.\nImages with odd dimensions may not decode properly."),
1474                                                 new_asset->path,
1475                                                 new_asset->width,
1476                                                 new_asset->height);
1477                                         MainError::show_error(string);
1478                                 }
1479
1480                                 if(new_asset->program >= 0 &&
1481                                         edl->session->program_no != new_asset->program)
1482                                 {
1483                                         char string[BCTEXTLEN];
1484                                         sprintf(string, _("%s's index was built for program number %d\n"
1485                                                 "Playback preference is %d.\n  Using program %d."),
1486                                                 new_asset->path, new_asset->program,
1487                                                 edl->session->program_no, new_asset->program);
1488                                         MainError::show_error(string);
1489                                 }
1490
1491
1492                                 if(load_mode != LOADMODE_RESOURCESONLY)
1493                                 {
1494 SET_TRACE
1495                                         RecordLabels *labels = edl->session->label_cells ?
1496                                                 new RecordLabels(new_file) : 0;
1497 SET_TRACE
1498                                         asset_to_edl(new_edl, new_asset, labels);
1499 SET_TRACE
1500                                         new_edls.append(new_edl);
1501 SET_TRACE
1502                                         new_asset->Garbage::remove_user();
1503                                         delete labels;
1504                                         new_asset = 0;
1505                                 }
1506                                 else
1507                                 {
1508                                         new_assets.append(new_asset);
1509                                         new_asset = 0;
1510                                 }
1511
1512 // Set filename to nothing for assets since save EDL would overwrite them.
1513                                 if(load_mode == LOADMODE_REPLACE ||
1514                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
1515                                 {
1516                                         set_filename("");
1517 // Reset timeline position
1518                                         for(int i = 0; i < TOTAL_PANES; i++)
1519                                         {
1520                                                 new_edl->local_session->view_start[i] = 0;
1521                                                 new_edl->local_session->track_start[i] = 0;
1522                                         }
1523                                 }
1524
1525                                 result = 0;
1526                                 break;
1527
1528 // File not found
1529                         case FILE_NOT_FOUND:
1530                                 sprintf(string, _("Failed to open %s"), new_asset->path);
1531                                 gui->show_message(string, theme->message_error);
1532                                 gui->update_default_message();
1533                                 break;
1534
1535 // Unknown format
1536                         case FILE_UNRECOGNIZED_CODEC:
1537                         {
1538 // Test index file
1539                                 {       IndexFile indexfile(this, new_asset);
1540                                         if( !(result = indexfile.open_index()) )
1541                                                 indexfile.close_index();
1542                                 }
1543
1544 // Test existing EDLs
1545                                 for(int j = 0; result && j <= new_edls.total; j++) {
1546                                         Asset *old_asset = j < new_edls.total ?
1547                                                 new_edls[j]->assets->get_asset(new_asset->path) :
1548                                                 edl->assets->get_asset(new_asset->path);
1549                                         if( old_asset ) {
1550                                                 new_asset->copy_from(old_asset,1);
1551                                                 result = 0;
1552                                         }
1553                                 }
1554
1555 // Prompt user
1556                                 if(result)
1557                                 {
1558                                         char string[BCTEXTLEN];
1559                                         FileSystem fs;
1560                                         fs.extract_name(string, new_asset->path);
1561
1562                                         strcat(string, _("'s format couldn't be determined."));
1563                                         new_asset->audio_data = 1;
1564                                         new_asset->format = FILE_PCM;
1565                                         new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
1566                                         new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
1567                                         new_asset->bits = defaults->get("AUDIO_BITS", 16);
1568                                         new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
1569                                         new_asset->signed_ = defaults->get("SIGNED_", 1);
1570                                         new_asset->header = defaults->get("HEADER", 0);
1571
1572                                         FileFormat fwindow(this);
1573                                         fwindow.create_objects(new_asset, string);
1574                                         result = fwindow.run_window();
1575
1576
1577                                         defaults->update("AUDIO_CHANNELS", new_asset->channels);
1578                                         defaults->update("SAMPLE_RATE", new_asset->sample_rate);
1579                                         defaults->update("AUDIO_BITS", new_asset->bits);
1580                                         defaults->update("BYTE_ORDER", new_asset->byte_order);
1581                                         defaults->update("SIGNED_", new_asset->signed_);
1582                                         defaults->update("HEADER", new_asset->header);
1583                                         save_defaults();
1584                                 }
1585
1586 // Append to list
1587                                 if(!result)
1588                                 {
1589 // Recalculate length
1590                                         delete new_file;
1591                                         new_file = new File;
1592                                         result = new_file->open_file(preferences, new_asset, 1, 0);
1593
1594                                         if(load_mode != LOADMODE_RESOURCESONLY)
1595                                         {
1596                                                 RecordLabels *labels = edl->session->label_cells ?
1597                                                         new RecordLabels(new_file) : 0;
1598                                                 asset_to_edl(new_edl, new_asset, labels);
1599                                                 new_edls.append(new_edl);
1600                                                 new_asset->Garbage::remove_user();
1601                                                 delete labels;
1602                                                 new_asset = 0;
1603                                         }
1604                                         else
1605                                         {
1606                                                 new_assets.append(new_asset);
1607                                                 new_asset = 0;
1608                                         }
1609                                 }
1610                                 else
1611                                 {
1612                                         result = 1;
1613                                 }
1614                                 break;
1615                         }
1616
1617                         case FILE_IS_XML:
1618                         {
1619                                 FileXML xml_file;
1620 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1621                                 xml_file.read_from_file(filenames->get(i));
1622 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1623                                 const char *cin_version = 0;
1624                                 while( !xml_file.read_tag() ) {
1625                                         if( xml_file.tag.title_is("EDL") ) {
1626                                                 cin_version = xml_file.tag.get_property("VERSION");
1627                                                 break;
1628                                         }
1629                                 }
1630                                 xml_file.rewind();
1631                                 if( !cin_version ) {
1632                                         eprintf(_("XML file %s\n not from cinelerra."),filenames->get(i));
1633                                         char string[BCTEXTLEN];
1634                                         sprintf(string,_("Unknown %s"), filenames->get(i));
1635                                         gui->show_message(string);
1636                                         result = 1;
1637                                         break;
1638                                 }
1639                                 if( strcmp(cin_version, CINELERRA_VERSION) ) {
1640                                         char string[BCTEXTLEN];
1641                                         snprintf(string, sizeof(string),
1642                                                  _("Warning: XML from cinelerra version %s\n"
1643                                                 "Session data may be incompatible."), cin_version);
1644                                         show_warning(&preferences->warn_version, string);
1645                                 }
1646                                 if(load_mode == LOADMODE_NESTED)
1647                                 {
1648 // Load temporary EDL for nesting.
1649                                         EDL *nested_edl = new EDL;
1650                                         nested_edl->create_objects();
1651                                         nested_edl->set_path(filenames->get(i));
1652                                         nested_edl->load_xml(&xml_file, LOAD_ALL);
1653 //printf("MWindow::load_filenames %p %s\n", nested_edl, nested_edl->project_path);
1654                                         edl_to_nested(new_edl, nested_edl);
1655                                         nested_edl->Garbage::remove_user();
1656                                 }
1657                                 else
1658                                 {
1659 // Load EDL for pasting
1660                                         new_edl->load_xml(&xml_file, LOAD_ALL);
1661 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1662                                         test_plugins(new_edl, filenames->get(i));
1663 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1664
1665                                         if(load_mode == LOADMODE_REPLACE ||
1666                                                 load_mode == LOADMODE_REPLACE_CONCATENATE)
1667                                         {
1668                                                 strcpy(session->filename, filenames->get(i));
1669                                                 strcpy(new_edl->local_session->clip_title,
1670                                                         filenames->get(i));
1671                                                 if(update_filename)
1672                                                         set_filename(new_edl->local_session->clip_title);
1673                                         }
1674                                         else
1675                                         if( load_mode == LOADMODE_RESOURCESONLY ) {
1676                                                 strcpy(new_edl->local_session->clip_title,
1677                                                         filenames->get(i));
1678                                                 struct stat st;
1679                                                 time_t t = !stat(filenames->get(i),&st) ?
1680                                                         st.st_mtime : time(&t);
1681                                                 ctime_r(&t, new_edl->local_session->clip_notes);
1682                                         }
1683                                 }
1684
1685                                 new_edls.append(new_edl);
1686                                 result = 0;
1687                                 break;
1688                         }
1689                 }
1690
1691 // edls are in new_edls
1692                 if( result && new_edl ) new_edl->Garbage::remove_user();
1693 // assets are copied
1694                 if( new_asset ) new_asset->Garbage::remove_user();
1695
1696 // Store for testing index
1697                 new_files.append(new_file);
1698         }
1699
1700 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1701
1702
1703         if(!result) {
1704                 gui->reset_default_message();
1705                 gui->default_message();
1706         }
1707
1708
1709 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1710
1711 // Paste them.
1712 // Don't back up here.
1713         if(new_edls.size())
1714         {
1715 // For pasting, clear the active region
1716                 if(load_mode == LOADMODE_PASTE ||
1717                         load_mode == LOADMODE_NESTED)
1718                 {
1719                         double start = edl->local_session->get_selectionstart();
1720                         double end = edl->local_session->get_selectionend();
1721                         if(!EQUIV(start, end))
1722                                 edl->clear(start,
1723                                         end,
1724                                         edl->session->labels_follow_edits,
1725                                         edl->session->plugins_follow_edits,
1726                                         edl->session->autos_follow_edits);
1727                 }
1728
1729                 paste_edls(&new_edls, load_mode, 0, -1,
1730                         edl->session->labels_follow_edits,
1731                         edl->session->plugins_follow_edits,
1732                         edl->session->autos_follow_edits,
1733                         0); // overwrite
1734         }
1735
1736
1737
1738
1739 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1740
1741 // Add new assets to EDL and schedule assets for index building.
1742         int got_indexes = 0;
1743         for(int i = 0; i < new_edls.size(); i++)
1744         {
1745                 EDL *new_edl = new_edls[i];
1746                 for(int j = 0; j < new_edl->nested_edls->size(); j++)
1747                 {
1748                         mainindexes->add_next_asset(0,
1749                                 new_edl->nested_edls->get(j));
1750                         got_indexes = 1;
1751                         edl->nested_edls->update_index(new_edl->nested_edls->get(j));
1752                 }
1753
1754         }
1755
1756 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1757         for(int i = 0; i < new_assets.size(); i++)
1758         {
1759                 Asset *new_asset = new_assets[i];
1760
1761                 File *new_file = 0;
1762                 int got_it = 0;
1763                 for(int j = 0; j < new_files.size(); j++)
1764                 {
1765                         new_file = new_files[j];
1766                         if(!strcmp(new_file->asset->path,
1767                                 new_asset->path))
1768                         {
1769                                 got_it = 1;
1770                                 break;
1771                         }
1772                 }
1773
1774                 mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
1775                 got_indexes = 1;
1776                 edl->assets->update(new_asset);
1777         }
1778 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1779
1780 // Start examining next batch of index files
1781         if(got_indexes) mainindexes->start_build();
1782 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1783
1784 // Open plugin GUIs
1785         Track *track = edl->tracks->first;
1786         while(track)
1787         {
1788                 for(int j = 0; j < track->plugin_set.size(); j++)
1789                 {
1790                         PluginSet *plugins = track->plugin_set[j];
1791                         Plugin *plugin = plugins->get_first_plugin();
1792
1793                         while(plugin)
1794                         {
1795                                 if(load_mode == LOADMODE_REPLACE ||
1796                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
1797                                 {
1798                                         if(plugin->plugin_type == PLUGIN_STANDALONE &&
1799                                                 plugin->show)
1800                                         {
1801                                                 show_plugin(plugin);
1802                                         }
1803                                 }
1804                                 else
1805                                 {
1806                                         plugin->show = 0;
1807                                 }
1808
1809                                 plugin = (Plugin*)plugin->next;
1810                         }
1811                 }
1812
1813                 track = track->next;
1814         }
1815
1816         // if just opening one new resource in replace mode
1817         if( ftype != FILE_IS_XML &&
1818             ( load_mode == LOADMODE_REPLACE ||
1819               load_mode == LOADMODE_REPLACE_CONCATENATE ) ) {
1820                 select_asset(0, 0);
1821                 edl->local_session->preview_start = 0;
1822                 edl->local_session->preview_end = edl->tracks->total_playable_length();
1823                 edl->local_session->loop_playback = 0;
1824                 edl->local_session->set_selectionstart(0);
1825                 edl->local_session->set_selectionend(0);
1826                 set_brender_active(0, 0);
1827                 fit_selection();
1828                 goto_start();
1829         }
1830
1831 // need to update undo before project, since mwindow is unlocked & a new load
1832 // can begin here.  Should really prevent loading until we're done.
1833 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1834         undo->update_undo_after(_("load"), LOAD_ALL);
1835
1836         for(int i = 0; i < new_edls.size(); i++)
1837         {
1838                 new_edls[i]->remove_user();
1839         }
1840 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1841
1842         new_edls.remove_all();
1843
1844         for(int i = 0; i < new_assets.size(); i++)
1845         {
1846                 new_assets[i]->Garbage::remove_user();
1847         }
1848
1849         new_assets.remove_all();
1850         new_files.remove_all_objects();
1851
1852
1853 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1854         if(load_mode == LOADMODE_REPLACE ||
1855                 load_mode == LOADMODE_REPLACE_CONCATENATE)
1856         {
1857                 session->changes_made = 0;
1858         }
1859         else
1860         {
1861                 session->changes_made = 1;
1862         }
1863
1864         gui->stop_hourglass();
1865
1866
1867 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1868         update_project(load_mode);
1869
1870 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1871
1872         return 0;
1873 }
1874
1875
1876
1877
1878 void MWindow::test_plugins(EDL *new_edl, char *path)
1879 {
1880         char string[BCTEXTLEN];
1881
1882 // Do a check weather plugins exist
1883         for(Track *track = new_edl->tracks->first; track; track = track->next)
1884         {
1885                 for(int k = 0; k < track->plugin_set.total; k++)
1886                 {
1887                         PluginSet *plugin_set = track->plugin_set[k];
1888                         for(Plugin *plugin = (Plugin*)plugin_set->first;
1889                                 plugin;
1890                                 plugin = (Plugin*)plugin->next)
1891                         {
1892                                 if(plugin->plugin_type == PLUGIN_STANDALONE)
1893                                 {
1894 // ok we need to find it in plugindb
1895                                         int plugin_found = 0;
1896
1897                                         for(int j = 0; j < plugindb->size(); j++)
1898                                         {
1899                                                 PluginServer *server = plugindb->get(j);
1900                                                 if(server->title &&
1901                                                         !strcasecmp(server->title, plugin->title) &&
1902                                                         ((track->data_type == TRACK_AUDIO && server->audio) ||
1903                                                         (track->data_type == TRACK_VIDEO && server->video)) &&
1904                                                         (!server->transition))
1905                                                         plugin_found = 1;
1906                                         }
1907
1908                                         if (!plugin_found)
1909                                         {
1910                                                 sprintf(string,
1911         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
1912           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
1913                                                         "effect", plugin->title,
1914                                                         path);
1915                                                 MainError::show_error(string);
1916                                         }
1917                                 }
1918                         }
1919                 }
1920
1921                 for(Edit *edit = (Edit*)track->edits->first;
1922                         edit;
1923                         edit = (Edit*)edit->next)
1924                 {
1925                         if (edit->transition)
1926                         {
1927 // ok we need to find transition in plugindb
1928
1929                                 int transition_found = 0;
1930                                 for(int j = 0; j < plugindb->size(); j++)
1931                                 {
1932                                         PluginServer *server = plugindb->get(j);
1933                                         if(server->title &&
1934                                                 !strcasecmp(server->title, edit->transition->title) &&
1935                                                 ((track->data_type == TRACK_AUDIO && server->audio) ||
1936                                                 (track->data_type == TRACK_VIDEO && server->video)) &&
1937                                                 (server->transition))
1938                                                 transition_found = 1;
1939                                 }
1940
1941                                 if (!transition_found)
1942                                 {
1943                                         sprintf(string,
1944         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
1945           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
1946                                                 "transition", edit->transition->title,
1947                                                 path);
1948                                         MainError::show_error(string);
1949                                 }
1950                         }
1951                 }
1952         }
1953 }
1954
1955
1956 void MWindow::init_shm()
1957 {
1958 // Fix shared memory
1959         FILE *fd = fopen("/proc/sys/kernel/shmmax", "w");
1960         if(fd) {
1961                 fprintf(fd, "0x7fffffff");
1962                 fclose(fd);
1963         }
1964         fd = 0;
1965
1966         fd = fopen("/proc/sys/kernel/shmmax", "r");
1967         if(!fd) {
1968                 MainError::show_error("MWindow::init_shm: couldn't open /proc/sys/kernel/shmmax for reading.\n");
1969                 return;
1970         }
1971
1972         int64_t result = 0;
1973         fscanf(fd, "%jd", &result);
1974         fclose(fd);
1975         fd = 0;
1976         if(result < 0x7fffffff) {
1977                 eprintf(_("MWindow::init_shm: /proc/sys/kernel/shmmax is %p.\n"
1978                         "you probably need to be root, or:\n"
1979                         "as root, run: echo 0x7fffffff > /proc/sys/kernel/shmmax\n"
1980                         "before trying to start cinelerra.\n"
1981                         "It should be at least 0x7fffffff for Cinelerra.\n"), (void *)result);
1982         }
1983 }
1984
1985 void MWindow::create_objects(int want_gui,
1986         int want_new,
1987         char *config_path)
1988 {
1989         FileSystem fs;
1990         const int debug = 0;
1991         if(debug) PRINT_TRACE
1992
1993 // For some reason, init_signals must come after show_splash or the signals won't
1994 // get trapped.
1995         init_signals();
1996         if(debug) PRINT_TRACE
1997         init_3d();
1998
1999         if(debug) PRINT_TRACE
2000         show_splash();
2001
2002         if(debug) PRINT_TRACE
2003         default_standard = default_std();
2004         init_defaults(defaults, config_path);
2005         check_language();
2006         init_preferences();
2007         if(splash_window)
2008                 splash_window->operation->update(_("Initializing Plugins"));
2009         init_plugins(this, preferences);
2010         if(debug) PRINT_TRACE
2011         init_ladspa_plugins(this, preferences);
2012         if(debug) PRINT_TRACE
2013         init_plugin_tips(*plugindb);
2014         if(splash_window)
2015                 splash_window->operation->update(_("Initializing GUI"));
2016         if(debug) PRINT_TRACE
2017         init_theme();
2018
2019         if(debug) PRINT_TRACE
2020         init_error();
2021
2022         if(splash_window)
2023                 splash_window->operation->update(_("Initializing Fonts"));
2024         char string[BCTEXTLEN];
2025         strcpy(string, preferences->plugin_dir);
2026         strcat(string, "/" FONT_SEARCHPATH);
2027         BC_Resources::init_fontconfig(string);
2028         if(debug) PRINT_TRACE
2029
2030 // Initialize before too much else is running
2031 // Preferences & theme are required for building MPEG table of contents
2032
2033 // Default project created here
2034         init_edl();
2035         if(debug) PRINT_TRACE
2036
2037         init_cache();
2038         if(debug) PRINT_TRACE
2039
2040         Timer timer;
2041
2042         init_awindow();
2043         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2044
2045         init_compositor();
2046         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2047
2048 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2049         if(session->show_vwindow)
2050                 get_viewer(1, DEFAULT_VWINDOW);
2051         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2052
2053         init_gui();
2054         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2055
2056         init_levelwindow();
2057         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2058
2059         init_indexes();
2060         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2061
2062         init_channeldb();
2063         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2064
2065         init_gwindow();
2066         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2067
2068         init_render();
2069         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2070
2071         init_brender();
2072         init_exportedl();
2073         init_commercials();
2074         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2075         mainprogress = new MainProgress(this, gui);
2076         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2077         undo = new MainUndo(this);
2078
2079         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2080
2081         plugin_guis = new ArrayList<PluginServer*>;
2082         dead_plugins = new ArrayList<PluginServer*>;
2083         keyframe_threads = new ArrayList<KeyFrameThread*>;
2084
2085         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2086                 __LINE__,
2087                 vwindows.size(),
2088                 session->show_vwindow);
2089
2090 // Show all vwindows
2091 //      if(session->show_vwindow) {
2092 //              for(int j = 0; j < vwindows.size(); j++) {
2093 //                      VWindow *vwindow = vwindows[j];
2094 //                      if( !vwindow->is_running() ) continue;
2095 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2096 //                              __LINE__,
2097 //                              vwindow);
2098 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2099 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2100 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2101 //                      vwindow->gui->show_window();
2102 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2103 //                      vwindow->gui->unlock_window();
2104 //              }
2105 //      }
2106
2107
2108         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2109
2110         if(session->show_cwindow)
2111         {
2112                 cwindow->gui->lock_window("MWindow::create_objects 1");
2113                 cwindow->gui->show_window();
2114                 cwindow->gui->unlock_window();
2115         }
2116
2117         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2118         if(session->show_awindow)
2119         {
2120                 awindow->gui->lock_window("MWindow::create_objects 1");
2121                 awindow->gui->show_window();
2122                 awindow->gui->unlock_window();
2123         }
2124
2125         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2126         if(session->show_lwindow)
2127         {
2128                 lwindow->gui->lock_window("MWindow::create_objects 1");
2129                 lwindow->gui->show_window();
2130                 lwindow->gui->unlock_window();
2131         }
2132
2133         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2134                 __LINE__,
2135                 (int)timer.get_difference(),
2136                 gwindow->gui);
2137         if(session->show_gwindow)
2138         {
2139                 gwindow->gui->lock_window("MWindow::create_objects 1");
2140                 gwindow->gui->show_window();
2141                 gwindow->gui->unlock_window();
2142         }
2143
2144         if(debug) PRINT_TRACE
2145
2146         gui->lock_window("MWindow::create_objects 1");
2147         gui->mainmenu->load_defaults(defaults);
2148         gui->mainmenu->update_toggles(0);
2149         gui->update_patchbay();
2150         gui->draw_canvas(0, 0);
2151         gui->draw_cursor(1);
2152         gui->show_window();
2153         gui->raise_window();
2154         gui->unlock_window();
2155
2156         if(debug) PRINT_TRACE
2157
2158         if(preferences->use_tipwindow)
2159                 init_tipwindow();
2160         if(debug) PRINT_TRACE
2161
2162         gui->add_keyboard_listener(
2163                 (int (BC_WindowBase::*)(BC_WindowBase *))
2164                 &MWindowGUI::keyboard_listener);
2165
2166         hide_splash();
2167         init_shm();
2168         if(debug) PRINT_TRACE
2169
2170         BC_WindowBase::get_resources()->vframe_shm = 1;
2171 }
2172
2173
2174 void MWindow::show_splash()
2175 {
2176 #include "data/heroine_logo9_png.h"
2177         VFrame *frame = new VFramePng(heroine_logo9_png);
2178         BC_DisplayInfo dpyi;
2179         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2180         int rr = (rw < rh ? rw : rh) / 4;
2181         splash_window = new SplashGUI(frame, rr, rr);
2182         splash_window->create_objects();
2183 }
2184
2185 void MWindow::hide_splash()
2186 {
2187         if(splash_window)
2188                 delete splash_window;
2189         splash_window = 0;
2190 }
2191
2192
2193 void MWindow::start()
2194 {
2195 ENABLE_BUFFER
2196 //PRINT_TRACE
2197 //      vwindows[DEFAULT_VWINDOW]->start();
2198         awindow->start();
2199 //PRINT_TRACE
2200         cwindow->start();
2201 //PRINT_TRACE
2202         lwindow->start();
2203 //PRINT_TRACE
2204         gwindow->start();
2205 //PRINT_TRACE
2206 //      Thread::start();
2207 //PRINT_TRACE
2208         playback_3d->start();
2209 //PRINT_TRACE
2210 }
2211
2212 void MWindow::run()
2213 {
2214         run_lock->lock("MWindow::run");
2215         gui->run_window();
2216         stop_playback(1);
2217
2218         brender_lock->lock("MWindow::run 1");
2219         delete brender;         brender = 0;
2220         brender_lock->unlock();
2221
2222         interrupt_indexes();
2223         clean_indexes();
2224         save_defaults();
2225         run_lock->unlock();
2226 }
2227
2228 void MWindow::show_vwindow()
2229 {
2230         int total_running = 0;
2231         session->show_vwindow = 1;
2232
2233 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2234 // Raise all windows which are visible
2235         for(int j = 0; j < vwindows.size(); j++) {
2236                 VWindow *vwindow = vwindows[j];
2237                 if( !vwindow->is_running() ) continue;
2238                 vwindow->gui->lock_window("MWindow::show_vwindow");
2239                 vwindow->gui->show_window(0);
2240                 vwindow->gui->raise_window();
2241                 vwindow->gui->flush();
2242                 vwindow->gui->unlock_window();
2243                 total_running++;
2244         }
2245
2246 // If no windows visible
2247         if(!total_running)
2248         {
2249                 get_viewer(1, DEFAULT_VWINDOW);
2250         }
2251
2252         gui->mainmenu->show_vwindow->set_checked(1);
2253 }
2254
2255 void MWindow::show_awindow()
2256 {
2257         session->show_awindow = 1;
2258         awindow->gui->lock_window("MWindow::show_awindow");
2259         awindow->gui->show_window();
2260         awindow->gui->raise_window();
2261         awindow->gui->flush();
2262         awindow->gui->unlock_window();
2263         gui->mainmenu->show_awindow->set_checked(1);
2264 }
2265
2266 char *MWindow::get_cwindow_display()
2267 {
2268         char *x11_host = screens < 2 || session->window_config == 0 ?
2269                 session->a_x11_host : session->b_x11_host;
2270         return *x11_host ? x11_host : 0;
2271 }
2272
2273 void MWindow::show_cwindow()
2274 {
2275         session->show_cwindow = 1;
2276         cwindow->show_window();
2277         gui->mainmenu->show_cwindow->set_checked(1);
2278 }
2279
2280 void MWindow::show_gwindow()
2281 {
2282         session->show_gwindow = 1;
2283
2284         gwindow->gui->lock_window("MWindow::show_gwindow");
2285         gwindow->gui->show_window();
2286         gwindow->gui->raise_window();
2287         gwindow->gui->flush();
2288         gwindow->gui->unlock_window();
2289
2290         gui->mainmenu->show_gwindow->set_checked(1);
2291 }
2292 void MWindow::hide_gwindow()
2293 {
2294         session->show_gwindow = 0;
2295
2296         gwindow->gui->lock_window("MWindow::show_gwindow");
2297         gwindow->gui->hide_window();
2298         gwindow->gui->unlock_window();
2299 }
2300
2301 void MWindow::show_lwindow()
2302 {
2303         session->show_lwindow = 1;
2304         lwindow->gui->lock_window("MWindow::show_lwindow");
2305         lwindow->gui->show_window();
2306         lwindow->gui->raise_window();
2307         lwindow->gui->flush();
2308         lwindow->gui->unlock_window();
2309         gui->mainmenu->show_lwindow->set_checked(1);
2310 }
2311
2312 int MWindow::tile_windows(int window_config)
2313 {
2314         int need_reload = 0;
2315         int play_config = window_config==0 ? 0 : 1;
2316         edl->session->playback_config->load_defaults(defaults, play_config);
2317         session->default_window_positions(window_config);
2318         if( screens == 1 ) {
2319                 gui->default_positions();
2320                 sync_parameters(CHANGE_ALL);
2321         }
2322         else
2323                 need_reload = 1;
2324         return need_reload;
2325 }
2326
2327 void MWindow::toggle_loop_playback()
2328 {
2329         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2330         set_loop_boundaries();
2331         save_backup();
2332
2333         gui->draw_overlays(1);
2334         sync_parameters(CHANGE_PARAMS);
2335 }
2336
2337 //void MWindow::set_titles(int value)
2338 //{
2339 //      edl->session->show_titles = value;
2340 //      trackmovement(edl->local_session->track_start);
2341 //}
2342
2343 void MWindow::set_screens(int value)
2344 {
2345         screens = value;
2346 }
2347
2348 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2349 {
2350         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2351         edl->session->auto_keyframes = value;
2352         gui->mbuttons->edit_panel->keyframe->update(value);
2353         gui->flush();
2354         if(lock_mwindow) gui->unlock_window();
2355
2356         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2357         cwindow->gui->edit_panel->keyframe->update(value);
2358         cwindow->gui->flush();
2359         if(lock_cwindow) cwindow->gui->unlock_window();
2360 }
2361
2362 void MWindow::set_auto_visibility(Autos *autos, int value)
2363 {
2364         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2365                 edl->session->auto_conf->plugins = value;
2366         else if( autos->autoidx >= 0 )
2367                 edl->session->auto_conf->autos[autos->autoidx] = value;
2368         else
2369                 return;
2370
2371         gui->update(0, 1, 0, 0, 0, 0, 0);
2372         gui->mainmenu->update_toggles(1);
2373         gui->unlock_window();
2374         gwindow->gui->update_toggles(1);
2375         gui->lock_window("MWindow::set_auto_visibility");
2376 }
2377
2378 void MWindow::set_keyframe_type(int mode)
2379 {
2380         gui->lock_window("MWindow::set_keyframe_type");
2381         edl->local_session->floatauto_type = mode;
2382         gui->mainmenu->update_toggles(0);
2383         gui->unlock_window();
2384 }
2385
2386 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
2387 {
2388         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
2389         edl->session->editing_mode = new_editing_mode;
2390         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
2391         gui->mbuttons->edit_panel->update();
2392         gui->set_editing_mode(1);
2393         if(lock_mwindow) gui->unlock_window();
2394
2395
2396         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
2397         cwindow->gui->edit_panel->update();
2398         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
2399         if(lock_cwindow) cwindow->gui->unlock_window();
2400         return 0;
2401 }
2402
2403 void MWindow::toggle_editing_mode()
2404 {
2405         int mode = edl->session->editing_mode;
2406         if( mode == EDITING_ARROW )
2407                 set_editing_mode(EDITING_IBEAM, 0, 1);
2408         else
2409                 set_editing_mode(EDITING_ARROW, 0, 1);
2410 }
2411
2412
2413 void MWindow::set_labels_follow_edits(int value)
2414 {
2415         gui->lock_window("MWindow::set_labels_follow_edits");
2416         edl->session->labels_follow_edits = value;
2417         gui->mbuttons->edit_panel->locklabels->update(value);
2418         gui->mainmenu->labels_follow_edits->set_checked(value);
2419         gui->flush();
2420         gui->unlock_window();
2421 }
2422
2423 void MWindow::sync_parameters(int change_type)
2424 {
2425         if( in_destructor ) return;
2426
2427 // Sync engines which are playing back
2428         if(cwindow->playback_engine->is_playing_back)
2429         {
2430                 if(change_type == CHANGE_PARAMS)
2431                 {
2432 // TODO: block keyframes until synchronization is done
2433                         cwindow->playback_engine->sync_parameters(edl);
2434                 }
2435                 else
2436 // Stop and restart
2437                 {
2438                         int command = cwindow->playback_engine->command->command;
2439                         cwindow->playback_engine->que->send_command(STOP,
2440                                 CHANGE_NONE,
2441                                 0,
2442                                 0);
2443 // Waiting for tracking to finish would make the restart position more
2444 // accurate but it can't lock the window to stop tracking for some reason.
2445 // Not waiting for tracking gives a faster response but restart position is
2446 // only as accurate as the last tracking update.
2447                         cwindow->playback_engine->interrupt_playback(0);
2448                         cwindow->playback_engine->que->send_command(command,
2449                                         change_type,
2450                                         edl,
2451                                         1,
2452                                         0);
2453                 }
2454         }
2455         else
2456         {
2457                 cwindow->playback_engine->que->send_command(CURRENT_FRAME,
2458                                                         change_type,
2459                                                         edl,
2460                                                         1);
2461         }
2462 }
2463
2464 void MWindow::age_caches()
2465 {
2466 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
2467 // __LINE__,
2468 // preferences->cache_size,
2469 // audio_cache->get_memory_usage(1),
2470 // video_cache->get_memory_usage(1),
2471 // frame_cache->get_memory_usage(),
2472 // wave_cache->get_memory_usage(),
2473 // memory_usage);
2474         frame_cache->age_cache(512);
2475         wave_cache->age_cache(8192);
2476
2477         int64_t memory_usage;
2478         int64_t prev_memory_usage = 0;
2479         int result = 0;
2480         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
2481         while( !result && prev_memory_usage !=
2482                 (memory_usage=video_cache->get_memory_usage(1)) &&
2483                 memory_usage > video_size ) {
2484                 video_cache->delete_oldest();
2485                 prev_memory_usage = memory_usage;
2486         }
2487
2488         prev_memory_usage = 0;
2489         result = 0;
2490         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
2491         while( !result && prev_memory_usage !=
2492                 (memory_usage=audio_cache->get_memory_usage(1)) &&
2493                 memory_usage > audio_size ) {
2494                 audio_cache->delete_oldest();
2495                 prev_memory_usage = memory_usage;
2496         }
2497 }
2498
2499 void MWindow::reset_android_remote()
2500 {
2501         gui->use_android_remote(preferences->android_remote);
2502 }
2503
2504
2505 void MWindow::show_keyframe_gui(Plugin *plugin)
2506 {
2507         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
2508 // Find existing thread
2509         for(int i = 0; i < keyframe_threads->size(); i++)
2510         {
2511                 if(keyframe_threads->get(i)->plugin == plugin)
2512                 {
2513                         keyframe_threads->get(i)->start_window(plugin, 0);
2514                         keyframe_gui_lock->unlock();
2515                         return;
2516                 }
2517         }
2518
2519 // Find unused thread
2520         for(int i = 0; i < keyframe_threads->size(); i++)
2521         {
2522                 if(!keyframe_threads->get(i)->plugin)
2523                 {
2524                         keyframe_threads->get(i)->start_window(plugin, 0);
2525                         keyframe_gui_lock->unlock();
2526                         return;
2527                 }
2528         }
2529
2530 // Create new thread
2531         KeyFrameThread *thread = new KeyFrameThread(this);
2532         keyframe_threads->append(thread);
2533         thread->start_window(plugin, 0);
2534
2535         keyframe_gui_lock->unlock();
2536 }
2537
2538
2539
2540
2541
2542 void MWindow::show_plugin(Plugin *plugin)
2543 {
2544         int done = 0;
2545
2546 SET_TRACE
2547 // Remove previously deleted plugin GUIs
2548         dead_plugin_lock->lock("MWindow::show_plugin");
2549         dead_plugins->remove_all_objects();
2550         dead_plugin_lock->unlock();
2551
2552 //printf("MWindow::show_plugin %d\n", __LINE__);
2553 SET_TRACE
2554
2555
2556         plugin_gui_lock->lock("MWindow::show_plugin");
2557         for(int i = 0; i < plugin_guis->total; i++)
2558         {
2559 // Pointer comparison
2560                 if(plugin_guis->get(i)->plugin == plugin)
2561                 {
2562                         plugin_guis->get(i)->raise_window();
2563                         done = 1;
2564                         break;
2565                 }
2566         }
2567 SET_TRACE
2568
2569 //printf("MWindow::show_plugin 1\n");
2570         if(!done)
2571         {
2572                 if(!plugin->track)
2573                 {
2574                         printf("MWindow::show_plugin track not defined.\n");
2575                 }
2576                 PluginServer *server = scan_plugindb(plugin->title,
2577                         plugin->track->data_type);
2578
2579 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
2580                 if(server && server->uses_gui)
2581                 {
2582                         PluginServer *gui = new PluginServer(*server);
2583                         plugin_guis->append(gui);
2584 // Needs mwindow to do GUI
2585                         gui->set_mwindow(this);
2586                         gui->open_plugin(0, preferences, edl, plugin);
2587                         plugin->show = 1;
2588                         gui->show_gui();
2589                 }
2590         }
2591         plugin_gui_lock->unlock();
2592 //printf("MWindow::show_plugin %d\n", __LINE__);
2593 SET_TRACE
2594 //sleep(1);
2595 //printf("MWindow::show_plugin 2\n");
2596 }
2597
2598 void MWindow::hide_plugin(Plugin *plugin, int lock)
2599 {
2600         plugin->show = 0;
2601 // Update the toggle
2602         gui->lock_window("MWindow::hide_plugin");
2603         gui->update(0, 1, 0, 0, 0, 0, 0);
2604         gui->unlock_window();
2605
2606         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
2607         for(int i = 0; i < plugin_guis->total; i++)
2608         {
2609                 if(plugin_guis->get(i)->plugin == plugin)
2610                 {
2611                         PluginServer *ptr = plugin_guis->get(i);
2612                         plugin_guis->remove(ptr);
2613                         if(lock) plugin_gui_lock->unlock();
2614 // Last command executed in client side close
2615 // Schedule for deletion
2616                         ptr->hide_gui();
2617                         delete_plugin(ptr);
2618 //sleep(1);
2619                         return;
2620                 }
2621         }
2622         if(lock) plugin_gui_lock->unlock();
2623 }
2624
2625 void MWindow::delete_plugin(PluginServer *plugin)
2626 {
2627         dead_plugin_lock->lock("MWindow::delete_plugin");
2628         dead_plugins->append(plugin);
2629         dead_plugin_lock->unlock();
2630 }
2631
2632 void MWindow::hide_plugins()
2633 {
2634         plugin_gui_lock->lock("MWindow::hide_plugins 1");
2635         while(plugin_guis->size())
2636         {
2637                 PluginServer *ptr = plugin_guis->get(0);
2638                 plugin_guis->remove(ptr);
2639                 plugin_gui_lock->unlock();
2640 // Last command executed in client side close
2641 // Schedule for deletion
2642                 ptr->hide_gui();
2643                 delete_plugin(ptr);
2644                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
2645         }
2646         plugin_gui_lock->unlock();
2647
2648         hide_keyframe_guis();
2649 }
2650
2651 void MWindow::hide_keyframe_guis()
2652 {
2653         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
2654         for(int i = 0; i < keyframe_threads->size(); i++)
2655         {
2656                 keyframe_threads->get(i)->close_window();
2657         }
2658         keyframe_gui_lock->unlock();
2659 }
2660
2661 void MWindow::hide_keyframe_gui(Plugin *plugin)
2662 {
2663         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
2664         for(int i = 0; i < keyframe_threads->size(); i++)
2665         {
2666                 if(keyframe_threads->get(i)->plugin == plugin)
2667                 {
2668                         keyframe_threads->get(i)->close_window();
2669                         break;
2670                 }
2671         }
2672         keyframe_gui_lock->unlock();
2673 }
2674
2675 void MWindow::update_keyframe_guis()
2676 {
2677 // Send new configuration to keyframe GUI's
2678         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
2679         for(int i = 0; i < keyframe_threads->size(); i++)
2680         {
2681                 KeyFrameThread *ptr = keyframe_threads->get(i);
2682                 if(edl->tracks->plugin_exists(ptr->plugin))
2683                         ptr->update_gui(1);
2684                 else
2685                 {
2686                         ptr->close_window();
2687                 }
2688         }
2689         keyframe_gui_lock->unlock();
2690 }
2691
2692 void MWindow::update_plugin_guis(int do_keyframe_guis)
2693 {
2694 // Send new configuration to plugin GUI's
2695         plugin_gui_lock->lock("MWindow::update_plugin_guis");
2696
2697         for(int i = 0; i < plugin_guis->size(); i++)
2698         {
2699                 PluginServer *ptr = plugin_guis->get(i);
2700                 if(edl->tracks->plugin_exists(ptr->plugin))
2701                         ptr->update_gui();
2702                 else
2703                 {
2704 // Schedule for deletion if no plugin
2705                         plugin_guis->remove_number(i);
2706                         i--;
2707
2708                         ptr->hide_gui();
2709                         delete_plugin(ptr);
2710                 }
2711         }
2712
2713
2714 // Change plugin variable if not visible
2715         Track *track = edl->tracks->first;
2716         while(track)
2717         {
2718                 for(int i = 0; i < track->plugin_set.size(); i++)
2719                 {
2720                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
2721                         while(plugin)
2722                         {
2723                                 int got_it = 0;
2724                                 for(int i = 0; i < plugin_guis->size(); i++)
2725                                 {
2726                                         PluginServer *server = plugin_guis->get(i);
2727                                         if(server->plugin == plugin)
2728                                         {
2729                                                 got_it = 1;
2730                                                 break;
2731                                         }
2732                                 }
2733
2734                                 if(!got_it) plugin->show = 0;
2735
2736                                 plugin = (Plugin*)plugin->next;
2737                         }
2738                 }
2739
2740                 track = track->next;
2741         }
2742
2743         plugin_gui_lock->unlock();
2744
2745
2746         if(do_keyframe_guis) update_keyframe_guis();
2747 }
2748
2749 int MWindow::plugin_gui_open(Plugin *plugin)
2750 {
2751         int result = 0;
2752         plugin_gui_lock->lock("MWindow::plugin_gui_open");
2753         for(int i = 0; i < plugin_guis->total; i++)
2754         {
2755                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2756                 {
2757                         result = 1;
2758                         break;
2759                 }
2760         }
2761         plugin_gui_lock->unlock();
2762         return result;
2763 }
2764
2765 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
2766 {
2767         plugin_gui_lock->lock("MWindow::render_plugin_gui");
2768         for(int i = 0; i < plugin_guis->total; i++)
2769         {
2770                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2771                 {
2772                         plugin_guis->get(i)->render_gui(data);
2773                         break;
2774                 }
2775         }
2776         plugin_gui_lock->unlock();
2777 }
2778
2779 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
2780 {
2781         plugin_gui_lock->lock("MWindow::render_plugin_gui");
2782         for(int i = 0; i < plugin_guis->total; i++)
2783         {
2784                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2785                 {
2786                         plugin_guis->get(i)->render_gui(data, size);
2787                         break;
2788                 }
2789         }
2790         plugin_gui_lock->unlock();
2791 }
2792
2793
2794 void MWindow::update_plugin_states()
2795 {
2796         plugin_gui_lock->lock("MWindow::update_plugin_states");
2797         for(int i = 0; i < plugin_guis->total; i++)
2798         {
2799                 int result = 0;
2800 // Get a plugin GUI
2801                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
2802                 PluginServer *src_plugingui = plugin_guis->get(i);
2803
2804 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
2805                 for(Track *track = edl->tracks->first;
2806                         track && !result;
2807                         track = track->next)
2808                 {
2809                         for(int j = 0;
2810                                 j < track->plugin_set.total && !result;
2811                                 j++)
2812                         {
2813                                 PluginSet *plugin_set = track->plugin_set[j];
2814                                 for(Plugin *plugin = (Plugin*)plugin_set->first;
2815                                         plugin && !result;
2816                                         plugin = (Plugin*)plugin->next)
2817                                 {
2818                                         if(plugin == src_plugin &&
2819                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
2820                                 }
2821                         }
2822                 }
2823
2824
2825 // Doesn't exist anymore
2826                 if(!result)
2827                 {
2828                         hide_plugin(src_plugin, 0);
2829                         i--;
2830                 }
2831         }
2832         plugin_gui_lock->unlock();
2833 }
2834
2835
2836 void MWindow::update_plugin_titles()
2837 {
2838         for(int i = 0; i < plugin_guis->total; i++)
2839         {
2840                 plugin_guis->get(i)->update_title();
2841         }
2842 }
2843
2844 int MWindow::asset_to_edl(EDL *new_edl,
2845         Asset *new_asset,
2846         RecordLabels *labels)
2847 {
2848 const int debug = 0;
2849 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
2850 __LINE__,
2851 new_asset->layers);
2852 // Keep frame rate, sample rate, and output size unchanged.
2853 // These parameters would revert the project if VWindow displayed an asset
2854 // of different size than the project.
2855         if(new_asset->video_data)
2856         {
2857                 new_edl->session->video_tracks = new_asset->layers;
2858         }
2859         else
2860                 new_edl->session->video_tracks = 0;
2861
2862 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2863
2864
2865
2866
2867
2868         if(new_asset->audio_data)
2869         {
2870                 new_edl->session->audio_tracks = new_asset->channels;
2871         }
2872         else
2873                 new_edl->session->audio_tracks = 0;
2874 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
2875
2876 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2877         new_edl->create_default_tracks();
2878 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
2879 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2880
2881
2882
2883 //printf("MWindow::asset_to_edl 3\n");
2884         new_edl->insert_asset(new_asset,
2885                 0,
2886                 0,
2887                 0,
2888                 labels);
2889 //printf("MWindow::asset_to_edl 3\n");
2890 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2891
2892 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
2893         if(edl->session->cursor_on_frames)
2894         {
2895                 double length = new_edl->tracks->total_length();
2896                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
2897                 new_edl->tracks->clear(length, edl_length, 1, 1);
2898         }
2899
2900
2901
2902
2903         char string[BCTEXTLEN];
2904         FileSystem fs;
2905         fs.extract_name(string, new_asset->path);
2906 //printf("MWindow::asset_to_edl 3\n");
2907
2908         strcpy(new_edl->local_session->clip_title, string);
2909 //printf("MWindow::asset_to_edl 4 %s\n", string);
2910 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2911
2912         return 0;
2913 }
2914
2915 int MWindow::edl_to_nested(EDL *new_edl,
2916         EDL *nested_edl)
2917 {
2918
2919 // Keep frame rate, sample rate, and output size unchanged.
2920 // These parameters would revert the project if VWindow displayed an asset
2921 // of different size than the project.
2922
2923
2924
2925 // Nest all video & audio outputs
2926         new_edl->session->video_tracks = 1;
2927         new_edl->session->audio_tracks = nested_edl->session->audio_channels;
2928         new_edl->create_default_tracks();
2929
2930
2931
2932         new_edl->insert_asset(0,
2933                 nested_edl,
2934                 0,
2935                 0,
2936                 0);
2937
2938         char string[BCTEXTLEN];
2939         FileSystem fs;
2940         fs.extract_name(string, nested_edl->path);
2941 //printf("MWindow::edl_to_nested %p %s\n", nested_edl, nested_edl->path);
2942
2943         strcpy(new_edl->local_session->clip_title, string);
2944
2945         return 0;
2946 }
2947
2948 // Reset everything after a load.
2949 void MWindow::update_project(int load_mode)
2950 {
2951         const int debug = 0;
2952
2953         if(debug) PRINT_TRACE
2954         restart_brender();
2955         edl->tracks->update_y_pixels(theme);
2956
2957         if(debug) PRINT_TRACE
2958
2959         if(load_mode == LOADMODE_REPLACE ||
2960                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2961         {
2962                 gui->load_panes();
2963         }
2964
2965         gui->update(1, 1, 1, 1, 1, 1, 1);
2966         if(debug) PRINT_TRACE
2967         gui->unlock_window();
2968
2969         cwindow->gui->lock_window("MWindow::update_project 1");
2970         cwindow->update(0, 0, 1, 1, 1);
2971         cwindow->gui->unlock_window();
2972
2973         if(debug) PRINT_TRACE
2974
2975 // Close all the vwindows
2976         if(load_mode == LOADMODE_REPLACE ||
2977                 load_mode == LOADMODE_REPLACE_CONCATENATE) {
2978                 if(debug) PRINT_TRACE
2979                 int first_vwindow = 0;
2980                 if(session->show_vwindow) first_vwindow = 1;
2981 // Change visible windows to no source
2982                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
2983                         VWindow *vwindow = vwindows[i];
2984                         if( !vwindow->is_running() ) continue;
2985                         vwindow->change_source(-1);
2986                 }
2987
2988 // Close remaining windows
2989                 for(int i = first_vwindow; i < vwindows.size(); i++) {
2990                         VWindow *vwindow = vwindows[i];
2991                         if( !vwindow->is_running() ) continue;
2992                         vwindow->close_window();
2993                 }
2994                 if(debug) PRINT_TRACE
2995         }
2996         else if(vwindows.size()) {
2997                 VWindow *vwindow = vwindows[DEFAULT_VWINDOW];
2998                 if( vwindow->is_running() ) {
2999                         vwindow->gui->lock_window("MWindow::update_project");
3000                         vwindow->update(1);
3001                         vwindow->gui->unlock_window();
3002                 }
3003         }
3004
3005         if(debug) PRINT_TRACE
3006         cwindow->gui->lock_window("MWindow::update_project 2");
3007         cwindow->gui->timebar->update(0);
3008         cwindow->gui->unlock_window();
3009
3010         if(debug) PRINT_TRACE
3011         cwindow->playback_engine->que->send_command(CURRENT_FRAME,
3012                 CHANGE_ALL,
3013                 edl,
3014                 1);
3015
3016         awindow->gui->async_update_assets();
3017         if(debug) PRINT_TRACE
3018
3019         gui->lock_window("MWindow::update_project");
3020         gui->flush();
3021         if(debug) PRINT_TRACE
3022 }
3023
3024 void MWindow::remove_indexfile(Indexable *indexable)
3025 {
3026         if( !indexable->is_asset ) return;
3027         Asset *asset = (Asset *)indexable;
3028 // Erase file
3029         IndexFile::delete_index(preferences, asset, ".toc");
3030         IndexFile::delete_index(preferences, asset, ".idx");
3031         IndexFile::delete_index(preferences, asset, ".mkr");
3032 }
3033
3034 void MWindow::rebuild_indices()
3035 {
3036         for(int i = 0; i < session->drag_assets->total; i++)
3037         {
3038                 Indexable *indexable = session->drag_assets->get(i);
3039 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3040                 remove_indexfile(indexable);
3041 // Schedule index build
3042                 IndexState *index_state = indexable->index_state;
3043                 index_state->index_status = INDEX_NOTTESTED;
3044                 if( indexable->is_asset ) {
3045                         Asset *asset = (Asset *)indexable;
3046                         if( asset->format != FILE_PCM ) {
3047                                 asset->format = FILE_UNKNOWN;
3048                                 asset->reset_audio();
3049                         }
3050                         asset->reset_video();
3051 //                      File file; // re-probe the asset
3052 //                      file.open_file(preferences, asset, 1, 0);
3053                 }
3054                 mainindexes->add_next_asset(0, indexable);
3055         }
3056         mainindexes->start_build();
3057 }
3058
3059
3060 void MWindow::save_backup()
3061 {
3062         FileXML file;
3063         edl->optimize();
3064         edl->set_path(session->filename);
3065         char backup_path[BCTEXTLEN];
3066         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3067                 File::get_config_path(), BACKUP_FILE);
3068         edl->save_xml(&file, backup_path, 0, 0);
3069         file.terminate_string();
3070         FileSystem fs;
3071         fs.complete_path(backup_path);
3072
3073         if(file.write_to_file(backup_path))
3074         {
3075                 char string2[256];
3076                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
3077                 gui->show_message(string2);
3078         }
3079 }
3080
3081 void MWindow::load_backup()
3082 {
3083         ArrayList<char*> path_list;
3084         path_list.set_array_delete();
3085         char *out_path;
3086         char backup_path[BCTEXTLEN];
3087         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3088                 File::get_config_path(), BACKUP_FILE);
3089         FileSystem fs;
3090         fs.complete_path(backup_path);
3091
3092         path_list.append(out_path = new char[strlen(backup_path) + 1]);
3093         strcpy(out_path, backup_path);
3094
3095         load_filenames(&path_list, LOADMODE_REPLACE, 0);
3096         edl->local_session->clip_title[0] = 0;
3097 // This is unique to backups since the path of the backup is different than the
3098 // path of the project.
3099         set_filename(edl->path);
3100         path_list.remove_all_objects();
3101         save_backup();
3102 }
3103
3104 static inline int gcd(int m, int n)
3105 {
3106         int r;
3107         if( m < n ) { r = m;  m = n;  n = r; }
3108         while( (r = m % n) != 0 ) { m = n;  n = r; }
3109         return n;
3110 }
3111
3112 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
3113 {
3114         w = 1;  h = 1;
3115         if(!width || !height) return 1;
3116         if( width == 720 && (height == 480 || height == 576) ) {
3117                 w = 4;  h = 3;  return 0; // for NTSC and PAL
3118         }
3119         double ar = (double)width / height;
3120 // square-ish pixels
3121         if( EQUIV(ar, 1.0000) ) return 0;
3122         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
3123         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
3124         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
3125         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
3126         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
3127         int ww = width, hh = height;
3128         // numerator, denominator must be under mx
3129         int mx = 255, n = gcd(ww, hh);
3130         if( n > 1 ) { ww /= n; hh /= n; }
3131         // search near height in case extra/missing lines
3132         if( ww >= mx || hh >= mx ) {
3133                 double err = height;  // +/- 2 percent height
3134                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
3135                         int iw = width, ih = height+i;
3136                         if( (n=gcd(iw, ih)) > 1 ) {
3137                                 int u = iw/n;  if( u >= mx ) continue;
3138                                 int v = ih/n;  if( v >= mx ) continue;
3139                                 double r = (double) u/v, er = fabs(ar-r);
3140                                 if( er >= err ) continue;
3141                                 err = er;  ww = u;  hh = v;
3142                         }
3143                 }
3144         }
3145
3146         w = ww;  h = hh;
3147         return 0;
3148 }
3149
3150 void MWindow::reset_caches()
3151 {
3152         frame_cache->remove_all();
3153         wave_cache->remove_all();
3154         audio_cache->remove_all();
3155         video_cache->remove_all();
3156         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3157                 cwindow->playback_engine->audio_cache->remove_all();
3158         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3159                 cwindow->playback_engine->video_cache->remove_all();
3160
3161         for(int i = 0; i < vwindows.size(); i++) {
3162                 VWindow *vwindow = vwindows[i];
3163                 if( !vwindow->is_running() ) continue;
3164                 if(vwindow->playback_engine && vwindow->playback_engine->audio_cache)
3165                         vwindow->playback_engine->audio_cache->remove_all();
3166                 if(vwindow->playback_engine && vwindow->playback_engine->video_cache)
3167                         vwindow->playback_engine->video_cache->remove_all();
3168         }
3169 }
3170
3171 void MWindow::remove_asset_from_caches(Asset *asset)
3172 {
3173         gui->resource_thread->get_video_source(0);
3174         gui->resource_thread->get_audio_source(0);
3175         frame_cache->remove_asset(asset);
3176         wave_cache->remove_asset(asset);
3177         audio_cache->delete_entry(asset);
3178         video_cache->delete_entry(asset);
3179         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3180                 cwindow->playback_engine->audio_cache->delete_entry(asset);
3181         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3182                 cwindow->playback_engine->video_cache->delete_entry(asset);
3183         for(int i = 0; i < vwindows.size(); i++) {
3184                 VWindow *vwindow = vwindows[i];
3185                 if( !vwindow->is_running() ) continue;
3186                 if(vwindow->playback_engine && vwindow->playback_engine->audio_cache)
3187                         vwindow->playback_engine->audio_cache->delete_entry(asset);
3188                 if(vwindow->playback_engine && vwindow->playback_engine->video_cache)
3189                         vwindow->playback_engine->video_cache->delete_entry(asset);
3190         }
3191 }
3192
3193
3194 void MWindow::remove_assets_from_project(int push_undo, int redraw,
3195                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
3196 {
3197         for(int i = 0; i < drag_assets->total; i++) {
3198                 Indexable *indexable = drag_assets->get(i);
3199                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
3200         }
3201
3202 // Remove from VWindow.
3203         for(int i = 0; i < session->drag_clips->total; i++) {
3204                 for(int j = 0; j < vwindows.size(); j++) {
3205                         VWindow *vwindow = vwindows[j];
3206                         if( !vwindow->is_running() ) continue;
3207                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
3208                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
3209                                 vwindow->delete_source(1, 1);
3210                                 vwindow->gui->unlock_window();
3211                         }
3212                 }
3213         }
3214
3215         for(int i = 0; i < drag_assets->size(); i++) {
3216                 for(int j = 0; j < vwindows.size(); j++) {
3217                         VWindow *vwindow = vwindows[j];
3218                         if( !vwindow->is_running() ) continue;
3219                         if(drag_assets->get(i) == vwindow->get_source()) {
3220                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
3221                                 vwindow->delete_source(1, 1);
3222                                 vwindow->gui->unlock_window();
3223                         }
3224                 }
3225         }
3226
3227         for(int i = 0; i < drag_assets->size(); i++) {
3228                 Indexable *indexable = drag_assets->get(i);
3229                 remove_indexfile(indexable);
3230         }
3231
3232 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3233         if(push_undo) undo->update_undo_before();
3234         if(drag_assets) edl->remove_from_project(drag_assets);
3235         if(drag_clips) edl->remove_from_project(drag_clips);
3236         if(redraw) save_backup();
3237         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
3238         if(redraw) {
3239                 restart_brender();
3240
3241                 gui->lock_window("MWindow::remove_assets_from_project 3");
3242                 gui->update(1, 1, 1, 1, 0, 1, 0);
3243                 gui->unlock_window();
3244
3245         // Removes from playback here
3246                 sync_parameters(CHANGE_ALL);
3247         }
3248
3249         awindow->gui->async_update_assets();
3250 }
3251
3252 void MWindow::remove_assets_from_disk()
3253 {
3254 // Remove from disk
3255         for(int i = 0; i < session->drag_assets->total; i++)
3256         {
3257                 remove(session->drag_assets->get(i)->path);
3258         }
3259
3260         remove_assets_from_project(1,
3261                 1,
3262                 session->drag_assets,
3263                 session->drag_clips);
3264 }
3265
3266 void MWindow::dump_plugins(FILE *fp)
3267 {
3268         if( !plugindb ) return;
3269         for(int i = 0; i < plugindb->total; i++)
3270         {
3271                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
3272                         " synth=%d transition=%d theme=%d %s\n",
3273                         plugindb->get(i)->plugin_type,
3274                         plugindb->get(i)->audio,
3275                         plugindb->get(i)->video,
3276                         plugindb->get(i)->realtime,
3277                         plugindb->get(i)->multichannel,
3278                         plugindb->get(i)->get_synthesis(),
3279                         plugindb->get(i)->transition,
3280                         plugindb->get(i)->theme,
3281                         plugindb->get(i)->title);
3282         }
3283 }
3284
3285 void MWindow::dump_edl(FILE *fp)
3286 {
3287         if( !edl ) return;
3288         edl->dump(fp);
3289 }
3290
3291 void MWindow::dump_undo(FILE *fp)
3292 {
3293         if( !undo ) return;
3294         undo->dump(fp);
3295 }
3296
3297 void MWindow::dump_exe(FILE *fp)
3298 {
3299         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
3300         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
3301
3302         int ret = -1, n = 100;
3303         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
3304                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
3305                 ret = 0;
3306         }
3307         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
3308
3309         struct stat st;
3310         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
3311         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
3312         struct tm *tm = localtime(&st.st_mtime);
3313         char mtime[256];
3314         strftime(mtime, sizeof(mtime), "%F %T", tm);
3315         fprintf(fp,"mtime: %s\n", mtime);
3316
3317         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
3318         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
3319         uint8_t *bfr = 0;
3320         int64_t bfrsz = 0;
3321         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
3322         int64_t maxsz = 1024*pagsz;
3323         int64_t size = st.st_size, pos = 0;
3324         SHA1 sha1;
3325         while( (bfrsz = size-pos) > 0 ) {
3326                 if( bfrsz > maxsz ) bfrsz = maxsz;
3327                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
3328                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
3329                 if( bfr == MAP_FAILED ) break;
3330                 sha1.addBytes(bfr, bfrsz);
3331                 munmap(bfr, bfrsz);
3332                 pos += bfrsz;
3333         }
3334         close(fd);
3335         ret = pos < size ? EIO : 0;
3336         fprintf(fp, "SHA1: ");
3337         uint8_t digest[20];  sha1.computeHash(digest);
3338         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
3339         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
3340         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
3341         fprintf(fp, "\n");
3342 }
3343
3344 void MWindow::trap_hook(FILE *fp, void *vp)
3345 {
3346         MWindow *mwindow = (MWindow *)vp;
3347 //      fprintf(fp, "\nPLUGINS:\n");
3348 //      mwindow->dump_plugins(fp);
3349         fprintf(fp, "\nEDL:\n");
3350         mwindow->dump_edl(fp);
3351         fprintf(fp, "\nUNDO:\n");
3352         mwindow->dump_undo(fp);
3353         fprintf(fp, "\nEXE:\n");
3354         mwindow->dump_exe(fp);
3355 }
3356
3357
3358
3359
3360
3361
3362 int MWindow::save_defaults()
3363 {
3364         gui->save_defaults(defaults);
3365         edl->save_defaults(defaults);
3366         session->save_defaults(defaults);
3367         preferences->save_defaults(defaults);
3368
3369         for(int i = 0; i < plugin_guis->total; i++)
3370         {
3371 // Pointer comparison
3372                 plugin_guis->get(i)->save_defaults();
3373         }
3374         awindow->save_defaults(defaults);
3375
3376         defaults->save();
3377         return 0;
3378 }
3379
3380 int MWindow::run_script(FileXML *script)
3381 {
3382         int result = 0, result2 = 0;
3383         while(!result && !result2)
3384         {
3385                 result = script->read_tag();
3386                 if(!result)
3387                 {
3388                         if(script->tag.title_is("new_project"))
3389                         {
3390 // Run new in immediate mode.
3391 //                              gui->mainmenu->new_project->run_script(script);
3392                         }
3393                         else
3394                         if(script->tag.title_is("record"))
3395                         {
3396 // Run record as a thread.  It is a terminal command.
3397                                 ;
3398 // Will read the complete scipt file without letting record read it if not
3399 // terminated.
3400                                 result2 = 1;
3401                         }
3402                         else
3403                         {
3404                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
3405                         }
3406                 }
3407         }
3408         return result2;
3409 }
3410
3411 // ================================= synchronization
3412
3413
3414 int MWindow::interrupt_indexes()
3415 {
3416         mainprogress->cancelled = 1;
3417         mainindexes->interrupt_build();
3418         return 0;
3419 }
3420
3421
3422
3423 void MWindow::next_time_format()
3424 {
3425         switch(edl->session->time_format)
3426         {
3427                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
3428                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
3429                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3430                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
3431                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
3432                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
3433                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
3434         }
3435
3436         time_format_common();
3437 }
3438
3439 void MWindow::prev_time_format()
3440 {
3441         switch(edl->session->time_format)
3442         {
3443                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
3444                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
3445                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
3446                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3447                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
3448                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
3449                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
3450         }
3451
3452         time_format_common();
3453 }
3454
3455 void MWindow::time_format_common()
3456 {
3457         gui->lock_window("MWindow::next_time_format");
3458         gui->redraw_time_dependancies();
3459
3460
3461         char string[BCTEXTLEN], string2[BCTEXTLEN];
3462         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
3463         gui->show_message(string);
3464         gui->flush();
3465         gui->unlock_window();
3466 }
3467
3468
3469 int MWindow::set_filename(const char *filename)
3470 {
3471         if( filename != session->filename )
3472                 strcpy(session->filename, filename);
3473         if( filename != edl->path )
3474                 strcpy(edl->path, filename);
3475
3476         if(gui)
3477         {
3478                 if(filename[0] == 0)
3479                 {
3480                         gui->set_title(PROGRAM_NAME);
3481                 }
3482                 else
3483                 {
3484                         FileSystem dir;
3485                         char string[BCTEXTLEN], string2[BCTEXTLEN];
3486                         dir.extract_name(string, filename);
3487                         sprintf(string2, PROGRAM_NAME ": %s", string);
3488                         gui->set_title(string2);
3489                 }
3490         }
3491         return 0;
3492 }
3493
3494
3495
3496
3497
3498
3499
3500
3501 int MWindow::set_loop_boundaries()
3502 {
3503         double start = edl->local_session->get_selectionstart();
3504         double end = edl->local_session->get_selectionend();
3505
3506         if(start !=
3507                 end)
3508         {
3509                 ;
3510         }
3511         else
3512         if(edl->tracks->total_length())
3513         {
3514                 start = 0;
3515                 end = edl->tracks->total_length();
3516         }
3517         else
3518         {
3519                 start = end = 0;
3520         }
3521
3522         if(edl->local_session->loop_playback && start != end)
3523         {
3524                 edl->local_session->loop_start = start;
3525                 edl->local_session->loop_end = end;
3526         }
3527         return 0;
3528 }
3529
3530
3531
3532
3533
3534
3535
3536 int MWindow::reset_meters()
3537 {
3538         cwindow->gui->lock_window("MWindow::reset_meters 1");
3539         cwindow->gui->meters->reset_meters();
3540         cwindow->gui->unlock_window();
3541
3542         for(int j = 0; j < vwindows.size(); j++) {
3543                 VWindow *vwindow = vwindows[j];
3544                 if( !vwindow->is_running() ) continue;
3545                 vwindow->gui->lock_window("MWindow::reset_meters 2");
3546                 vwindow->gui->meters->reset_meters();
3547                 vwindow->gui->unlock_window();
3548         }
3549
3550         lwindow->gui->lock_window("MWindow::reset_meters 3");
3551         lwindow->gui->panel->reset_meters();
3552         lwindow->gui->unlock_window();
3553
3554         gui->lock_window("MWindow::reset_meters 4");
3555         gui->reset_meters();
3556         gui->unlock_window();
3557         return 0;
3558 }
3559
3560
3561 void MWindow::resync_guis()
3562 {
3563 // Update GUIs
3564         restart_brender();
3565         gui->lock_window("MWindow::resync_guis");
3566         gui->update(1, 1, 1, 1, 1, 1, 0);
3567         gui->unlock_window();
3568
3569         cwindow->gui->lock_window("MWindow::resync_guis");
3570         cwindow->gui->resize_event(cwindow->gui->get_w(),
3571                 cwindow->gui->get_h());
3572         int channels = edl->session->audio_channels;
3573         cwindow->gui->meters->set_meters(channels, 1);
3574         cwindow->gui->flush();
3575         cwindow->gui->unlock_window();
3576
3577         for(int i = 0; i < vwindows.size(); i++) {
3578                 VWindow *vwindow = vwindows[i];
3579                 if( !vwindow->is_running() ) continue;
3580                 vwindow->gui->lock_window("MWindow::resync_guis");
3581                 vwindow->gui->resize_event(vwindow->gui->get_w(),
3582                         vwindow->gui->get_h());
3583                 vwindow->gui->meters->set_meters(channels, 1);
3584                 vwindow->gui->flush();
3585                 vwindow->gui->unlock_window();
3586         }
3587
3588         lwindow->gui->lock_window("MWindow::resync_guis");
3589         lwindow->gui->panel->set_meters(channels, 1);
3590         lwindow->gui->flush();
3591         lwindow->gui->unlock_window();
3592
3593 // Warn user
3594         if(((edl->session->output_w % 4) ||
3595                 (edl->session->output_h % 4)) &&
3596                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
3597         {
3598                 MainError::show_error(
3599                         _("This project's dimensions are not multiples of 4 so\n"
3600                         "it can't be rendered by OpenGL."));
3601         }
3602
3603
3604 // Flash frame
3605         sync_parameters(CHANGE_ALL);
3606 }
3607
3608 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
3609 {
3610         File *file = new File;
3611         EDLSession *session = edl->session;
3612         double old_framerate = session->frame_rate;
3613         double old_samplerate = session->sample_rate;
3614         int old_auto_keyframes = session->auto_keyframes;
3615         session->auto_keyframes = 0;
3616         int result = file->open_file(preferences, asset, 1, 0);
3617         if( !result && delete_tracks > 0 )
3618                 undo->update_undo_before();
3619         if( !result && asset->video_data && asset->get_video_layers() > 0 ) {
3620                 // try to get asset up to date, may fail
3621                 file->select_video_stream(asset, vstream);
3622                 // either way use what was/is there.
3623                 double framerate = asset->get_frame_rate();
3624                 int width = asset->get_w();
3625                 int height = asset->get_h();
3626                 // must be multiple of 4 for opengl
3627                 width = (width+3) & ~3;  height = (height+3) & ~3;
3628                 int driver = session->playback_config->vconfig->driver;
3629                 int color_model = file->get_best_colormodel(asset, driver);
3630 //              color_model = BC_CModels::is_yuv(color_model) ?
3631 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
3632 //                      BC_CModels::is_float(color_model) ?
3633 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
3634 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
3635 // have alpha for now
3636                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
3637                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
3638                 session->color_model = color_model;
3639                 session->output_w = width;
3640                 session->output_h = height;
3641                 session->frame_rate = framerate;
3642                 // not, asset->actual_width/actual_height
3643                 asset->width = session->output_w;
3644                 asset->height = session->output_h;
3645                 asset->frame_rate = session->frame_rate;
3646                 create_aspect_ratio(session->aspect_w, session->aspect_h,
3647                         session->output_w, session->output_h);
3648                 Track *track = edl->tracks->first;
3649                 for( Track *next_track=0; track; track=next_track ) {
3650                         next_track = track->next;
3651                         if( track->data_type != TRACK_VIDEO ) continue;
3652                         if( delete_tracks ) {
3653                                 Edit *edit = track->edits->first;
3654                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
3655                                         next_edit = edit->next;
3656                                         if( edit->channel != vstream ||
3657                                             !edit->asset || !edit->asset->is_asset ||
3658                                             !asset->equivalent(*edit->asset,1,1,edl) )
3659                                                 delete edit;
3660                                 }
3661                         }
3662                         if( track->edits->first ) {
3663                                 track->track_w = edl->session->output_w;
3664                                 track->track_h = edl->session->output_h;
3665                         }
3666                         else if( delete_tracks )
3667                                 edl->tracks->delete_track(track);
3668                 }
3669                 edl->retrack();
3670                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
3671         }
3672         if( !result && asset->audio_data && asset->channels > 0 ) {
3673                 session->sample_rate = asset->get_sample_rate();
3674                 int64_t channel_mask = 0;
3675                 int astrm = !asset->video_data ? -1 :
3676                         file->get_audio_for_video(vstream, astream, channel_mask);
3677                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
3678                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
3679                 int channels = 0;
3680                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
3681                 if( channels < 1 ) channels = 1;
3682                 if( channels > 6 ) channels = 6;
3683                 session->audio_tracks = session->audio_channels = channels;
3684                 switch( channels ) {
3685                 case 6:
3686                         session->achannel_positions[0] = 90;
3687                         session->achannel_positions[1] = 150;
3688                         session->achannel_positions[2] = 30;
3689                         session->achannel_positions[3] = 210;
3690                         session->achannel_positions[4] = 330;
3691                         session->achannel_positions[5] = 270;
3692                         break;
3693                 case 2:
3694                         session->achannel_positions[0] = 180;
3695                         session->achannel_positions[1] = 0;
3696                         break;
3697                 case 1:
3698                         session->achannel_positions[1] = 90;
3699                         break;
3700                 default: {
3701                         if( !channels ) break;
3702                         double t = 0, dt = 360./channels;
3703                         for( int i=channels; --i>=0; t+=dt )
3704                                 session->achannel_positions[i] = int(t+0.5);
3705                         break; }
3706                 }
3707                 remap_audio(MWindow::AUDIO_1_TO_1);
3708
3709                 if( delete_tracks ) {
3710                         Track *track = edl->tracks->first;
3711                         for( Track *next_track=0; track; track=next_track ) {
3712                                 next_track = track->next;
3713                                 if( track->data_type != TRACK_AUDIO ) continue;
3714                                 Edit *edit = track->edits->first;
3715                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
3716                                         next_edit = edit->next;
3717                                         if( !((1<<edit->channel) & channel_mask) ||
3718                                             !edit->asset || !edit->asset->is_asset ||
3719                                             !asset->equivalent(*edit->asset,1,1,edl) )
3720                                                 delete edit;
3721                                 }
3722                                 if( !track->edits->first )
3723                                         edl->tracks->delete_track(track);
3724                         }
3725                 }
3726                 edl->rechannel();
3727                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
3728         }
3729         delete file;
3730         session->auto_keyframes = old_auto_keyframes;
3731         if( !result && delete_tracks > 0 ) {
3732                 save_backup();
3733                 undo->update_undo_after(_("select asset"), LOAD_ALL);
3734         }
3735         resync_guis();
3736         return result;
3737 }
3738
3739 int MWindow::select_asset(int vtrack, int delete_tracks)
3740 {
3741         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
3742         if( !track )
3743                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
3744         if( !track ) return 1;
3745         Edit *edit = track->edits->first;
3746         if( !edit ) return 1;
3747         Asset *asset = edit->asset;
3748         if( !asset || !asset->is_asset ) return 1;
3749         return select_asset(asset, edit->channel, 0, delete_tracks);
3750 }
3751
3752 void MWindow::dump_plugindb(FILE *fp)
3753 {
3754         if( !plugindb ) return;
3755         for(int i = 0; i < plugindb->total; i++)
3756                 plugindb->get(i)->dump(fp);
3757 }
3758
3759 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
3760 {
3761         Auto *current = 0;
3762         double unit_position = edl->local_session->get_selectionstart(1);
3763         unit_position = patch->track->to_units(unit_position, 0);
3764
3765         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
3766         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
3767 }
3768
3769 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
3770 {
3771         Auto *current = 0;
3772         double unit_position = edl->local_session->get_selectionstart(1);
3773         unit_position = patch->track->to_units(unit_position, 0);
3774
3775         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
3776         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
3777 }
3778
3779 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
3780 {
3781         Auto *current = 0;
3782         double unit_position = edl->local_session->get_selectionstart(1);
3783         unit_position = patch->track->to_units(unit_position, 0);
3784
3785         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
3786         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
3787 }
3788
3789