+ return pos;
+}
+
+Command*
+Quantize::operator () (boost::shared_ptr<MidiModel> model,
+ Evoral::Beats position,
+ std::vector<Evoral::Sequence<Evoral::Beats>::Notes>& seqs)
+{
+ /* TODO: Rewrite this to be precise with fixed point? */
+
+ /* 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.to_double() / _start_grid) * _start_grid;
+ const double offset = round_pos - position.to_double();
+
+ MidiModel::NoteDiffCommand* cmd = new MidiModel::NoteDiffCommand (model, "quantize");
+
+ for (std::vector<Evoral::Sequence<Evoral::Beats>::Notes>::iterator s = seqs.begin(); s != seqs.end(); ++s) {
+
+ for (Evoral::Sequence<MidiModel::TimeType>::Notes::iterator i = (*s).begin(); i != (*s).end(); ++i) {
+
+ /* compute new start + end points WITHOUT the offset
+ * caused by the start of the model (see above).
+ *
+ * these versions of new_start and new_end are
+ * guaranteed to precisely align with the quantize grid(s).
+ */
+
+ double new_start = round (((*i)->time().to_double() - offset) / _start_grid) * _start_grid;
+ double new_end = round (((*i)->end_time().to_double() - offset) / _end_grid) * _end_grid;
+
+ if (_swing) {
+
+ new_start = swing_position (new_start, _start_grid, _swing, offset);
+ new_end = swing_position (new_end, _end_grid, _swing, offset);
+
+ } else {
+
+ /* now correct for start-of-model offset */
+
+ new_start += offset;
+ new_end += offset;
+ }
+
+ double delta = new_start - (*i)->time().to_double();
+
+
+ if (fabs (delta) >= _threshold) {
+ if (_snap_start) {
+ delta *= _strength;
+ cmd->change ((*i), MidiModel::NoteDiffCommand::StartTime,
+ (*i)->time() + delta);
+ }
+ }
+
+ if (_snap_end) {
+ delta = new_end - (*i)->end_time().to_double();
+
+ if (fabs (delta) >= _threshold) {
+ Evoral::Beats new_dur(new_end - new_start);
+
+ if (!new_dur) {
+ new_dur = Evoral::Beats(_end_grid);
+ }
+
+ cmd->change ((*i), MidiModel::NoteDiffCommand::Length, new_dur);
+ }
+ }
+ }
+ }