libcrtc
crtc.h
Go to the documentation of this file.
1 
2 /*
3 * The MIT License (MIT)
4 *
5 * Copyright (c) 2017 vmolsa <ville.molsa@gmail.com> (http://github.com/vmolsa)
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 *
25 */
26 
43 #ifndef INCLUDE_CRTC_H_
44 #define INCLUDE_CRTC_H_
45 
46 #include <utility>
47 #include <memory>
48 #include <vector>
49 #include <string>
50 
51 #ifdef CRTC_OS_WIN
52  #define CRTC_EXPORT __declspec(dllexport)
53  #define CRTC_NO_EXPORT __declspec(dllimport)
54 #else
55  #define CRTC_EXPORT __attribute__((visibility("default")))
56  #define CRTC_NO_EXPORT __attribute__((visibility("hidden")))
57 #endif
58 
59 #ifndef CRTC_STATIC
60 #define CRTC_STATIC(className) \
61  explicit className() = delete; \
62  className(const className&) = delete; \
63  className& operator=(const className&) = delete;
64 #endif
65 
66 #ifndef CRTC_PRIVATE
67 #define CRTC_PRIVATE(className) \
68  className(const className&) = delete; \
69  className& operator=(const className&) = delete;
70 #endif
71 
72 namespace crtc {
73 
74 class CRTC_EXPORT Atomic {
75  CRTC_STATIC(Atomic);
76 
77  public:
78  static int Increment(volatile int *arg);
79  static int Decrement(volatile int *arg);
80  static int AcquireLoad(volatile int *arg);
81 };
82 
83 class CRTC_EXPORT Time {
84  CRTC_STATIC(Time);
85  public:
86  static int64_t Now(); // returns current time in milliseconds
87  static int64_t Diff(int64_t begin, int64_t end = Now()); // returns milliseconds
88  static double Since(int64_t begin, int64_t end = Now()); // returns seconds
89 };
90 
92 
93 template <class T> class Let {
94  public:
95  template <typename... Args> inline static Let<T> New(Args&&... args) {
96  return Let<T>(new Constructor<Args...>(std::forward<Args>(args)...));
97  }
98 
99  inline static Let<T> Empty() {
100  return Let<T>();
101  }
102 
103  inline explicit Let() : _ptr(nullptr) { }
104 
105  inline ~Let() {
106  Let::RemoveRef();
107  }
108 
109  inline Let(T* ptr) : _ptr(ptr) {
110  Let::AddRef();
111  }
112 
113  inline Let(const Let<T> &src) : _ptr(*src) {
114  Let::AddRef();
115  }
116 
117  template <class S> inline Let(Let<S> src) : _ptr(reinterpret_cast<T*>(*src)) {
118  Let::AddRef();
119  }
120 
121  inline Let<T> &operator=(T* src) {
122  if (src) { src->AddRef(); }
123 
124  Let::RemoveRef();
125 
126  _ptr = src;
127  return *this;
128  }
129 
130  template <class S> inline static Let<T> Cast(S* src) {
131  return Let<T>(static_cast<T*>(src));
132  }
133 
134  template <class S> inline static Let<T> Cast(const Let<S> &src) {
135  return Let<T>(reinterpret_cast<T*>(*src));
136  }
137 
138  inline Let<T> &operator=(const Let<T> &src) { return *this = src._ptr; }
139  inline bool IsEmpty() const { return (_ptr == nullptr); }
140  inline operator T* () const { return _ptr; }
141  inline T* operator*() const { return _ptr; }
142  inline T* operator->() const { return _ptr; }
143 
144  inline void Dispose() const {
145  if (_ptr) {
146  T* ptr = _ptr;
147  _ptr = nullptr;
148 
149  ptr->RemoveRef();
150  }
151  }
152 
153  template <class R> inline R& operator[](const size_t index) {
154  return _ptr[index];
155  }
156 
157  template <class R> inline const R& operator[](const size_t index) const {
158  return _ptr[index];
159  }
160 
161  private:
162  template <typename... Args> class Constructor : public T {
163  public:
164  explicit Constructor(Args&&... args) : T(std::forward<Args>(args)...), reference_count(0) { }
165 
166  protected:
167  inline virtual int AddRef() const {
168  return Atomic::Increment(&reference_count);
169  }
170 
171  inline virtual int RemoveRef() const {
172  int res = Atomic::Decrement(&reference_count);
173 
174  if (!res) {
175  delete this;
176  }
177 
178  return res;
179  }
180 
181  inline virtual int RefCount() const {
182  return Atomic::AcquireLoad(&reference_count);
183  }
184 
185  virtual ~Constructor() { }
186 
187  private:
188  mutable volatile int reference_count = 0;
189  };
190 
191  inline void AddRef() const {
192  if (_ptr) { _ptr->AddRef(); }
193  }
194 
195  inline void RemoveRef() const {
196  if (_ptr) { _ptr->RemoveRef(); }
197  }
198 
199  protected:
200  mutable T* _ptr;
201 };
202 
203 class CRTC_EXPORT Reference {
204  template <class T> friend class Let;
205 
206  protected:
207  virtual ~Reference() { }
208 
209  virtual int AddRef() const = 0;
210  virtual int RemoveRef() const = 0;
211  virtual int RefCount() const = 0;
212 };
213 
214 /*
215  * class Example {
216  * public:
217  * static int Foo(const char *msg) {
218  * printf("%s\n", msg);
219  * return 1337;
220  * }
221  *
222  * int Bar(const char *msg) {
223  * printf("%s\n", msg);
224  * return 1337;
225  * }
226  * };
227  *
228  * Example ex;
229  *
230  * Functor<int(const char *msg)> ex1(&Example::Foo);
231  * Functor<int(const char *msg)> ex2 = Functor<int(const char *msg)>(&ex, &Example::Bar);
232  * Functor<int(const char *msg)> ex3 = [](const char *msg) {
233  * printf("%s\n", msg);
234  * return 1337;
235  * };
236  *
237  * int res1 = ex1("Hello World1!");
238  * int res2 = ex2("Hello World2!");
239  * int res3 = ex3("Hello World3!");
240  *
241  * printf("Ex1: %s\n", (res1 == 1337) ? "OK" : "FAILED");
242  * printf("Ex2: %s\n", (res2 == 1337) ? "OK" : "FAILED");
243  * printf("Ex3: %s\n", (res3 == 1337) ? "OK" : "FAILED");
244  *
245  */
246 
247 template <typename T> class CRTC_EXPORT Functor;
248 template <typename R, typename... Args> class CRTC_EXPORT Functor<R(Args...)> {
249  public:
250  enum Flags {
251  kNone = 1 << 1,
252  kOnce = 1 << 2,
253  };
254 
255  explicit Functor() : _flags(kNone) { }
256  virtual ~Functor() { }
257 
258  Functor(const Functor<R(Args...)> &functor, const Functor<void()> &notifier) : _flags(kOnce), _callback(Let<VerifyWrap<void>>::New(functor, notifier)) { }
259  Functor(const Functor<R(Args...)> &functor) : _flags(functor._flags), _callback(functor._callback) { }
260  Functor(Functor&& functor) : _flags(functor._flags), _callback(std::move(functor._callback)) { }
261 
262  template <class T> inline Functor(const T& functor, Flags flags = kNone) : _flags(flags), _callback(Let<Wrap<T> >::New(functor)) { }
263  template <class Object, class Method> inline Functor(Object *object, const Method& method, Flags flags = kNone) : _flags(flags), _callback(Let<ObjectWrap<Object, Method> >::New(object, method)) { }
264  template <class Object, class Method> inline Functor(const Let<Object> &object, const Method& method, Flags flags = kNone) : _flags(flags), _callback(Let<LetWrap<Object, Method> >::New(object, method)) { }
265 
266  inline R operator()(Args... args) const {
267  if (!_callback.IsEmpty()) {
268  Let<Callback> callback = _callback;
269 
270  if (_flags & kOnce) {
271  _callback.Dispose();
272  }
273 
274  return callback->Call(std::move(args)...);
275  }
276 
277  return R();
278  }
279 
280  inline Functor<R(Args...)>& operator=(const Functor<R(Args...)> &functor) {
281  _flags = functor._flags;
282  _callback = std::move(functor._callback);
283  return *this;
284  }
285 
286  inline bool IsEmpty() const {
287  return _callback.IsEmpty();
288  }
289 
290  operator bool() const {
291  return !_callback.IsEmpty();
292  }
293 
294  inline void Dispose() const {
295  _callback.Dispose();
296  }
297 
298  private:
299  class Callback : virtual public Reference {
300  CRTC_PRIVATE(Callback);
301  friend class Let<Callback>;
302 
303  public:
304  virtual R Call(Args&&... args) const = 0;
305 
306  protected:
307  explicit Callback() { }
308  ~Callback() override { }
309  };
310 
311  template <class T> class Wrap : public Callback {
312  CRTC_PRIVATE(Wrap);
313  friend class Let<Wrap>;
314 
315  public:
316  inline R Call(Args&&... args) const override {
317  return _functor(std::forward<Args>(args)...);
318  }
319 
320  protected:
321  explicit Wrap(const T& functor) : _functor(functor) { }
322  ~Wrap() override { }
323 
324  T _functor;
325  };
326 
327  template <class Object, class Method> class ObjectWrap : public Callback {
328  CRTC_PRIVATE(ObjectWrap);
329  friend class Let<ObjectWrap>;
330 
331  public:
332  inline R Call(Args&&... args) const override {
333  if (_object) {
334  return (_object->*_method)(std::forward<Args>(args)...);
335  }
336 
337  return R();
338  }
339 
340  protected:
341  explicit ObjectWrap(Object *object, const Method &method) : _object(object), _method(method) { }
342  ~ObjectWrap() override { }
343 
344  Object* _object;
345  Method _method;
346  };
347 
348  template <class Object, class Method> class LetWrap : public Callback {
349  CRTC_PRIVATE(LetWrap);
350  friend class Let<LetWrap>;
351 
352  public:
353  inline R Call(Args&&... args) const override {
354  if (!_object.IsEmpty()) {
355  return (_object->*_method)(std::forward<Args>(args)...);
356  }
357 
358  return R();
359  }
360 
361  protected:
362  explicit LetWrap(const Let<Object> &object, const Method &method) : _object(object), _method(method) { }
363  ~LetWrap() override { }
364 
365  Let<Object> _object;
366  Method _method;
367  };
368 
369  template <class Type = void> class VerifyWrap : public Callback {
370  CRTC_PRIVATE(VerifyWrap);
371  friend class Let<VerifyWrap>;
372 
373  public:
374  inline R Call(Args&&... args) const override {
375  _notifier.Dispose();
376  return _functor(std::forward<Args>(args)...);
377  }
378 
379  protected:
380  explicit VerifyWrap(const Functor<R(Args...)> &functor, const Functor<Type()> &notifier) : _functor(functor), _notifier(notifier) { }
381 
382  ~VerifyWrap() override {
383  _notifier();
384  }
385 
386  Functor<R(Args...)> _functor;
387  Functor<Type()> _notifier;
388  };
389 
390  Flags _flags;
391  Let<Callback> _callback;
392 };
393 
394 typedef Functor<void()> Callback;
395 
396 class CRTC_EXPORT Worker : virtual public Reference {
397  CRTC_PRIVATE(Worker);
398  public:
399  static Let<Worker> New(const Callback &runnable = Callback());
400  static Let<Worker> This();
401  protected:
402  explicit Worker() { }
403  ~Worker() override { }
404 };
405 
406 class CRTC_EXPORT RealTimeClock : virtual public Reference {
407  CRTC_PRIVATE(RealTimeClock);
408  public:
409  static Let<RealTimeClock> New(const Callback &runnable = Callback());
410 
411  virtual void Start(uint32_t interval_ms = 0) = 0;
412  virtual void Stop() = 0;
413 
414  protected:
415  explicit RealTimeClock() { }
416  ~RealTimeClock() override { }
417 };
418 
419 class CRTC_EXPORT Async {
420  CRTC_STATIC(Async);
421  public:
422  static void Call(Callback callback, int delay = 0, Let<Worker> worker = Worker::This());
423 };
424 
426 
427 template <typename F, typename... Args> static inline void SetImmediate(F&& func, Args... args) {
428  Functor<void(Args...)> callback(func);
429 
430  Async::Call(Callback([=]() {
431  callback(args...);
432  }, [=]() {
433  callback(args...);
434  }));
435 }
436 
438 
439 template <typename F, typename... Args> static inline void SetTimeout(F&& func, int delay, Args... args) {
440  Functor<void(Args... args)> callback(func);
441 
442  Async::Call(Callback([=]() {
443  callback(args...);
444  }, [=]() {
445  callback(args...);
446  }), (delay > 0) ? delay : 0);
447 }
448 
450 
451 class CRTC_EXPORT Error : virtual public Reference {
452  public:
453  static Let<Error> New(std::string message, std::string fileName = __FILE__, int lineNumber = __LINE__);
454 
455  virtual std::string Message() const = 0;
456  virtual std::string FileName() const = 0;
457  virtual int LineNumber() const = 0;
458 
459  virtual std::string ToString() const = 0;
460 
461  protected:
462  explicit Error() { }
463  ~Error() override { }
464 };
465 
466 typedef Functor<void(const Let<Error> &error)> ErrorCallback;
467 
469 
470 template <typename... Args> class Promise : virtual public Reference {
471  CRTC_PRIVATE(Promise<Args...>);
472  friend class Let<Promise<Args...>>;
473 
474  public:
475  typedef Functor<void(Args...)> FullFilledCallback;
476  typedef Callback FinallyCallback;
477  typedef ErrorCallback RejectedCallback;
478  typedef Functor<void(const FullFilledCallback &resolve, const RejectedCallback &reject)> ExecutorCallback;
479 
480  inline static Let<Promise<Args...>> New(const ExecutorCallback &executor, const Let<Worker> &worker = Worker::This()) {
481  Let<Promise<Args...>> self = Let<Promise<Args...>>::New();
482 
483  RejectedCallback reject([=](const Let<Error> &error) {
484  if (!self.IsEmpty()) {
485  for (const auto &callback: self->_onreject) {
486  callback(error);
487  }
488 
489  for (const auto &callback: self->_onfinally) {
490  callback();
491  }
492 
493  self->_onfinally.clear();
494  self->_onreject.clear();
495  self->_onresolve.clear();
496 
497  self.Dispose();
498  }
499  });
500 
501  RejectedCallback asyncReject([=](const Let<Error> &error) {
502  Async::Call(Callback([=]() {
503  reject(error);
504  }, [=]() {
505  reject(error);
506  }), 0, worker);
507  });
508 
509  FullFilledCallback resolve([=](Args... args) {
510  Async::Call(Callback([=]() {
511  if (!self.IsEmpty()) {
512  for (const auto &callback: self->_onresolve) {
513  callback(std::move(args)...);
514  }
515 
516  for (const auto &callback: self->_onfinally) {
517  callback();
518  }
519 
520  self->_onfinally.clear();
521  self->_onreject.clear();
522  self->_onresolve.clear();
523 
524  self.Dispose();
525  }
526  }, [=]() {
527  asyncReject(Error::New("Reference Lost.", __FILE__, __LINE__));
528  }), 0, worker);
529  }, [=]() {
530  asyncReject(Error::New("Reference Lost.", __FILE__, __LINE__));
531  });
532 
533  if (!executor.IsEmpty()) {
534  executor(resolve, asyncReject);
535  } else {
536  asyncReject(Error::New("Invalid Executor Callback.", __FILE__, __LINE__));
537  }
538 
539  return self;
540  }
541 
542  inline Let<Promise<Args...>> Then(const FullFilledCallback &callback) {
543  _onresolve.push_back(callback);
544  return this;
545  }
546 
547  inline Let<Promise<Args...>> Catch(const RejectedCallback &callback) {
548  _onreject.push_back(callback);
549  return this;
550  }
551 
552  inline Let<Promise<Args...>> Finally(const FinallyCallback &callback) {
553  _onfinally.push_back(callback);
554  return this;
555  }
556 
557  private:
558  std::vector<FullFilledCallback> _onresolve;
559  std::vector<RejectedCallback> _onreject;
560  std::vector<FinallyCallback> _onfinally;
561 
562  protected:
563  explicit Promise() { }
564  ~Promise() override { }
565 };
566 
567 template<> class Promise<void> : public Promise<> { };
568 
570 
571 class CRTC_EXPORT ArrayBuffer : virtual public Reference {
572  CRTC_PRIVATE(ArrayBuffer);
573 
574  public:
575  static Let<ArrayBuffer> New(size_t byteLength = 0);
576  static Let<ArrayBuffer> New(const std::string &data);
577  static Let<ArrayBuffer> New(const uint8_t *data, size_t byteLength = 0);
578 
579  virtual size_t ByteLength() const = 0;
580 
581  virtual Let<ArrayBuffer> Slice(size_t begin = 0, size_t end = 0) const = 0;
582 
583  virtual uint8_t *Data() = 0;
584  virtual const uint8_t *Data() const = 0;
585 
586  virtual std::string ToString() const = 0;
587 
588  protected:
589  explicit ArrayBuffer() { }
590  ~ArrayBuffer() override { }
591 };
592 
594 
595 template <typename T> class CRTC_EXPORT TypedArray {
596  public:
597  explicit TypedArray(size_t length = 0) :
598  TypedArray(ArrayBuffer::New(length * sizeof(T)))
599  { }
600 
601  TypedArray(const T *data, size_t length = 0) :
602  TypedArray(ArrayBuffer::New(data, length * sizeof(T)))
603  { }
604 
605  TypedArray(const TypedArray<T> &typedArray) :
606  _empty(0),
607  _data(typedArray._data),
608  _length(typedArray._length),
609  _byteOffset(typedArray._byteOffset),
610  _byteLength(typedArray._byteLength),
611  _buffer(typedArray._buffer)
612  { }
613 
614  template <typename N> TypedArray(const TypedArray<N> &typedArray) :
615  TypedArray(typedArray.Buffer())
616  { }
617 
618  TypedArray(const Let<ArrayBuffer> &buffer, size_t byteOffset = 0, size_t byteLength = 0) :
619  _empty(0),
620  _data(nullptr),
621  _length(0),
622  _byteOffset(0),
623  _byteLength(0),
624  _buffer(buffer)
625  {
626  if (_buffer.IsEmpty()) {
627  _buffer = ArrayBuffer::New(byteLength - byteOffset);
628  }
629 
630  byteLength = (!byteLength) ? _buffer->ByteLength() : byteLength;
631  byteLength -= byteOffset;
632 
633  if (byteLength && (byteLength % sizeof(T)) == 0) {
634  _data = reinterpret_cast<T*>(buffer->Data() + byteOffset);
635  _byteOffset = byteOffset;
636  _byteLength = byteLength;
637  _length = byteLength / sizeof(T);
638  }
639  }
640 
641  inline size_t Length() const {
642  return _length;
643  }
644 
645  inline size_t ByteOffset() const {
646  return _byteOffset;
647  }
648 
649  inline size_t ByteLength() const {
650  return _byteLength;
651  }
652 
653  inline Let<ArrayBuffer> Buffer() const {
654  return _buffer;
655  }
656 
657  inline Let<ArrayBuffer> Slice(size_t begin = 0, size_t end = 0) const {
658  if (_length) {
659  return _buffer->Slice(begin * sizeof(T), end * sizeof(T));
660  }
661 
662  return ArrayBuffer::New();
663  }
664 
665  inline T *Data() {
666  return (_length) ? _data : nullptr;
667  }
668 
669  inline const T *Data() const {
670  return (_length) ? _data : nullptr;
671  }
672 
673  inline T& Get(const size_t index) {
674  if (index < _length) {
675  return _data[index];
676  }
677 
678  return _empty;
679  }
680 
681  inline const T& Get(const size_t index) const {
682  if (index < _length) {
683  return _data[index];
684  }
685 
686  return TypedArray<T>::empty;
687  }
688 
689  inline void Set(const size_t index, const T &value) {
690  if (index < _length) {
691  _data[index] = index;
692  }
693  }
694 
695  inline T& operator[](const size_t index) {
696  if (index < _length) {
697  return _data[index];
698  }
699 
700  return _empty;
701  }
702 
703  inline const T& operator[](const size_t index) const {
704  if (index < _length) {
705  return _data[index];
706  }
707 
708  return TypedArray<T>::empty;
709  }
710 
711  protected:
712  static const T empty = 0;
713 
714  T _empty;
715  T* _data;
716  size_t _length;
717  size_t _byteOffset;
718  size_t _byteLength;
719  Let<ArrayBuffer> _buffer;
720 };
721 
723 
725 
727 
729 
731 
733 
735 
737 
739 
741 
743 
745 
746 class CRTC_EXPORT Module {
747  CRTC_STATIC(Module);
748 
749  public:
750  static void Init();
751  static bool DispatchEvents(bool kForever = false);
752  static void Dispose();
753 };
754 
755 class CRTC_EXPORT Event : virtual public Reference {
756  CRTC_PRIVATE(Event);
757  friend class Let<Event>;
758 
759  public:
760  static Let<Event> New();
761 
762  protected:
763  explicit Event();
764  ~Event() override;
765 };
766 
768 
769 class MediaStreamTrack : virtual public Reference {
770  CRTC_PRIVATE(MediaStreamTrack);
771 
772  public:
773  enum Type {
774  kAudio,
775  kVideo,
776  };
777 
778  enum State {
779  kLive,
780  kEnded,
781  };
782 
783  virtual bool Enabled() const = 0;
784  virtual bool Muted() const = 0;
785  virtual bool Remote() const = 0;
786  virtual std::string Id() const = 0;
787 
788  virtual Type Kind() const = 0;
789  virtual State ReadyState() const = 0;
790 
792 
793  virtual Let<MediaStreamTrack> Clone() = 0;
794 
795  Callback onstarted;
796  Callback onended;
797  Callback onmute;
798  Callback onunmute;
799 
800  protected:
801  explicit MediaStreamTrack();
802  ~MediaStreamTrack() override;
803 };
804 
805 typedef std::vector<Let<MediaStreamTrack>> MediaStreamTracks;
806 
808 
809 class MediaStream : virtual public Reference {
810  CRTC_PRIVATE(MediaStream);
811 
812  public:
813  virtual std::string Id() const = 0;
814 
816 
817  virtual void AddTrack(const Let<MediaStreamTrack> &track) = 0;
818  virtual void RemoveTrack(const Let<MediaStreamTrack> &track) = 0;
819 
821 
822  virtual Let<MediaStreamTrack> GetTrackById(const std::string &id) const = 0;
823 
824  virtual MediaStreamTracks GetAudioTracks() const = 0;
825  virtual MediaStreamTracks GetVideoTracks() const = 0;
826 
828 
829  virtual Let<MediaStream> Clone() = 0;
830 
831  Functor<void(const Let<MediaStreamTrack> &track)> onaddtrack;
832  Functor<void(const Let<MediaStreamTrack> &track)> onremovetrack;
833 
834  protected:
835  explicit MediaStream();
836  ~MediaStream() override;
837 };
838 
839 typedef std::vector<Let<MediaStream>> MediaStreams;
840 
841 class CRTC_EXPORT AudioBuffer : virtual public ArrayBuffer {
842  CRTC_PRIVATE(AudioBuffer);
843 
844  public:
845  static Let<AudioBuffer> New(int channels = 2, int sampleRate = 44100, int bitsPerSample = 8, int frames = 1);
846  static Let<AudioBuffer> New(const Let<ArrayBuffer> &buffer, int channels = 2, int sampleRate = 44100, int bitsPerSample = 8, int frames = 1);
847 
848  virtual int Channels() const = 0;
849  virtual int SampleRate() const = 0;
850  virtual int BitsPerSample() const = 0;
851  virtual int Frames() const = 0;
852 
853  protected:
854  explicit AudioBuffer() { }
855  ~AudioBuffer() override { }
856 };
857 
858 class CRTC_EXPORT AudioSource : virtual public MediaStream {
859  CRTC_PRIVATE(AudioSource);
860 
861  public:
862  static Let<AudioSource> New();
863 
864  virtual bool IsRunning() const = 0;
865  virtual void Stop() = 0;
866 
867  virtual void Write(const Let<AudioBuffer> &buffer, ErrorCallback callback = ErrorCallback()) = 0;
868 
869  Callback ondrain;
870 
871  protected:
872  explicit AudioSource();
873  ~AudioSource() override;
874 };
875 
876 class CRTC_EXPORT AudioSink : virtual public MediaStreamTrack {
877  CRTC_PRIVATE(AudioSink);
878 
879  public:
880  static Let<AudioSink> New(const Let<MediaStreamTrack> &track);
881 
882  virtual bool IsRunning() const = 0;
883  virtual void Stop() = 0;
884 
885  Functor<void(const Let<AudioBuffer> &buffer)> ondata;
886 
887  protected:
888  explicit AudioSink();
889  ~AudioSink() override;
890 };
891 
892 class CRTC_EXPORT ImageBuffer : public ArrayBuffer {
893  CRTC_PRIVATE(ImageBuffer);
894 
895  public:
896  static Let<ImageBuffer> New(int width, int height);
897  static Let<ImageBuffer> New(const Let<ArrayBuffer> &buffer, int width, int height);
898 
899  static size_t ByteLength(int height, int stride_y, int stride_u, int stride_v);
900  static size_t ByteLength(int width, int height);
901 
902  virtual int Width() const = 0;
903  virtual int Height() const = 0;
904 
905  virtual const uint8_t* DataY() const = 0;
906  virtual const uint8_t* DataU() const = 0;
907  virtual const uint8_t* DataV() const = 0;
908 
909  virtual int StrideY() const = 0;
910  virtual int StrideU() const = 0;
911  virtual int StrideV() const = 0;
912 
913  protected:
914  explicit ImageBuffer() { }
915  ~ImageBuffer() override { }
916 };
917 
918 class CRTC_EXPORT VideoSource : virtual public MediaStream {
919  CRTC_PRIVATE(VideoSource);
920 
921  public:
922  static Let<VideoSource> New(int width = 1280, int height = 720, float fps = 30);
923 
924  virtual bool IsRunning() const = 0;
925  virtual void Stop() = 0;
926 
927  virtual int Width() const = 0;
928  virtual int Height() const = 0;
929  virtual float Fps() const = 0;
930 
931  virtual void Write(const Let<ImageBuffer> &frame, ErrorCallback callback = ErrorCallback()) = 0;
932 
933  Callback ondrain;
934 
935  protected:
936  explicit VideoSource();
937  ~VideoSource() override;
938 };
939 
940 class CRTC_EXPORT VideoSink : virtual public MediaStreamTrack {
941  CRTC_PRIVATE(VideoSink);
942 
943  public:
944  static Let<VideoSink> New(const Let<MediaStreamTrack> &track);
945 
946  virtual bool IsRunning() const = 0;
947  virtual void Stop() = 0;
948 
949  Functor<void(const Let<ImageBuffer> &frame)> ondata;
950 
951  protected:
952  explicit VideoSink();
953  ~VideoSink() override;
954 };
955 
957 
958 class CRTC_EXPORT RTCDataChannel : virtual public Reference {
959  CRTC_PRIVATE(RTCDataChannel);
960 
961  public:
962  typedef Functor<void(const Let<ArrayBuffer> &buffer, bool binary)> MessageCallback;
963 
964  enum State {
965  kConnecting,
966  kOpen,
967  kClosing,
968  kClosed
969  };
970 
972 
973  virtual int Id() = 0;
974 
976 
977  virtual std::string Label() = 0;
978 
980 
981  virtual uint64_t BufferedAmount() = 0;
982 
984 
985  virtual uint64_t BufferedAmountLowThreshold() = 0;
986  virtual void SetBufferedAmountLowThreshold(uint64_t threshold = 0) = 0;
987 
989 
990  virtual uint16_t MaxPacketLifeTime() = 0;
991 
993 
994  virtual uint16_t MaxRetransmits() = 0;
995 
997 
998  virtual bool Negotiated() = 0;
999 
1001 
1002  virtual bool Ordered() = 0;
1003 
1005 
1006  virtual std::string Protocol() = 0;
1007 
1009 
1010  virtual State ReadyState() = 0;
1011 
1013 
1014  virtual void Close() = 0;
1015 
1017 
1018  virtual void Send(const Let<ArrayBuffer> &data, bool binary = true) = 0;
1019 
1021 
1023 
1025 
1026  Callback onclose;
1027 
1029 
1030  ErrorCallback onerror;
1031 
1033 
1034  MessageCallback onmessage;
1035 
1037 
1038  Callback onopen;
1039 
1040  protected:
1041  explicit RTCDataChannel();
1042  ~RTCDataChannel() override;
1043 };
1044 
1046 
1047 class CRTC_EXPORT RTCPeerConnection : virtual public Reference {
1048  CRTC_PRIVATE(RTCPeerConnection);
1049 
1050  public:
1052 
1053  typedef struct RTCDataChannelInit {
1054  RTCDataChannelInit() :
1055  id(-1),
1056  maxPacketLifeTime(-1),
1057  maxRetransmits(-1),
1058  ordered(true),
1059  negotiated(false)
1060  { }
1061 
1062  int id;
1063  int maxPacketLifeTime;
1064  int maxRetransmits;
1065  bool ordered;
1066  bool negotiated;
1067  std::string protocol;
1069 
1071 
1072  typedef struct {
1073  enum RTCSdpType {
1074  kAnswer,
1075  kOffer,
1076  kPranswer,
1077  kRollback,
1078  };
1079 
1080  RTCSdpType type;
1081  std::string sdp;
1083 
1085 
1087  kStable,
1088  kHaveLocalOffer,
1089  kHaveLocalPrAnswer,
1090  kHaveRemoteOffer,
1091  kHaveRemotePrAnswer,
1092  kSignalingClosed,
1093  };
1094 
1096 
1098  kNewGathering,
1099  kGathering,
1100  kComplete
1101  };
1102 
1104 
1106  kNew,
1107  kChecking,
1108  kConnected,
1109  kCompleted,
1110  kFailed,
1111  kDisconnected,
1112  kClosed,
1113  };
1114 
1116 
1118  kBalanced,
1119  kMaxBundle,
1120  kMaxCompat
1121  };
1122 
1124 
1126  kRelay,
1127  kPublic,
1128  kAll
1129  };
1130 
1132 
1134  kNegotiate,
1135  kRequire,
1136  };
1137 
1138  // \sa https://developer.mozilla.org/en/docs/Web/API/RTCIceCandidate
1139 
1140  typedef struct {
1141  std::string candidate;
1142  std::string sdpMid;
1143  uint32_t sdpMLineIndex;
1144  } RTCIceCandidate;
1145 
1147 
1148  typedef struct {
1149  std::string credential;
1150  std::string credentialType;
1151  std::string username;
1152  std::vector<std::string> urls;
1153  } RTCIceServer;
1154 
1155  typedef std::vector<RTCIceServer> RTCIceServers;
1156 
1157  static RTCIceServers defaultIceServers;
1158 
1160 
1161  typedef struct RTCConfiguration {
1162  explicit RTCConfiguration();
1163  ~RTCConfiguration();
1164 
1165  uint16_t iceCandidatePoolSize;
1166  RTCBundlePolicy bundlePolicy;
1167  RTCIceServers iceServers;
1168  RTCIceTransportPolicy iceTransportPolicy;
1169  RTCRtcpMuxPolicy rtcpMuxPolicy;
1170  } RTCConfiguration;
1171 
1174 
1175  typedef struct {
1176  bool voiceActivityDetection;
1178 
1180 
1181  typedef struct : RTCOfferAnswerOptions {
1182  bool iceRestart;
1183  } RTCOfferOptions;
1184 
1186 
1187  typedef struct : RTCOfferAnswerOptions {
1188  } RTCAnswerOptions;
1189 
1190  typedef Functor<void(const Let<MediaStream> &stream)> StreamCallback;
1191  typedef Functor<void(const Let<RTCDataChannel> &dataChannel)> DataChannelCallback;
1192  typedef Functor<void(const RTCIceCandidate &candidate)> IceCandidateCallback;
1193 
1194  static Let<RTCPeerConnection> New(const RTCConfiguration &config = RTCConfiguration());
1195 
1196  virtual Let<RTCDataChannel> CreateDataChannel(const std::string &label, const RTCDataChannelInit &options = RTCDataChannelInit()) = 0;
1197 
1199 
1200  virtual Let<Promise<void>> AddIceCandidate(const RTCIceCandidate &candidate) = 0;
1201 
1203 
1204  virtual void AddStream(const Let<MediaStream> &stream) = 0;
1205 
1207 
1208  virtual Let<Promise<RTCSessionDescription>> CreateAnswer(const RTCAnswerOptions &options = RTCAnswerOptions()) = 0;
1209 
1211 
1212  virtual Let<Promise<RTCSessionDescription>> CreateOffer(const RTCOfferOptions &options = RTCOfferOptions()) = 0;
1213 
1215 
1216  virtual MediaStreams GetLocalStreams() = 0;
1217 
1219 
1220  virtual MediaStreams GetRemoteStreams() = 0;
1221 
1223 
1224  virtual void RemoveStream(const Let<MediaStream> &stream) = 0;
1225 
1227 
1228  virtual void SetConfiguration(const RTCConfiguration &config) = 0;
1229 
1231 
1232  virtual Let<Promise<void>> SetLocalDescription(const RTCSessionDescription &sdp) = 0;
1233 
1235 
1236  virtual Let<Promise<void>> SetRemoteDescription(const RTCSessionDescription &sdp) = 0;
1237 
1239 
1240  virtual void Close() = 0;
1241 
1242  virtual RTCSessionDescription CurrentLocalDescription() = 0;
1243  virtual RTCSessionDescription CurrentRemoteDescription() = 0;
1244  virtual RTCSessionDescription LocalDescription() = 0;
1245  virtual RTCSessionDescription PendingLocalDescription() = 0;
1246  virtual RTCSessionDescription PendingRemoteDescription() = 0;
1247  virtual RTCSessionDescription RemoteDescription() = 0;
1248 
1249  virtual RTCIceConnectionState IceConnectionState() = 0;
1250  virtual RTCIceGatheringState IceGatheringState() = 0;
1251  virtual RTCSignalingState SignalingState() = 0;
1252 
1253  Callback onnegotiationneeded;
1254  Callback onsignalingstatechange;
1255  Callback onicegatheringstatechange;
1256  Callback oniceconnectionstatechange;
1257  Callback onicecandidatesremoved;
1258  StreamCallback onaddstream;
1259  StreamCallback onremovestream;
1260  DataChannelCallback ondatachannel;
1261  IceCandidateCallback onicecandidate;
1262 
1263  protected:
1264  explicit RTCPeerConnection();
1265  ~RTCPeerConnection() override;
1266 };
1267 }; // namespace crtc
1268 
1269 #endif // INCLUDE_CRTC_H_
Definition: crtc.h:769
Definition: crtc.h:571
Definition: crtc.h:74
Definition: crtc.h:858
Definition: crtc.h:203
Definition: crtc.h:1047
Definition: crtc.h:755
RTCIceGatheringState
Definition: crtc.h:1097
Definition: crtc.h:406
RTCSignalingState
Definition: crtc.h:1086
Definition: crtc.h:940
Definition: crtc.h:809
Definition: crtc.h:918
Definition: crtc.h:595
Callback onbufferedamountlow
Definition: crtc.h:1022
Callback onclose
Definition: crtc.h:1026
Definition: crtc.h:93
Definition: crtc.h:451
Definition: crtc.h:419
Definition: crtc.h:892
Definition: crtc.h:841
ErrorCallback onerror
Definition: crtc.h:1030
Definition: crtc.h:83
Definition: crtc.h:958
Definition: crtc.h:470
Definition: crtc.h:746
RTCBundlePolicy
Definition: crtc.h:1117
RTCIceTransportPolicy
Definition: crtc.h:1125
Definition: crtc.h:876
Callback onopen
Definition: crtc.h:1038
RTCIceConnectionState
Definition: crtc.h:1105
Definition: crtc.h:72
Definition: crtc.h:396
RTCRtcpMuxPolicy
Definition: crtc.h:1133
MessageCallback onmessage
Definition: crtc.h:1034