4 * Copyright (C) 1997-2014 Adam Williams <broadcast at earthling dot net>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "automation.h"
26 #include "bcsignals.h"
30 #include "condition.h"
33 #include "edlsession.h"
36 #include "filesystem.h"
38 #include "floatauto.h"
39 #include "floatautos.h"
40 #include "indexable.h"
41 #include "indexfile.h"
42 #include "indexstate.h"
43 #include "indexthread.h"
45 #include "localsession.h"
46 #include "mainprogress.h"
47 #include "mwindowgui.h"
49 #include "preferences.h"
50 #include "removefile.h"
51 #include "renderengine.h"
52 #include "resourcepixmap.h"
55 #include "timelinepane.h"
56 #include "trackcanvas.h"
58 #include "transportque.h"
71 #include <sys/types.h>
73 #include <linux/iso_fs.h>
75 // check for isofs volume_id for dvd/cdrom
77 static int udf_volume_id(const char *path, char *fname)
80 if( stat(path,&st) ) return 1;
81 // search mounted devices
82 FILE *fp = fopen("/proc/mounts","r");
86 while( result && !feof(fp) && !ferror(fp) ) {
87 char devpath[BCTEXTLEN], mpath[BCTEXTLEN];
88 char options[BCTEXTLEN], line[BCTEXTLEN];
89 char fstype[64], zero1[16], zero2[16];
90 if( !fgets(&line[0], sizeof(line)-1, fp) ) break;
91 int n = sscanf(&line[0], "%s %s %s %s %s %s\n",
92 devpath, mpath, fstype, options, zero1, zero2);
93 if( n != 6 ) continue;
94 // check udf filesystems
95 if( strcmp(fstype,"udf") != 0 ) continue;
97 if( stat(devpath,&dst) ) continue;
98 if( st.st_dev != dst.st_rdev ) continue;
99 int fd = open(devpath,O_RDONLY);
100 if( fd < 0 ) continue;
101 struct iso_primary_descriptor id;
102 if( lseek(fd,0x8000,SEEK_SET) == 0x8000 )
103 n = read(fd,&id,sizeof(id));
105 if( n != sizeof(id) ) continue;
106 // look for magic number
107 if( strncmp(ISO_STANDARD_ID,id.id,sizeof(id.id)) ) continue;
108 // look for volume_id
109 if( !isalnum(id.volume_id[0]) ) continue;
110 char *bp = (char*)&id.volume_id[0], *cp = fname;
111 for( int i=0; i<(int)sizeof(id.volume_id); ++i ) *cp++ = *bp++;
112 while( --cp>=fname && *cp==' ' ) *cp = 0;
113 if( !*fname ) continue;
114 // fname = volume_id _ creation_date
115 ++cp; *cp++ = '_'; bp = (char*)&id.creation_date[0];
116 for( int i=0; i<(int)sizeof(id.creation_date)-1; ++i ) {
117 if( !isdigit(*bp) ) break;
121 if( cp-fname > 4 ) result = 0;
128 // Use native sampling rates for files so the same index can be used in
129 // multiple projects.
131 IndexFile::IndexFile(MWindow *mwindow)
133 //printf("IndexFile::IndexFile 1\n");
135 this->mwindow = mwindow;
136 //printf("IndexFile::IndexFile 2\n");
137 redraw_timer = new Timer;
140 IndexFile::IndexFile(MWindow *mwindow,
141 Indexable *indexable)
143 //printf("IndexFile::IndexFile 2\n");
145 this->mwindow = mwindow;
146 this->indexable = indexable;
147 redraw_timer = new Timer;
150 indexable->add_user();
151 source_channels = indexable->get_audio_channels();
152 source_samplerate = indexable->get_sample_rate();
153 source_length = indexable->get_audio_samples();
157 IndexFile::~IndexFile()
159 //printf("IndexFile::~IndexFile 1\n");
161 if(indexable) indexable->remove_user();
165 void IndexFile::reset()
177 IndexState* IndexFile::get_state()
179 IndexState *index_state = 0;
180 if(indexable) index_state = indexable->index_state;
186 int IndexFile::open_index()
188 IndexState *index_state = 0;
191 // use buffer if being built
192 index_state = get_state();
194 if(index_state->index_status == INDEX_BUILDING)
200 if(!(result = open_file()))
202 // opened existing file
210 index_state->index_status = INDEX_READY;
221 void IndexFile::delete_index(Preferences *preferences,
222 Indexable *indexable, const char *suffix)
224 char index_filename[BCTEXTLEN];
225 char source_filename[BCTEXTLEN];
226 const char *path = indexable->path;
228 get_index_filename(source_filename,
229 preferences->index_directory,
230 index_filename, path, suffix);
231 //printf("IndexFile::delete_index %s %s\n", source_filename, index_filename);
232 remove_file(index_filename);
235 int IndexFile::open_file()
239 const char *path = indexable->path;
242 //printf("IndexFile::open_file %f\n", indexable->get_frame_rate());
244 get_index_filename(source_filename,
245 mwindow->preferences->index_directory,
249 if(debug) printf("IndexFile::open_file %d index_filename=%s\n",
252 fd = fopen(index_filename, "rb");
255 // Index file already exists.
256 // Get its last size without changing the real asset status.
257 Indexable *test_indexable = new Indexable(0);
259 test_indexable->copy_indexable(indexable);
260 read_info(test_indexable);
261 IndexState *index_state = test_indexable->index_state;
264 if(fs.get_date(index_filename) < fs.get_date(test_indexable->path))
266 if(debug) printf("IndexFile::open_file %d index_date=%jd source_date=%jd\n",
268 fs.get_date(index_filename),
269 fs.get_date(test_indexable->path));
271 // index older than source
277 if(fs.get_size(test_indexable->path) != index_state->index_bytes)
279 // source file is a different size than index source file
280 if(debug) printf("IndexFile::open_file %d index_size=%jd source_size=%jd\n",
282 index_state->index_bytes,
283 fs.get_size(test_indexable->path));
290 if(debug) printf("IndexFile::open_file %d\n",
292 fseek(fd, 0, SEEK_END);
293 file_length = ftell(fd);
294 fseek(fd, 0, SEEK_SET);
297 test_indexable->Garbage::remove_user();
302 if(debug) printf("IndexFile::open_file %d index_filename=%s doesn't exist\n",
311 int IndexFile::open_source()
313 //printf("IndexFile::open_source %p %s\n", asset, asset->path);
315 if(indexable && indexable->is_asset)
317 if(!source) source = new File;
319 Asset *asset = (Asset*)indexable;
320 if(source->open_file(mwindow->preferences,
323 //printf("IndexFile::open_source() Couldn't open %s.\n", asset->path);
329 asset->index_state->index_bytes = fs.get_size(asset->path);
330 source_length = source->get_audio_length();
331 int proxy_scale = asset->proxy_scale;
332 if( proxy_scale > 0 ) {
333 asset->width = asset->actual_width * proxy_scale;
334 asset->height = asset->actual_height * proxy_scale;
340 TransportCommand command;
341 command.command = NORMAL_FWD;
342 command.get_edl()->copy_all((EDL*)indexable);
343 command.change_type = CHANGE_ALL;
344 command.realtime = 0;
345 cache = new CICache(mwindow->preferences);
346 render_engine = new RenderEngine(0,
347 mwindow->preferences, 0, 0);
348 render_engine->set_acache(cache);
349 render_engine->arm_command(&command);
351 indexable->index_state->index_bytes = fs.get_size(indexable->path);
357 void IndexFile::close_source()
362 delete render_engine;
369 int64_t IndexFile::get_required_scale()
374 // get scale of index file
375 // Total peaks which may be stored in buffer
376 int64_t peak_count = mwindow->preferences->index_size /
377 (2 * sizeof(float) * source_channels);
379 source_length / result > peak_count;
383 // Takes too long to draw from source on a CDROM. Make indexes for
389 int IndexFile::get_index_filename(char *source_filename,
390 char *index_directory,
391 char *index_filename,
392 const char *input_filename,
395 const char *input_fn = input_filename;
396 char volume_id[BCTEXTLEN];
397 // Replace mount/directory with volume_id if isofs
398 if( !udf_volume_id(input_filename, volume_id) )
400 char *cp = strrchr((char*)input_filename,'/');
401 if( cp ) input_fn = cp + 1;
402 for( cp=volume_id; *cp; ++cp );
403 *cp++ = '_'; strcpy(cp, input_fn);
404 input_fn = volume_id;
406 // Replace slashes and dots
408 int len = strlen(input_fn);
409 for(i = 0, j = 0; i < len; i++)
411 if(input_fn[i] != '/' &&
413 source_filename[j++] = input_fn[i];
417 source_filename[j++] = '_';
420 source_filename[j] = 0;
422 fs.join_names(index_filename, index_directory, source_filename);
423 strcat(index_filename, suffix ? suffix : ".idx");
427 int IndexFile::interrupt_index()
433 // Read data into buffers
435 int IndexFile::create_index(MainProgressBar *progress)
442 // open the source file
443 if(open_source()) return 1;
444 source_channels = indexable->get_audio_channels();
445 source_samplerate = indexable->get_sample_rate();
446 source_length = indexable->get_audio_samples();
450 get_index_filename(source_filename,
451 mwindow->preferences->index_directory,
457 // Some file formats have their own sample index.
458 // Test for index in stream table of contents
459 if(source && !source->get_index(this, progress))
461 IndexState *index_state = get_state();
462 index_state->index_status = INDEX_READY;
466 // Build index from scratch
470 // Indexes are now built for everything since it takes too long to draw
471 // from CDROM source.
473 // get amount to read at a time in floats
474 int64_t buffersize = 65536;
475 char string[BCTEXTLEN];
476 sprintf(string, _("Creating %s."), index_filename);
478 progress->update_title(string);
479 progress->update_length(source_length);
480 redraw_timer->update();
483 // thread out index thread
484 IndexThread *index_thread = new IndexThread(mwindow,
489 index_thread->start_build();
491 // current sample in source file
492 int64_t position = 0;
493 int64_t fragment_size = buffersize;
494 int current_buffer = 0;
497 // pass through file once
498 // printf("IndexFile::create_index %d source_length=%jd source=%p progress=%p\n",
504 while(position < source_length && !result)
507 if(source_length - position < fragment_size && fragment_size == buffersize) fragment_size = source_length - position;
509 index_thread->input_lock[current_buffer]->lock("IndexFile::create_index 1");
510 index_thread->input_len[current_buffer] = fragment_size;
513 int cancelled = progress->update(position);
514 //printf("IndexFile::create_index cancelled=%d\n", cancelled);
517 index_thread->interrupt_flag ||
525 if(source && !result)
529 !result && channel < source_channels;
532 // Read from source file
533 source->set_audio_position(position);
534 source->set_channel(channel);
536 if(source->read_samples(
537 index_thread->buffer_in[current_buffer][channel],
544 if(render_engine && !result)
547 if(render_engine->arender)
549 result = render_engine->arender->process_buffer(
550 index_thread->buffer_in[current_buffer],
556 for(int i = 0; i < source_channels; i++)
558 bzero(index_thread->buffer_in[current_buffer][i]->get_data(),
559 fragment_size * sizeof(double));
566 // Release buffer to thread
569 index_thread->output_lock[current_buffer]->unlock();
571 if(current_buffer >= TOTAL_INDEX_BUFFERS) current_buffer = 0;
572 position += fragment_size;
576 index_thread->input_lock[current_buffer]->unlock();
582 // end thread cleanly
583 index_thread->input_lock[current_buffer]->lock("IndexFile::create_index 2");
584 index_thread->last_buffer[current_buffer] = 1;
585 index_thread->output_lock[current_buffer]->unlock();
586 index_thread->stop_build();
603 mwindow->edl->set_index_file(indexable);
609 int IndexFile::redraw_edits(int force)
611 int64_t difference = redraw_timer->get_scaled_difference(1000);
613 if(difference > 250 || force)
615 redraw_timer->update();
616 mwindow->gui->lock_window("IndexFile::redraw_edits");
617 mwindow->edl->set_index_file(indexable);
618 mwindow->gui->draw_indexes(indexable);
619 mwindow->gui->unlock_window();
627 int IndexFile::draw_index(
629 ResourcePixmap *pixmap,
635 IndexState *index_state = get_state();
636 int pane_number = canvas->pane->number;
637 //index_state->dump();
640 if(debug) printf("IndexFile::draw_index %d\n", __LINE__);
641 if(index_state->index_zoom == 0)
643 printf(_("IndexFile::draw_index: index has 0 zoom\n"));
646 if(debug) printf("IndexFile::draw_index %d\n", __LINE__);
648 // test channel number
649 if(edit->channel > source_channels) return 1;
650 if(debug) printf("IndexFile::draw_index %d source_samplerate=%d "
651 "w=%d samplerate=%jd zoom_sample=%jd\n",
652 __LINE__, source_samplerate, w,
653 mwindow->edl->session->sample_rate,
654 mwindow->edl->local_session->zoom_sample);
656 // calculate a virtual x where the edit_x should be in floating point
657 double virtual_edit_x = 1.0 *
658 edit->track->from_units(edit->startproject) *
659 mwindow->edl->session->sample_rate /
660 mwindow->edl->local_session->zoom_sample -
661 mwindow->edl->local_session->view_start[pane_number];
663 // samples in segment to draw relative to asset
664 FloatAutos *speed_autos = !edit->track->has_speed() ? 0 :
665 (FloatAutos *)edit->track->automation->autos[AUTOMATION_SPEED];
666 double project_zoom = mwindow->edl->local_session->zoom_sample;
667 int64_t edit_position = (x + pixmap->pixmap_x - virtual_edit_x) * project_zoom;
668 int64_t start_position = edit->startsource;
669 start_position += !speed_autos ? edit_position :
670 speed_autos->automation_integral(edit->startproject, edit_position, PLAY_FORWARD);
671 int64_t end_position = edit->startsource;
672 edit_position = (x + w + pixmap->pixmap_x - virtual_edit_x) * project_zoom;
673 end_position += !speed_autos ? edit_position :
674 speed_autos->automation_integral(edit->startproject, edit_position, PLAY_FORWARD);
675 double session_sample_rate = mwindow->edl->session->sample_rate;
676 double asset_over_session = (double)indexable->get_sample_rate() / session_sample_rate;
677 int64_t start_source = start_position * asset_over_session;
678 if( start_source < 0 ) start_source = 0;
679 int64_t start_index = start_source / index_state->index_zoom;
680 int64_t end_source = end_position * asset_over_session;
681 if( end_source < 0 ) end_source = 0;
682 int64_t end_index = end_source / index_state->index_zoom;
683 // start/length of index to read in floats
684 start_index *= 2; end_index *= 2;
685 // length of index available in floats
686 int64_t size_index = index_state->index_status == INDEX_BUILDING ?
687 index_state->get_channel_used(edit->channel) * 2 :
688 index_state->get_index_size(edit->channel);
689 // Clamp length of index to read by available data
690 if( end_index >= size_index ) end_index = size_index;
691 int64_t length_index = end_index - start_index;
692 if( length_index <= 0 ) return 0;
694 // Start and length of fragment to read from file in bytes.
696 int buffer_shared = 0;
697 int rect_audio = mwindow->preferences->rectify_audio;;
698 int center_pixel = !rect_audio ?
699 mwindow->edl->local_session->zoom_track / 2 :
700 mwindow->edl->local_session->zoom_track;
701 if( edit->track->show_titles() )
702 center_pixel += mwindow->theme->get_image("title_bg_data")->get_h();
704 if( index_state->index_status == INDEX_BUILDING ) {
705 // index is in RAM, being built
706 buffer = index_state->get_channel_buffer(edit->channel);
707 if( !buffer ) return 0;
708 buffer += start_index;
712 buffer = new float[length_index + 1];
713 int64_t length_buffer = length_index * sizeof(float);
714 // add file/channel offset
715 int64_t index_offset = index_state->get_index_offset(edit->channel);
716 int64_t file_offset = (index_offset + start_index) * sizeof(float);
717 int64_t file_pos = index_state->index_start + file_offset;
718 int64_t read_length = file_length - file_pos;
719 if( read_length > length_buffer )
720 read_length = length_buffer;
721 int64_t length_read = 0;
722 if( read_length > 0 ) {
723 fseek(fd, file_pos, SEEK_SET);
724 length_read = fread(buffer, 1, read_length + sizeof(float), fd);
725 length_read &= ~(sizeof(float)-1);
727 if( (read_length-=length_read) > 0 )
728 memset((char*)buffer + length_read, 0, read_length);
732 canvas->set_color(mwindow->theme->audio_color);
734 int prev_y1 = center_pixel;
735 int prev_y2 = center_pixel;
737 int zoom_y = !rect_audio ?
738 mwindow->edl->local_session->zoom_y / 2 :
739 mwindow->edl->local_session->zoom_y;
740 int max_y = center_pixel + zoom_y - 1;
741 edit_position = (x + pixmap->pixmap_x - virtual_edit_x) * project_zoom;
742 int64_t speed_position = edit->startsource;
743 speed_position += !speed_autos ? edit_position :
744 speed_autos->automation_integral(edit->startproject, edit_position, PLAY_FORWARD);
745 int64_t source_position = speed_position * asset_over_session;
746 int64_t index_position = source_position / index_state->index_zoom;
747 int64_t i = 2 * index_position - start_index;
748 CLAMP(i, 0, length_index);
751 for( int64_t x1=0; x1<w && i < length_index; ++x1 ) {
752 float highsample = !rect_audio ? buffer[i] : fabsf(buffer[i]); ++i;
753 float lowsample = !rect_audio ? buffer[i] : fabsf(buffer[i]); ++i;
755 edit_position = (x2 + pixmap->pixmap_x - virtual_edit_x) * project_zoom;
756 int64_t speed_position = edit->startsource;
757 speed_position += !speed_autos ? edit_position :
758 speed_autos->automation_integral(edit->startproject, edit_position, PLAY_FORWARD);
759 source_position = speed_position * asset_over_session;
760 index_position = source_position / index_state->index_zoom;
761 int64_t k = 2 * index_position - start_index;
762 CLAMP(k, 0, length_index);
764 float high = !rect_audio ? buffer[i] : fabsf(buffer[i]);
765 highsample = MAX(highsample, high); ++i;
766 float low = !rect_audio ? buffer[i] : fabsf(buffer[i]);
767 lowsample = MIN(lowsample, low); ++i;
770 int y1 = (int)(center_pixel - highsample * zoom_y);
771 int y2 = (int)(center_pixel - lowsample * zoom_y);
772 CLAMP(y1, 0, max_y); int next_y1 = y1;
773 CLAMP(y2, 0, max_y); int next_y2 = y2;
774 //printf("draw_line (%f,%f) = %d,%d, %d,%d\n", lowsample, highsample, x2, y1, x2, y2);
777 // A different algorithm has to be used if it's 1 sample per pixel and the
778 // index is used. Now the min and max values are equal so we join the max samples.
779 if(mwindow->edl->local_session->zoom_sample == 1) {
780 canvas->draw_line(x2 - 1, !rect_audio ? prev_y1 : center_pixel, x2, y1, pixmap);
783 // Extend line height if it doesn't connect to previous line
785 if(y1 > prev_y2) y1 = prev_y2 + 1;
786 if(y2 < prev_y1) y2 = prev_y1 - 1;
791 canvas->draw_line(x2, y1, x2, !rect_audio ? y2 : center_pixel, pixmap);
799 if(!buffer_shared) delete [] buffer;
801 if(debug) printf("IndexFile::draw_index %d\n", __LINE__);
805 int IndexFile::close_index()
815 int IndexFile::remove_index()
817 IndexState *index_state = get_state();
818 if(index_state->index_status == INDEX_READY ||
819 index_state->index_status == INDEX_NOTTESTED)
822 remove(index_filename);
827 int IndexFile::read_info(Indexable *test_indexable)
831 // Store format in actual asset.
832 // If it's a nested EDL, we never want the format, just the index info.
833 if(!test_indexable) test_indexable = indexable;
834 if(!test_indexable) return 1;
836 IndexState * index_state = test_indexable->index_state;
837 if(index_state->index_status == INDEX_NOTTESTED)
839 // read start of index data
840 int temp = fread((char*)&(index_state->index_start), sizeof(int64_t), 1, fd);
841 //printf("IndexFile::read_info %d %f\n", __LINE__, test_indexable->get_frame_rate());
844 // read test_indexable info from index
847 data = new char[index_state->index_start];
848 temp = fread(data, index_state->index_start - sizeof(int64_t), 1, fd);
851 data[index_state->index_start - sizeof(int64_t)] = 0;
853 xml.read_from_string(data);
858 // Read the file format & index state.
859 if(test_indexable->is_asset)
861 Asset *test_asset = (Asset *)test_indexable;
862 Asset *asset = new Asset;
865 //printf("IndexFile::read_info %d %f\n", __LINE__, asset->get_frame_rate());
867 if( asset->format == FILE_UNKNOWN ||
868 test_asset->format != asset->format ) {
869 if(debug) printf("IndexFile::read_info %d\n", __LINE__);
872 asset->remove_user();
873 if( ret ) return ret;
877 // Read only the index state for a nested EDL
879 if(debug) printf("IndexFile::read_info %d\n", __LINE__);
882 result = xml.read_tag();
885 if(xml.tag.title_is("INDEX"))
887 index_state->read_xml(&xml, source_channels);
888 if(debug) printf("IndexFile::read_info %d\n", __LINE__);
889 if(debug) index_state->dump();