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