This file is indexed.

/usr/include/ableton/link/Controller.hpp is in ableton-link-dev 1.0.0+dfsg-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/* Copyright 2016, Ableton AG, Berlin. All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  If you would like to incorporate Link into a proprietary software application,
 *  please contact <link-devs@ableton.com>.
 */

#pragma once

#include <ableton/discovery/Service.hpp>
#include <ableton/link/ClientSessionTimelines.hpp>
#include <ableton/link/Gateway.hpp>
#include <ableton/link/GhostXForm.hpp>
#include <ableton/link/NodeState.hpp>
#include <ableton/link/Peers.hpp>
#include <ableton/link/Sessions.hpp>
#include <mutex>

namespace ableton
{
namespace link
{
namespace detail
{

template <typename Clock>
GhostXForm initXForm(const Clock& clock)
{
  // Make the current time map to a ghost time of 0 with ghost time
  // increasing at the same rate as clock time
  return {1.0, -clock.micros()};
}

// The timespan in which local modifications to the timeline will be
// preferred over any modifications coming from the network.
const auto kLocalModGracePeriod = std::chrono::seconds(1);

} // namespace detail

// function types corresponding to the Controller callback type params
using PeerCountCallback = std::function<void(std::size_t)>;
using TempoCallback = std::function<void(ableton::link::Tempo)>;

// The main Link controller
template <typename PeerCountCallback,
  typename TempoCallback,
  typename Clock,
  typename IoContext>
class Controller
{
public:
  using Ticks = typename Clock::Ticks;

  Controller(Tempo tempo,
    PeerCountCallback peerCallback,
    TempoCallback tempoCallback,
    Clock clock,
    util::Injected<IoContext> io)
    : mTempoCallback(std::move(tempoCallback))
    , mClock(std::move(clock))
    , mNodeId(NodeId::random())
    , mSessionId(mNodeId)
    , mGhostXForm(detail::initXForm(mClock))
    , mSessionTimeline(clampTempo({tempo, Beats{0.}, std::chrono::microseconds{0}}))
    , mClientTimeline({mSessionTimeline.tempo, Beats{0.},
        mGhostXForm.ghostToHost(std::chrono::microseconds{0})})
    , mRtClientTimeline(mClientTimeline)
    , mRtClientTimelineTimestamp(0)
    , mSessionPeerCounter(*this, std::move(peerCallback))
    , mEnabled(false)
    , mIo(std::move(io))
    , mRealtimeIo(util::injectRef(*mIo))
    , mPeers(util::injectRef(*mIo),
        std::ref(mSessionPeerCounter),
        SessionTimelineCallback{*this})
    , mSessions({mSessionId, mSessionTimeline, {mGhostXForm, mClock.micros()}},
        util::injectRef(mPeers),
        MeasurePeer{*this},
        JoinSessionCallback{*this},
        util::injectRef(*mIo),
        mClock)
    , mDiscovery(
        std::make_pair(NodeState{mNodeId, mSessionId, mSessionTimeline}, mGhostXForm),
        GatewayFactory{*this},
        util::injectVal(mIo->clone(UdpSendExceptionHandler{*this})))
  {
  }

  Controller(const Controller&) = delete;
  Controller(Controller&&) = delete;

  Controller& operator=(const Controller&) = delete;
  Controller& operator=(Controller&&) = delete;

  void enable(const bool bEnable)
  {
    const bool bWasEnabled = mEnabled.exchange(bEnable);
    if (bWasEnabled != bEnable)
    {
      mRealtimeIo.async([this, bEnable] {
        if (bEnable)
        {
          // Always reset when first enabling to avoid hijacking
          // tempo in existing sessions
          resetState();
        }
        mDiscovery.enable(bEnable);
      });
    }
  }

  bool isEnabled() const
  {
    return mEnabled;
  }

  std::size_t numPeers() const
  {
    return mSessionPeerCounter.mSessionPeerCount;
  }

  // Get the current Link timeline. Thread-safe but may block, so
  // it cannot be used from audio thread.
  Timeline timeline() const
  {
    std::lock_guard<std::mutex> lock(mClientTimelineGuard);
    return mClientTimeline;
  }

  // Set the timeline to be used, starting at the given
  // time. Thread-safe but may block, so it cannot be used from audio thread.
  void setTimeline(Timeline newTimeline, const std::chrono::microseconds atTime)
  {
    newTimeline = clampTempo(newTimeline);
    {
      std::lock_guard<std::mutex> lock(mClientTimelineGuard);
      mClientTimeline = newTimeline;
    }
    mIo->async([this, newTimeline, atTime] {
      handleTimelineFromClient(updateSessionTimelineFromClient(
        mSessionTimeline, newTimeline, atTime, mGhostXForm));
    });
  }

