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