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