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