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 "bcsignals.h"
28 #include "condition.h"
31 #include "edlsession.h"
34 #include "filesystem.h"
37 #include "indexable.h"
38 #include "indexfile.h"
39 #include "indexstate.h"
40 #include "indexthread.h"
42 #include "localsession.h"
43 #include "mainprogress.h"
44 #include "mwindowgui.h"
46 #include "preferences.h"
47 #include "removefile.h"
48 #include "renderengine.h"
49 #include "resourcepixmap.h"
52 #include "timelinepane.h"
53 #include "trackcanvas.h"
55 #include "transportque.h"
68 #include <sys/types.h>
70 #include <linux/iso_fs.h>
72 // check for isofs volume_id for dvd/cdrom
74 static int udf_volume_id(const char *path, char *fname)
77 if( stat(path,&st) ) return 1;
78 // search mounted devices
79 FILE *fp = fopen("/proc/mounts","r");
83 while( result && !feof(fp) && !ferror(fp) ) {
84 char devpath[BCTEXTLEN], mpath[BCTEXTLEN];
85 char options[BCTEXTLEN], line[BCTEXTLEN];
86 char fstype[64], zero1[16], zero2[16];
87 if( !fgets(&line[0], sizeof(line)-1, fp) ) break;
88 int n = sscanf(&line[0], "%s %s %s %s %s %s\n",
89 devpath, mpath, fstype, options, zero1, zero2);
90 if( n != 6 ) continue;
91 // check udf filesystems
92 if( strcmp(fstype,"udf") != 0 ) continue;
94 if( stat(devpath,&dst) ) continue;
95 if( st.st_dev != dst.st_rdev ) continue;
96 int fd = open(devpath,O_RDONLY);
97 if( fd < 0 ) continue;
98 struct iso_primary_descriptor id;
99 if( lseek(fd,0x8000,SEEK_SET) == 0x8000 )
100 n = read(fd,&id,sizeof(id));
102 if( n != sizeof(id) ) continue;
103 // look for magic number
104 if( strncmp(ISO_STANDARD_ID,id.id,sizeof(id.id)) ) continue;
105 // look for volume_id
106 if( !isalnum(id.volume_id[0]) ) continue;
107 char *bp = &id.volume_id[0], *cp = fname;
108 for( int i=0; i<(int)sizeof(id.volume_id); ++i ) *cp++ = *bp++;
109 while( --cp>=fname && *cp==' ' ) *cp = 0;
110 if( !*fname ) continue;
111 // fname = volume_id _ creation_date
112 ++cp; *cp++ = '_'; bp = &id.creation_date[0];
113 for( int i=0; i<(int)sizeof(id.creation_date)-1; ++i ) {
114 if( !isdigit(*bp) ) break;
118 if( cp-fname > 4 ) result = 0;
125 // Use native sampling rates for files so the same index can be used in
126 // multiple projects.
128 IndexFile::IndexFile(MWindow *mwindow)
130 //printf("IndexFile::IndexFile 1\n");
132 this->mwindow = mwindow;
133 //printf("IndexFile::IndexFile 2\n");
134 redraw_timer = new Timer;
137 IndexFile::IndexFile(MWindow *mwindow,
138 Indexable *indexable)
140 //printf("IndexFile::IndexFile 2\n");
142 this->mwindow = mwindow;
143 this->indexable = indexable;
144 redraw_timer = new Timer;
148 indexable->add_user();
149 source_channels = indexable->get_audio_channels();
150 source_samplerate = indexable->get_sample_rate();
151 source_length = indexable->get_audio_samples();
155 IndexFile::~IndexFile()
157 //printf("IndexFile::~IndexFile 1\n");
159 if(indexable) indexable->remove_user();
163 void IndexFile::reset()
175 IndexState* IndexFile::get_state()
177 IndexState *index_state = 0;
178 if(indexable) index_state = indexable->index_state;
184 int IndexFile::open_index()
186 IndexState *index_state = 0;
189 // use buffer if being built
190 index_state = get_state();
192 if(index_state->index_status == INDEX_BUILDING)
198 if(!(result = open_file()))
200 // opened existing file
208 index_state->index_status = INDEX_READY;
219 void IndexFile::delete_index(Preferences *preferences,
220 Indexable *indexable, const char *suffix)
222 char index_filename[BCTEXTLEN];
223 char source_filename[BCTEXTLEN];
224 const char *path = indexable->path;
226 get_index_filename(source_filename,
227 preferences->index_directory,
228 index_filename, path, suffix);
229 //printf("IndexFile::delete_index %s %s\n", source_filename, index_filename);
230 remove_file(index_filename);
233 int IndexFile::open_file()
237 const char *path = indexable->path;
240 //printf("IndexFile::open_file %f\n", indexable->get_frame_rate());
242 get_index_filename(source_filename,
243 mwindow->preferences->index_directory,
247 if(debug) printf("IndexFile::open_file %d index_filename=%s\n",
250 fd = fopen(index_filename, "rb");
253 // Index file already exists.
254 // Get its last size without changing the real asset status.
255 Indexable *test_indexable = new Indexable(0);
257 test_indexable->copy_indexable(indexable);
258 read_info(test_indexable);
259 IndexState *index_state = test_indexable->index_state;
262 if(fs.get_date(index_filename) < fs.get_date(test_indexable->path))
264 if(debug) printf("IndexFile::open_file %d index_date=" _LD " source_date=" _LD "\n",
266 fs.get_date(index_filename),
267 fs.get_date(test_indexable->path));
269 // index older than source
275 if(fs.get_size(test_indexable->path) != index_state->index_bytes)
277 // source file is a different size than index source file
278 if(debug) printf("IndexFile::open_file %d index_size=" _LD " source_size=" _LD "\n",
280 index_state->index_bytes,
281 fs.get_size(test_indexable->path));
288 if(debug) printf("IndexFile::open_file %d\n",
290 fseek(fd, 0, SEEK_END);
291 file_length = ftell(fd);
292 fseek(fd, 0, SEEK_SET);
295 test_indexable->Garbage::remove_user();
300 if(debug) printf("IndexFile::open_file %d index_filename=%s doesn't exist\n",
309 int IndexFile::open_source()
311 //printf("IndexFile::open_source %p %s\n", asset, asset->path);
313 if(indexable && indexable->is_asset)
315 if(!source) source = new File;
317 Asset *asset = (Asset*)indexable;
318 if(source->open_file(mwindow->preferences,
321 //printf("IndexFile::open_source() Couldn't open %s.\n", asset->path);
327 asset->index_state->index_bytes = fs.get_size(asset->path);
328 source_length = source->get_audio_length();
333 TransportCommand command;
334 command.command = NORMAL_FWD;
335 command.get_edl()->copy_all((EDL*)indexable);
336 command.change_type = CHANGE_ALL;
337 command.realtime = 0;
338 cache = new CICache(mwindow->preferences);
339 render_engine = new RenderEngine(0,
340 mwindow->preferences, 0, 0, 0);
341 render_engine->set_acache(cache);
342 render_engine->arm_command(&command);
344 indexable->index_state->index_bytes = fs.get_size(indexable->path);
350 void IndexFile::close_source()
355 delete render_engine;
362 int64_t IndexFile::get_required_scale()
367 // get scale of index file
368 // Total peaks which may be stored in buffer
369 int64_t peak_count = mwindow->preferences->index_size /
370 (2 * sizeof(float) * source_channels);
372 source_length / result > peak_count;
376 // Takes too long to draw from source on a CDROM. Make indexes for
382 int IndexFile::get_index_filename(char *source_filename,
383 char *index_directory,
384 char *index_filename,
385 const char *input_filename,
388 const char *input_fn = input_filename;
389 char volume_id[BCTEXTLEN];
390 // Replace mount/directory with volume_id if isofs
391 if( !udf_volume_id(input_filename, volume_id) )
393 char *cp = strrchr((char*)input_filename,'/');
394 if( cp ) input_fn = cp + 1;
395 for( cp=volume_id; *cp; ++cp );
396 *cp++ = '_'; strcpy(cp, input_fn);
397 input_fn = volume_id;
399 // Replace slashes and dots
401 int len = strlen(input_fn);
402 for(i = 0, j = 0; i < len; i++)
404 if(input_fn[i] != '/' &&
406 source_filename[j++] = input_fn[i];
410 source_filename[j++] = '_';
413 source_filename[j] = 0;
415 fs.join_names(index_filename, index_directory, source_filename);
416 strcat(index_filename, suffix ? suffix : ".idx");
420 int IndexFile::interrupt_index()
426 // Read data into buffers
428 int IndexFile::create_index(MainProgressBar *progress)
435 // open the source file
436 if(open_source()) return 1;
440 get_index_filename(source_filename,
441 mwindow->preferences->index_directory,
447 // Some file formats have their own sample index.
448 // Test for index in stream table of contents
449 if(source && !source->get_index(index_filename))
451 IndexState *index_state = get_state();
452 index_state->index_status = INDEX_READY;
456 // Build index from scratch
460 // Indexes are now built for everything since it takes too long to draw
461 // from CDROM source.
463 // get amount to read at a time in floats
464 int64_t buffersize = 65536;
465 char string[BCTEXTLEN];
466 sprintf(string, _("Creating %s."), index_filename);
468 progress->update_title(string);
469 progress->update_length(source_length);
470 redraw_timer->update();
473 // thread out index thread
474 IndexThread *index_thread = new IndexThread(mwindow,
479 index_thread->start_build();
481 // current sample in source file
482 int64_t position = 0;
483 int64_t fragment_size = buffersize;
484 int current_buffer = 0;
487 // pass through file once
488 // printf("IndexFile::create_index %d source_length=" _LD " source=%p progress=%p\n",
494 while(position < source_length && !result)
497 if(source_length - position < fragment_size && fragment_size == buffersize) fragment_size = source_length - position;
499 index_thread->input_lock[current_buffer]->lock("IndexFile::create_index 1");
500 index_thread->input_len[current_buffer] = fragment_size;
503 int cancelled = progress->update(position);
504 //printf("IndexFile::create_index cancelled=%d\n", cancelled);
507 index_thread->interrupt_flag ||
515 if(source && !result)
519 !result && channel < source_channels;
522 // Read from source file
523 source->set_audio_position(position);
524 source->set_channel(channel);
526 if(source->read_samples(
527 index_thread->buffer_in[current_buffer][channel],
534 if(render_engine && !result)
537 if(render_engine->arender)
539 result = render_engine->arender->process_buffer(
540 index_thread->buffer_in[current_buffer],
546 for(int i = 0; i < source_channels; i++)
548 bzero(index_thread->buffer_in[current_buffer][i]->get_data(),
549 fragment_size * sizeof(double));
556 // Release buffer to thread
559 index_thread->output_lock[current_buffer]->unlock();
561 if(current_buffer >= TOTAL_INDEX_BUFFERS) current_buffer = 0;
562 position += fragment_size;
566 index_thread->input_lock[current_buffer]->unlock();
572 // end thread cleanly
573 index_thread->input_lock[current_buffer]->lock("IndexFile::create_index 2");
574 index_thread->last_buffer[current_buffer] = 1;
575 index_thread->output_lock[current_buffer]->unlock();
576 index_thread->stop_build();
593 mwindow->edl->set_index_file(indexable);
599 int IndexFile::redraw_edits(int force)
601 int64_t difference = redraw_timer->get_scaled_difference(1000);
603 if(difference > 250 || force)
605 redraw_timer->update();
606 mwindow->gui->lock_window("IndexFile::redraw_edits");
607 mwindow->edl->set_index_file(indexable);
608 mwindow->gui->draw_indexes(indexable);
609 mwindow->gui->unlock_window();
617 int IndexFile::draw_index(
619 ResourcePixmap *pixmap,
625 IndexState *index_state = get_state();
626 int pane_number = canvas->pane->number;
627 //index_state->dump();
630 if(debug) printf("IndexFile::draw_index %d\n", __LINE__);
631 if(index_state->index_zoom == 0)
633 printf(_("IndexFile::draw_index: index has 0 zoom\n"));
636 if(debug) printf("IndexFile::draw_index %d\n", __LINE__);
638 // test channel number
639 if(edit->channel > source_channels) return 1;
640 if(debug) printf("IndexFile::draw_index %d source_samplerate=%d "
641 "w=%d samplerate=" _LD " zoom_sample=" _LD "\n",
642 __LINE__, source_samplerate, w,
643 mwindow->edl->session->sample_rate,
644 mwindow->edl->local_session->zoom_sample);
646 // calculate a virtual x where the edit_x should be in floating point
647 double virtual_edit_x = 1.0 *
648 edit->track->from_units(edit->startproject) *
649 mwindow->edl->session->sample_rate /
650 mwindow->edl->local_session->zoom_sample -
651 mwindow->edl->local_session->view_start[pane_number];
653 // samples in segment to draw relative to asset
654 double asset_over_session = (double)source_samplerate /
655 mwindow->edl->session->sample_rate;
656 int64_t startsource = (int64_t)(((pixmap->pixmap_x - virtual_edit_x + x) *
657 mwindow->edl->local_session->zoom_sample +
660 // just in case we get a numerical error
661 if (startsource < 0) startsource = 0;
662 int64_t length = (int64_t)(w *
663 mwindow->edl->local_session->zoom_sample *
665 int64_t lengthindex = length / index_state->index_zoom * 2;
666 int64_t startindex = startsource / index_state->index_zoom * 2;
667 // length of index to read in floats
668 // length of index available in floats
669 int64_t endindex = index_state->index_status == INDEX_BUILDING ?
670 index_state->get_channel_used(edit->channel) * 2 :
671 index_state->get_index_size(edit->channel);
672 // Clamp length of index to read by available data
673 if(startindex + lengthindex >= endindex )
674 lengthindex = endindex - startindex;
675 if( lengthindex <= 0 ) return 0;
677 // Actual length read from file in bytes
679 // Start and length of fragment to read from file in bytes.
680 int64_t startfile, lengthfile;
682 int buffer_shared = 0;
683 int center_pixel = mwindow->edl->local_session->zoom_track / 2;
684 if( mwindow->edl->session->show_titles )
685 center_pixel += mwindow->theme->get_image("title_bg_data")->get_h();
686 //int miny = center_pixel - mwindow->edl->local_session->zoom_track / 2;
687 //int maxy = center_pixel + mwindow->edl->local_session->zoom_track / 2;
689 // get zoom_sample relative to index zoomx
690 double index_frames_per_pixel = mwindow->edl->local_session->zoom_sample /
691 index_state->index_zoom *
696 if(index_state->index_status == INDEX_BUILDING)
698 // index is in RAM, being built
699 buffer = index_state->get_channel_buffer(edit->channel);
700 if( !buffer ) return 0;
701 buffer += startindex;
706 // add channel offset
707 startindex += index_state->get_index_offset(edit->channel);
708 // index is stored in a file
709 buffer = new float[lengthindex + 1];
711 startfile = index_state->index_start + startindex * sizeof(float);
712 lengthfile = lengthindex * sizeof(float);
715 if(startfile < file_length)
717 fseek(fd, startfile, SEEK_SET);
719 length_read = lengthfile;
720 if(startfile + length_read > file_length)
721 length_read = file_length - startfile;
723 (void)fread(buffer, length_read + sizeof(float), 1, fd);
726 if(length_read < lengthfile) {
727 int pos = length_read / sizeof(float);
728 int file_length = lengthfile / sizeof(float);
729 while( pos < file_length ) buffer[pos++] = 0;
733 canvas->set_color(mwindow->theme->audio_color);
735 double current_frame = 0;
736 float highsample = buffer[0];
737 float lowsample = buffer[1];
738 int prev_y1 = center_pixel;
739 int prev_y2 = center_pixel;
741 int zoom_y = mwindow->edl->local_session->zoom_y, zoom_y2 = zoom_y / 2;
742 int max_y = canvas->get_h();
743 int zmax_y = center_pixel + zoom_y2 - 1;
744 if( zmax_y < max_y ) max_y = zmax_y;
747 for(int bufferposition = 0;
748 bufferposition < lengthindex;
751 if(current_frame >= index_frames_per_pixel)
754 int y1 = (int)(center_pixel - highsample * zoom_y2);
755 int y2 = (int)(center_pixel - lowsample * zoom_y2);
756 CLAMP(y1, 0, max_y); int next_y1 = y1;
757 CLAMP(y2, 0, max_y); int next_y2 = y2;
758 //printf("draw_line (%f,%f) = %d,%d, %d,%d\n", lowsample, highsample, x1 + x, y1, x1 + x, y2);
761 // A different algorithm has to be used if it's 1 sample per pixel and the
762 // index is used. Now the min and max values are equal so we join the max samples.
763 if(mwindow->edl->local_session->zoom_sample == 1)
765 canvas->draw_line(x1 + x - 1, prev_y1, x1 + x, y1, pixmap);
769 // Extend line height if it doesn't connect to previous line
772 if(y1 > prev_y2) y1 = prev_y2 + 1;
773 if(y2 < prev_y1) y2 = prev_y1 - 1;
782 canvas->draw_line(x1 + x, y1, x1 + x, y2, pixmap);
784 current_frame -= index_frames_per_pixel;
788 highsample = buffer[bufferposition];
789 lowsample = buffer[bufferposition + 1];
793 highsample = MAX(highsample, buffer[bufferposition]);
794 lowsample = MIN(lowsample, buffer[bufferposition + 1]);
801 y1 = (int)(center_pixel - highsample * zoom_y2);
802 y2 = (int)(center_pixel - lowsample * zoom_y2);
803 canvas->draw_line(x1 + x, y1, x1 + x, y2, pixmap);
810 if(!buffer_shared) delete [] buffer;
812 if(debug) printf("IndexFile::draw_index %d\n", __LINE__);
816 int IndexFile::close_index()
826 int IndexFile::remove_index()
828 IndexState *index_state = get_state();
829 if(index_state->index_status == INDEX_READY ||
830 index_state->index_status == INDEX_NOTTESTED)
833 remove(index_filename);
838 int IndexFile::read_info(Indexable *test_indexable)
842 // Store format in actual asset.
843 // If it's a nested EDL, we never want the format, just the index info.
844 if(!test_indexable) test_indexable = indexable;
845 if(!test_indexable) return 1;
847 IndexState * index_state = test_indexable->index_state;
848 if(index_state->index_status == INDEX_NOTTESTED)
850 // read start of index data
851 int temp = fread((char*)&(index_state->index_start), sizeof(int64_t), 1, fd);
852 //printf("IndexFile::read_info %d %f\n", __LINE__, test_indexable->get_frame_rate());
855 // read test_indexable info from index
858 data = new char[index_state->index_start];
859 temp = fread(data, index_state->index_start - sizeof(int64_t), 1, fd);
862 data[index_state->index_start - sizeof(int64_t)] = 0;
864 xml.read_from_string(data);
869 // Read the file format & index state.
870 if(test_indexable->is_asset)
872 Asset *asset = (Asset*)test_indexable;
875 //printf("IndexFile::read_info %d %f\n", __LINE__, asset->get_frame_rate());
877 if(asset->format == FILE_UNKNOWN)
879 if(debug) printf("IndexFile::read_info %d\n", __LINE__);
885 // Read only the index state for a nested EDL
887 if(debug) printf("IndexFile::read_info %d\n", __LINE__);
890 result = xml.read_tag();
893 if(xml.tag.title_is("INDEX"))
895 index_state->read_xml(&xml, source_channels);
896 if(debug) printf("IndexFile::read_info %d\n", __LINE__);
897 if(debug) index_state->dump();