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