  // Non-blocking timeline access for a realtime context. NOT
  // thread-safe. Must not be called from multiple threads
  // concurrently and must not be called concurrently with setTimelineRtSafe.
  Timeline timelineRtSafe() const
  {
    // Respect the session timing guard but don't block on it. If we
    // can't access it because it's being modified we fall back to our
    // cached version of the timeline.
    const auto now = mClock.micros();
    if (now - mRtClientTimelineTimestamp > detail::kLocalModGracePeriod
        && mSessionTimingGuard.try_lock())
    {
      const auto clientTimeline = updateClientTimelineFromSession(
        mRtClientTimeline, mSessionTimeline, now, mGhostXForm);

      mSessionTimingGuard.unlock();

      if (clientTimeline != mRtClientTimeline)
      {
        mRtClientTimeline = clientTimeline;
      }
    }

    return mRtClientTimeline;
  }

  // should only be called from the audio thread
  void setTimelineRtSafe(Timeline newTimeline, const std::chrono::microseconds atTime)
  {
    newTimeline = clampTempo(newTimeline);
    // Cache the new timeline for serving back to the client
    mRtClientTimeline = newTimeline;
    mRtClientTimelineTimestamp = mClock.micros();

    // Update the session timeline from the new client timeline
    mRealtimeIo.async([this, newTimeline, atTime] {
      // Synchronize with the non-rt version of the client timeline
      {
        std::lock_guard<std::mutex> lock(mClientTimelineGuard);
        mClientTimeline = newTimeline;
      }
      handleTimelineFromClient(updateSessionTimelineFromClient(
        mSessionTimeline, newTimeline, atTime, mGhostXForm));
    });
  }

private:
  void updateSessionTiming(const Timeline newTimeline, const GhostXForm newXForm)
  {
    const auto oldTimeline = mSessionTimeline;
    const auto oldXForm = mGhostXForm;

    if (oldTimeline != newTimeline || oldXForm != newXForm)
    {
      {
        std::lock_guard<std::mutex> lock(mSessionTimingGuard);
        mSessionTimeline = newTimeline;
        mGhostXForm = newXForm;
      }

      // Update the client timeline based on the new session timing data
      {
        std::lock_guard<std::mutex> lock(mClientTimelineGuard);
        mClientTimeline = updateClientTimelineFromSession(
          mClientTimeline, mSessionTimeline, mClock.micros(), mGhostXForm);
      }

      // Push the change to the discovery service
      mDiscovery.updateNodeState(
        std::make_pair(NodeState{mNodeId, mSessionId, newTimeline}, newXForm));

      if (oldTimeline.tempo != newTimeline.tempo)
      {
        mTempoCallback(newTimeline.tempo);
      }
    }
  }

  void handleTimelineFromClient(Timeline tl)
  {
    mSessions.resetTimeline(tl);
    mPeers.setSessionTimeline(mSessionId, tl);
    updateSessionTiming(std::move(tl), mGhostXForm);
  }

  void handleTimelineFromSession(SessionId id, Timeline timeline)
  {
    debug(mIo->log()) << "Received timeline with tempo: " << timeline.tempo.bpm()
                      << " for session: " << id;
    updateSessionTiming(
      mSessions.sawSessionTimeline(std::move(id), std::move(timeline)), mGhostXForm);
  }

  void joinSession(const Session& session)
  {
    const bool sessionIdChanged = mSessionId != session.sessionId;
    mSessionId = session.sessionId;
    updateSessionTiming(session.timeline, session.measurement.xform);

    if (sessionIdChanged)
    {
      debug(mIo->log()) << "Joining session " << session.sessionId << " with tempo "
                        << session.timeline.tempo.bpm();
      mSessionPeerCounter();
    }
  }

  void resetState()
  {
    mNodeId = NodeId::random();
    mSessionId = mNodeId;

    const auto xform = detail::initXForm(mClock);
    const auto hostTime = -xform.intercept;
    // When creating the new timeline, make it continuous by finding
    // the beat on the old session timeline corresponding to the
    // current host time and mapping it to the new ghost time
    // representation of the current host time.
    const auto newTl = Timeline{mSessionTimeline.tempo,
      mSessionTimeline.toBeats(mGhostXForm.hostToGhost(hostTime)),
      xform.hostToGhost(hostTime)};

    updateSessionTiming(newTl, xform);

    mSessions.resetSession({mNodeId, newTl, {xform, hostTime}});
    mPeers.resetPeers();
  }

