fix math bug with numthreads computation
[ardour2.git] / gtk2_ardour / midi_streamview.cc
blob97573d40082f24fb82dd5fb320134b6b257dc4b8
1 /*
2 Copyright (C) 2001-2007 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 #include <cmath>
20 #include <cassert>
21 #include <utility>
23 #include <gtkmm.h>
25 #include <gtkmm2ext/gtk_ui.h>
27 #include "ardour/midi_diskstream.h"
28 #include "ardour/midi_playlist.h"
29 #include "ardour/midi_region.h"
30 #include "ardour/midi_source.h"
31 #include "ardour/midi_track.h"
32 #include "ardour/region_factory.h"
33 #include "ardour/smf_source.h"
34 #include "ardour/session.h"
36 #include "ardour_ui.h"
37 #include "canvas-simplerect.h"
38 #include "gui_thread.h"
39 #include "lineset.h"
40 #include "midi_region_view.h"
41 #include "midi_streamview.h"
42 #include "midi_time_axis.h"
43 #include "midi_util.h"
44 #include "public_editor.h"
45 #include "region_selection.h"
46 #include "region_view.h"
47 #include "rgb_macros.h"
48 #include "selection.h"
49 #include "simplerect.h"
50 #include "utils.h"
52 using namespace std;
53 using namespace ARDOUR;
54 using namespace PBD;
55 using namespace Editing;
57 MidiStreamView::MidiStreamView (MidiTimeAxisView& tv)
58 : StreamView (tv)
59 , note_range_adjustment(0.0f, 0.0f, 0.0f)
60 , _range_dirty(false)
61 , _range_sum_cache(-1.0)
62 , _lowest_note(60)
63 , _highest_note(71)
64 , _data_note_min(60)
65 , _data_note_max(71)
67 color_handler ();
69 /* use a group dedicated to MIDI underlays. Audio underlays are not in this group. */
70 midi_underlay_group = new ArdourCanvas::Group (*_canvas_group);
71 midi_underlay_group->lower_to_bottom();
73 /* put the note lines in the timeaxisview's group, so it
74 can be put below ghost regions from MIDI underlays*/
75 _note_lines = new ArdourCanvas::LineSet(*_canvas_group, ArdourCanvas::LineSet::Horizontal);
77 _note_lines->property_x1() = 0;
78 _note_lines->property_y1() = 0;
79 _note_lines->property_x2() = trackview().editor().frame_to_pixel (max_frames);
80 _note_lines->property_y2() = 0;
82 _note_lines->signal_event().connect(sigc::bind(
83 sigc::mem_fun(_trackview.editor(), &PublicEditor::canvas_stream_view_event),
84 _note_lines, &_trackview));
86 _note_lines->lower_to_bottom();
88 ColorsChanged.connect(sigc::mem_fun(*this, &MidiStreamView::draw_note_lines));
90 note_range_adjustment.set_page_size(_highest_note - _lowest_note);
91 note_range_adjustment.set_value(_lowest_note);
93 note_range_adjustment.signal_value_changed().connect(
94 sigc::mem_fun(*this, &MidiStreamView::note_range_adjustment_changed));
97 MidiStreamView::~MidiStreamView ()
101 static void
102 veto_note_range(uint8_t& min, uint8_t& max)
104 /* Legal notes, thanks */
105 clamp_to_0_127(min);
106 clamp_to_0_127(max);
108 /* Always display at least one octave in [0, 127] */
109 if (max == 127) {
110 if (min > (127 - 11)) {
111 min = 127 - 11;
113 } else if (max < min + 11) {
114 uint8_t d = 11 - (max - min);
115 if (max + d/2 > 127) {
116 min -= d;
117 } else {
118 min -= d / 2;
119 max += d / 2;
122 assert(max - min >= 11);
123 assert(max <= 127);
124 assert(min <= 127);
127 RegionView*
128 MidiStreamView::create_region_view (boost::shared_ptr<Region> r, bool /*wfd*/, bool)
130 boost::shared_ptr<MidiRegion> region = boost::dynamic_pointer_cast<MidiRegion> (r);
132 if (region == 0) {
133 return 0;
136 RegionView* region_view = new MidiRegionView (_canvas_group, _trackview, region,
137 _samples_per_unit, region_color);
139 region_view->init (region_color, false);
141 return region_view;
144 RegionView*
145 MidiStreamView::add_region_view_internal (boost::shared_ptr<Region> r, bool wfd, bool recording)
147 boost::shared_ptr<MidiRegion> region = boost::dynamic_pointer_cast<MidiRegion> (r);
149 if (region == 0) {
150 return 0;
153 for (list<RegionView*>::iterator i = region_views.begin(); i != region_views.end(); ++i) {
154 if ((*i)->region() == r) {
156 /* great. we already have a MidiRegionView for this Region. use it again. */
158 (*i)->set_valid (true);
160 display_region(dynamic_cast<MidiRegionView*>(*i), wfd);
162 return 0;
166 MidiRegionView* region_view = dynamic_cast<MidiRegionView*> (create_region_view (r, wfd, recording));
167 if (region_view == 0) {
168 return 0;
171 region_views.push_front (region_view);
173 /* display events and find note range */
174 display_region (region_view, wfd);
176 /* catch regionview going away */
177 region->DropReferences.connect (*this, invalidator (*this), boost::bind (&MidiStreamView::remove_region_view, this, region), gui_context());
179 RegionViewAdded (region_view);
181 return region_view;
184 void
185 MidiStreamView::display_region(MidiRegionView* region_view, bool load_model)
187 if ( ! region_view)
188 return;
190 region_view->enable_display(true);
192 boost::shared_ptr<MidiSource> source(region_view->midi_region()->midi_source(0));
194 if (load_model) {
195 source->load_model();
198 _range_dirty = update_data_note_range(
199 source->model()->lowest_note(),
200 source->model()->highest_note());
202 // Display region contents
203 region_view->set_height(height);
204 region_view->display_model(source->model());
207 void
208 MidiStreamView::display_track (boost::shared_ptr<Track> tr)
210 StreamView::display_track (tr);
212 draw_note_lines();
214 NoteRangeChanged();
217 void
218 MidiStreamView::update_contents_metrics(boost::shared_ptr<Region> r)
220 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(r);
221 if (mr) {
222 mr->midi_source(0)->load_model();
223 _range_dirty = update_data_note_range(
224 mr->model()->lowest_note(),
225 mr->model()->highest_note());
229 bool
230 MidiStreamView::update_data_note_range(uint8_t min, uint8_t max)
232 bool dirty = false;
233 if (min < _data_note_min) {
234 _data_note_min = min;
235 dirty = true;
237 if (max > _data_note_max) {
238 _data_note_max = max;
239 dirty = true;
241 return dirty;
244 void
245 MidiStreamView::redisplay_track ()
247 if (!_trackview.is_midi_track()) {
248 return;
251 list<RegionView*>::iterator i;
253 // Load models if necessary, and find note range of all our contents
254 _range_dirty = false;
255 _data_note_min = 127;
256 _data_note_max = 0;
257 _trackview.track()->playlist()->foreach_region(
258 sigc::mem_fun (*this, &StreamView::update_contents_metrics)
261 // No notes, use default range
262 if (!_range_dirty) {
263 _data_note_min = 60;
264 _data_note_max = 71;
267 // Extend visible range to show newly recorded data, if necessary
268 _lowest_note = std::min(_lowest_note, _data_note_min);
269 _highest_note = std::max(_highest_note, _data_note_max);
271 veto_note_range(_lowest_note, _highest_note);
273 // Flag region views as invalid and disable drawing
274 for (i = region_views.begin(); i != region_views.end(); ++i) {
275 (*i)->set_valid(false);
276 (*i)->enable_display(false);
279 // Add and display region views, and flag them as valid
280 _trackview.track()->playlist()->foreach_region(
281 sigc::hide_return (sigc::mem_fun (*this, &StreamView::add_region_view))
284 // Stack regions by layer, and remove invalid regions
285 layer_regions();
287 // Update note range (not regions which are correct) and draw note lines
288 apply_note_range(_lowest_note, _highest_note, false);
292 void
293 MidiStreamView::update_contents_height ()
295 StreamView::update_contents_height();
296 _note_lines->property_y2() = height;
298 apply_note_range (lowest_note(), highest_note(), true);
301 void
302 MidiStreamView::draw_note_lines()
304 double y;
305 double prev_y = contents_height();
306 uint32_t color;
308 _note_lines->clear();
310 if(height < 140){
311 return;
314 for (int i = lowest_note(); i <= highest_note(); ++i) {
315 y = floor(note_to_y(i));
317 _note_lines->add_line(prev_y, 1.0, ARDOUR_UI::config()->canvasvar_PianoRollBlackOutline.get());
319 switch (i % 12) {
320 case 1:
321 case 3:
322 case 6:
323 case 8:
324 case 10:
325 color = ARDOUR_UI::config()->canvasvar_PianoRollBlack.get();
326 break;
327 default:
328 color = ARDOUR_UI::config()->canvasvar_PianoRollWhite.get();
329 break;
332 if (i == highest_note()) {
333 _note_lines->add_line(y, prev_y - y, color);
334 } else {
335 _note_lines->add_line(y + 1.0, prev_y - y - 1.0, color);
338 prev_y = y;
342 void
343 MidiStreamView::set_note_range(VisibleNoteRange r)
345 if (r == FullRange) {
346 _lowest_note = 0;
347 _highest_note = 127;
348 } else {
349 _lowest_note = _data_note_min;
350 _highest_note = _data_note_max;
353 apply_note_range(_lowest_note, _highest_note, true);
356 void
357 MidiStreamView::apply_note_range(uint8_t lowest, uint8_t highest, bool to_region_views)
359 _highest_note = highest;
360 _lowest_note = lowest;
362 int range = _highest_note - _lowest_note;
363 int pixels_per_note = floor (height/range);
365 /* do not grow note height beyond 10 pixels */
366 if (pixels_per_note > 10) {
368 int available_note_range = floor ((height)/10);
369 int additional_notes = available_note_range - range;
371 /* distribute additional notes to higher and lower ranges, clamp at 0 and 127 */
372 for (int i = 0; i < additional_notes; i++){
374 if (i % 2 && _highest_note < 127){
375 _highest_note++;
377 else if (i % 2) {
378 _lowest_note--;
380 else if (_lowest_note > 0){
381 _lowest_note--;
383 else {
384 _highest_note++;
389 note_range_adjustment.set_page_size(_highest_note - _lowest_note);
390 note_range_adjustment.set_value(_lowest_note);
392 draw_note_lines();
394 if (to_region_views) {
395 for (list<RegionView*>::iterator i = region_views.begin(); i != region_views.end(); ++i) {
396 ((MidiRegionView*)(*i))->apply_note_range(_lowest_note, _highest_note);
400 NoteRangeChanged();
403 void
404 MidiStreamView::update_note_range(uint8_t note_num)
406 assert(note_num <= 127);
407 _data_note_min = min(_data_note_min, note_num);
408 _data_note_max = max(_data_note_max, note_num);
411 void
412 MidiStreamView::setup_rec_box ()
414 // cerr << _trackview.name() << " streamview SRB\n";
416 if (_trackview.session()->transport_rolling()) {
418 if (!rec_active &&
419 _trackview.session()->record_status() == Session::Recording &&
420 _trackview.track()->record_enabled()) {
422 if (Config->get_show_waveforms_while_recording() && rec_regions.size() == rec_rects.size()) {
424 /* add a new region, but don't bother if they set show-waveforms-while-recording mid-record */
426 MidiRegion::SourceList sources;
428 rec_data_ready_connections.drop_connections ();
430 sources.push_back (_trackview.midi_track()->write_source());
432 _trackview.midi_track()->write_source()->ViewDataRangeReady.connect
433 (rec_data_ready_connections,
434 invalidator (*this),
435 ui_bind (&MidiStreamView::rec_data_range_ready, this, _1, _2, boost::weak_ptr<Source>(_trackview.midi_track()->write_source())),
436 gui_context());
438 // handle multi
440 nframes_t start = 0;
441 if (rec_regions.size() > 0) {
442 start = rec_regions.back().first->start()
443 + _trackview.track()->get_captured_frames(rec_regions.size()-1);
446 PropertyList plist;
448 plist.add (ARDOUR::Properties::start, start);
449 plist.add (ARDOUR::Properties::length, 1);
450 plist.add (ARDOUR::Properties::name, string());
451 plist.add (ARDOUR::Properties::layer, 0);
453 boost::shared_ptr<MidiRegion> region (boost::dynamic_pointer_cast<MidiRegion>
454 (RegionFactory::create (sources, plist, false)));
456 assert(region);
457 region->block_property_changes ();
458 region->set_position (_trackview.session()->transport_frame(), this);
459 rec_regions.push_back (make_pair(region, (RegionView*)0));
461 // rec regions are destroyed in setup_rec_box
463 /* we add the region later */
466 /* start a new rec box */
468 boost::shared_ptr<MidiTrack> mt = _trackview.midi_track(); /* we know what it is already */
469 nframes_t frame_pos = mt->current_capture_start ();
470 gdouble xstart = _trackview.editor().frame_to_pixel (frame_pos);
471 gdouble xend;
472 uint32_t fill_color;
474 assert(_trackview.midi_track()->mode() == Normal);
476 xend = xstart;
477 fill_color = ARDOUR_UI::config()->canvasvar_RecordingRect.get();
479 ArdourCanvas::SimpleRect * rec_rect = new Gnome::Canvas::SimpleRect (*_canvas_group);
480 rec_rect->property_x1() = xstart;
481 rec_rect->property_y1() = 1.0;
482 rec_rect->property_x2() = xend;
483 rec_rect->property_y2() = (double) _trackview.current_height() - 1;
484 rec_rect->property_outline_color_rgba() = ARDOUR_UI::config()->canvasvar_RecordingRect.get();
485 rec_rect->property_fill_color_rgba() = fill_color;
486 rec_rect->lower_to_bottom();
488 RecBoxInfo recbox;
489 recbox.rectangle = rec_rect;
490 recbox.start = _trackview.session()->transport_frame();
491 recbox.length = 0;
493 rec_rects.push_back (recbox);
495 screen_update_connection.disconnect();
496 screen_update_connection = ARDOUR_UI::instance()->SuperRapidScreenUpdate.connect (
497 sigc::mem_fun (*this, &MidiStreamView::update_rec_box));
498 rec_updating = true;
499 rec_active = true;
501 } else if (rec_active &&
502 (_trackview.session()->record_status() != Session::Recording ||
503 !_trackview.track()->record_enabled())) {
504 screen_update_connection.disconnect();
505 rec_active = false;
506 rec_updating = false;
509 } else {
511 // cerr << "\tNOT rolling, rec_rects = " << rec_rects.size() << " rec_regions = " << rec_regions.size() << endl;
513 if (!rec_rects.empty() || !rec_regions.empty()) {
515 /* disconnect rapid update */
516 screen_update_connection.disconnect();
517 rec_data_ready_connections.drop_connections ();
519 rec_updating = false;
520 rec_active = false;
522 /* remove temp regions */
524 for (list<pair<boost::shared_ptr<Region>,RegionView*> >::iterator iter = rec_regions.begin(); iter != rec_regions.end();) {
525 list<pair<boost::shared_ptr<Region>,RegionView*> >::iterator tmp;
527 tmp = iter;
528 ++tmp;
530 (*iter).first->drop_references ();
532 iter = tmp;
535 rec_regions.clear();
537 // cerr << "\tclear " << rec_rects.size() << " rec rects\n";
539 /* transport stopped, clear boxes */
540 for (vector<RecBoxInfo>::iterator iter=rec_rects.begin(); iter != rec_rects.end(); ++iter) {
541 RecBoxInfo &rect = (*iter);
542 delete rect.rectangle;
545 rec_rects.clear();
551 void
552 MidiStreamView::update_rec_regions (boost::shared_ptr<MidiModel> data, nframes_t start, nframes_t dur)
554 ENSURE_GUI_THREAD (*this, &MidiStreamView::update_rec_regions, data, start, dur)
556 if (Config->get_show_waveforms_while_recording ()) {
558 uint32_t n = 0;
559 bool update_range = false;
561 for (list<pair<boost::shared_ptr<Region>,RegionView*> >::iterator iter = rec_regions.begin();
562 iter != rec_regions.end(); n++) {
564 list<pair<boost::shared_ptr<Region>,RegionView*> >::iterator tmp = iter;
565 ++tmp;
567 if (!canvas_item_visible (rec_rects[n].rectangle)) {
568 /* rect already hidden, this region is done */
569 iter = tmp;
570 continue;
573 boost::shared_ptr<MidiRegion> region = boost::dynamic_pointer_cast<MidiRegion>(iter->first);
574 if (!region) {
575 iter = tmp;
576 continue;
579 nframes_t origlen = region->length();
581 if (region == rec_regions.back().first && rec_active) {
583 if (start >= region->midi_source(0)->timeline_position()) {
585 nframes_t nlen = start + dur - region->position();
587 if (nlen != region->length()) {
589 region->suspend_property_changes ();
590 region->set_position (_trackview.track()->get_capture_start_frame(n), this);
591 region->set_length (start + dur - region->position(), this);
592 region->resume_property_changes ();
594 if (origlen == 1) {
595 /* our special initial length */
596 iter->second = add_region_view_internal (region, false);
597 ((MidiRegionView*)iter->second)->begin_write();
600 /* also update rect */
601 ArdourCanvas::SimpleRect * rect = rec_rects[n].rectangle;
602 gdouble xend = _trackview.editor().frame_to_pixel (region->position() + region->length());
603 rect->property_x2() = xend;
605 ARDOUR::BeatsFramesConverter tconv(_trackview.session()->tempo_map(), region->position());
606 const MidiModel::TimeType start_beats = tconv.from(start);
608 /* draw events */
609 MidiRegionView* mrv = (MidiRegionView*)iter->second;
611 for (MidiModel::Notes::const_iterator i = data->note_lower_bound(start_beats);
612 i != data->notes().end(); ++i) {
614 const boost::shared_ptr<MidiRegionView::NoteType>& note = *i;
616 nframes_t note_start_frames = tconv.to(note->time());
617 nframes_t note_end_frames = tconv.to(note->end_time());
619 if (note->length() > 0 && note_end_frames + region->position() > start)
620 mrv->resolve_note(note->note(), note_end_frames);
622 if (note_start_frames + region->position() < start) {
623 continue;
626 if (note_start_frames + region->position() > start + dur) {
627 break;
630 if (note->note() < _lowest_note) {
631 _lowest_note = note->note();
632 update_range = true;
633 } else if (note->note() > _highest_note) {
634 _highest_note = note->note();
635 update_range = true;
638 mrv->add_note (note, !update_range);
641 mrv->extend_active_notes();
645 } else {
647 nframes_t nlen = _trackview.track()->get_captured_frames(n);
649 if (nlen != region->length()) {
651 if (region->source_length(0) >= region->position() + nlen) {
653 region->suspend_property_changes ();
654 region->set_position (_trackview.track()->get_capture_start_frame(n), this);
655 region->set_length (nlen, this);
656 region->resume_property_changes ();
658 if (origlen == 1) {
659 /* our special initial length */
660 iter->second = add_region_view_internal (region, false);
663 /* also hide rect */
664 ArdourCanvas::Item * rect = rec_rects[n].rectangle;
665 rect->hide();
671 iter = tmp;
674 if (update_range)
675 update_contents_height();
679 void
680 MidiStreamView::rec_data_range_ready (nframes_t start, nframes_t cnt, boost::weak_ptr<Source> weak_src)
682 // this is called from the butler thread for now
684 ENSURE_GUI_THREAD (*this, &MidiStreamView::rec_data_range_ready, start, cnt, weak_src)
686 boost::shared_ptr<SMFSource> src (boost::dynamic_pointer_cast<SMFSource>(weak_src.lock()));
688 if (!src) {
689 return;
692 if (start + cnt > last_rec_data_frame) {
693 last_rec_data_frame = start + cnt;
696 this->update_rec_regions (src->model(), start, cnt);
699 void
700 MidiStreamView::color_handler ()
702 if (_trackview.is_midi_track()) {
703 canvas_rect->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_MidiTrackBase.get();
704 } else {
705 canvas_rect->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_MidiBusBase.get();;
709 void
710 MidiStreamView::note_range_adjustment_changed()
712 double sum = note_range_adjustment.get_value() + note_range_adjustment.get_page_size();
713 int lowest = (int) floor(note_range_adjustment.get_value());
714 int highest;
716 if (sum == _range_sum_cache) {
717 //cerr << "cached" << endl;
718 highest = (int) floor(sum);
719 } else {
720 //cerr << "recalc" << endl;
721 highest = lowest + (int) floor(note_range_adjustment.get_page_size());
722 _range_sum_cache = sum;
725 if (lowest == _lowest_note && highest == _highest_note) {
726 return;
729 //cerr << "note range adjustment changed: " << lowest << " " << highest << endl;
730 //cerr << " val=" << v_zoom_adjustment.get_value() << " page=" << v_zoom_adjustment.get_page_size() << " sum=" << v_zoom_adjustment.get_value() + v_zoom_adjustment.get_page_size() << endl;
732 _lowest_note = lowest;
733 _highest_note = highest;
734 apply_note_range(lowest, highest, true);