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