  struct SessionTimelineCallback
  {
    void operator()(SessionId id, Timeline timeline)
    {
      mController.handleTimelineFromSession(std::move(id), std::move(timeline));
    }

    Controller& mController;
  };

  struct SessionPeerCounter
  {
    SessionPeerCounter(Controller& controller, PeerCountCallback callback)
      : mController(controller)
      , mCallback(std::move(callback))
      , mSessionPeerCount(0)
    {
    }

    void operator()()
    {
      const auto count =
        mController.mPeers.uniqueSessionPeerCount(mController.mSessionId);
      const auto oldCount = mSessionPeerCount.exchange(count);
      if (oldCount != count)
      {
        if (count == 0)
        {
          // When the count goes down to zero, completely reset the
          // state, effectively founding a new session
          mController.resetState();
        }
        mCallback(count);
      }
    }

    Controller& mController;
    PeerCountCallback mCallback;
    std::atomic<std::size_t> mSessionPeerCount;
  };

  struct MeasurePeer
  {
    template <typename Peer, typename Handler>
    void operator()(Peer peer, Handler handler)
    {
      using It = typename Discovery::ServicePeerGateways::GatewayMap::iterator;
      using ValueType = typename Discovery::ServicePeerGateways::GatewayMap::value_type;
      mController.mDiscovery.withGatewaysAsync([peer, handler](It begin, const It end) {
        const auto addr = peer.second;
        const auto it = std::find_if(
          begin, end, [&addr](const ValueType& vt) { return vt.first == addr; });
        if (it != end)
        {
          it->second->measurePeer(std::move(peer.first), std::move(handler));
        }
        else
        {
          // invoke the handler with an empty result if we couldn't
          // find the peer's gateway
          handler(GhostXForm{});
        }
      });
    }

    Controller& mController;
  };

  struct JoinSessionCallback
  {
    void operator()(Session session)
    {
      mController.joinSession(std::move(session));
    }

    Controller& mController;
  };

  using IoType = typename util::Injected<IoContext>::type;

  using ControllerPeers =
    Peers<IoType&, std::reference_wrapper<SessionPeerCounter>, SessionTimelineCallback>;

  using ControllerGateway =
    Gateway<typename ControllerPeers::GatewayObserver, Clock, IoType&>;
  using GatewayPtr = std::shared_ptr<ControllerGateway>;

  struct GatewayFactory
  {
    GatewayPtr operator()(std::pair<NodeState, GhostXForm> state,
      util::Injected<IoType&> io,
      const asio::ip::address& addr)
    {
      if (addr.is_v4())
      {
        return GatewayPtr{new ControllerGateway{std::move(io), addr.to_v4(),
          util::injectVal(makeGatewayObserver(mController.mPeers, addr)),
          std::move(state.first), std::move(state.second), mController.mClock}};
      }
      else
      {
        throw std::runtime_error("Could not create peer gateway on non-ipV4 address");
      }
    }

    Controller& mController;
  };

  struct UdpSendExceptionHandler
  {
    using Exception = discovery::UdpSendException;

    void operator()(const Exception& exception)
    {
      mController.mDiscovery.repairGateway(exception.interfaceAddr);
    }

    Controller& mController;
  };

  TempoCallback mTempoCallback;
  Clock mClock;
  NodeId mNodeId;
  SessionId mSessionId;

  // Mutex that controls access to mGhostXForm and mSessionTimeline
  mutable std::mutex mSessionTimingGuard;
  GhostXForm mGhostXForm;
  Timeline mSessionTimeline;

  mutable std::mutex mClientTimelineGuard;
  Timeline mClientTimeline;

  mutable Timeline mRtClientTimeline;
  std::chrono::microseconds mRtClientTimelineTimestamp;

  SessionPeerCounter mSessionPeerCounter;

  std::atomic<bool> mEnabled;

  util::Injected<IoContext> mIo;
  // A realtime facade over the provided IoContext. This should only
  // be used by realtime code, non-realtime code should use mIo.
  typename IoType::template RealTimeContext<IoType&> mRealtimeIo;

  ControllerPeers mPeers;

  using ControllerSessions = Sessions<ControllerPeers&,
    MeasurePeer,
    JoinSessionCallback,
    typename util::Injected<IoContext>::type&,
    Clock>;
  ControllerSessions mSessions;

  using Discovery =
    discovery::Service<std::pair<NodeState, GhostXForm>, GatewayFactory, IoContext>;
  Discovery mDiscovery;
};

} // namespace link
} // namespace ableton