- boost::shared_ptr<MidiRegion> region = boost::dynamic_pointer_cast<MidiRegion>(r);
- if (!region)
- return -1;
-
- // FIXME: how to make a whole file region if it isn't?
- //assert(region->whole_file());
-
- boost::shared_ptr<MidiSource> src = region->midi_source(0);
- src->load_model();
-
- boost::shared_ptr<MidiModel> model = src->model();
-
- // FIXME: Model really needs to be switched to beat time (double) ASAP
-
- const Tempo& t = session.tempo_map().tempo_at(r->start());
- const Meter& m = session.tempo_map().meter_at(r->start());
-
- double q_frames = _q * (m.frames_per_bar(t, session.frame_rate()) / (double)m.beats_per_bar());
-
- for (MidiModel::Notes::iterator i = model->notes().begin(); i != model->notes().end(); ++i) {
- const double new_time = lrint((*i)->time() / q_frames) * q_frames;
- double new_dur = lrint((*i)->duration() / q_frames) * q_frames;
- if (new_dur == 0.0)
- new_dur = q_frames;
-
- (*i)->set_time(new_time);
- (*i)->set_duration(new_dur);
- }
+ /* Calculate offset from start of model to next closest quantize step,
+ to quantize relative to actual session beats (etc.) rather than from the
+ start of the model.
+ */
+ const double round_pos = round(position / _start_grid) * _start_grid;
+ const double offset = round_pos - position;
+
+ bool even;
+ MidiModel::NoteDiffCommand* cmd = new MidiModel::NoteDiffCommand (model, "quantize");
+
+ for (std::vector<Evoral::Sequence<Evoral::MusicalTime>::Notes>::iterator s = seqs.begin(); s != seqs.end(); ++s) {
+
+ even = false;
+
+ /* TODO 'swing' probably requires a 2nd iteration:
+ * first quantize notes to the grid, then apply beat shift
+ */
+ for (Evoral::Sequence<MidiModel::TimeType>::Notes::iterator i = (*s).begin(); i != (*s).end(); ++i) {
+
+ double new_start = round (((*i)->time() - offset) / _start_grid) * _start_grid + offset;
+ double new_end = round (((*i)->end_time() - offset) / _end_grid) * _end_grid + offset;
+
+ if (_swing > 0.0 && !even) {
+
+ double next_grid = new_start + _start_grid;
+
+ /* find a spot 2/3 (* swing factor) of the way between the grid point
+ we would put this note at, and the nominal position of the next note.
+ */
+
+ new_start = new_start + (2.0/3.0 * _swing * (next_grid - new_start));
+ new_end = new_end + (2.0/3.0 * _swing * (next_grid - new_start));