mediaconnection.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * Wraps the streaming interface between two Peers.
  3. */
  4. function MediaConnection(peer, provider, options) {
  5. if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options);
  6. EventEmitter.call(this);
  7. this.options = util.extend({}, options);
  8. this.open = false;
  9. this.type = 'media';
  10. this.peer = peer;
  11. this.provider = provider;
  12. this.metadata = this.options.metadata;
  13. this.localStream = this.options._stream;
  14. this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
  15. if (this.localStream) {
  16. this.pc = Negotiator.startConnection(
  17. this,
  18. {_stream: this.localStream, originator: true}
  19. )
  20. }
  21. };
  22. util.inherits(MediaConnection, EventEmitter);
  23. MediaConnection._idPrefix = 'mc_';
  24. MediaConnection.prototype.addStream = function(remoteStream) {
  25. util.log('Receiving stream', remoteStream);
  26. this.remoteStream = remoteStream;
  27. this.emit('stream', remoteStream); // Should we call this `open`?
  28. this.open = true;
  29. };
  30. MediaConnection.prototype.handleMessage = function(message) {
  31. var payload = message.payload;
  32. switch (message.type) {
  33. case 'ANSWER':
  34. // TODO: assert sdp exists.
  35. // Should we pass `this`?
  36. // Forward to negotiator
  37. Negotiator.handleSDP(message.type, this, payload.sdp);
  38. break;
  39. case 'CANDIDATE':
  40. // TODO
  41. Negotiator.handleCandidate(this, payload.candidate);
  42. break;
  43. default:
  44. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  45. break;
  46. }
  47. }
  48. MediaConnection.prototype.answer = function(stream) {
  49. if (this.localStream) {
  50. // Throw some error.
  51. return;
  52. }
  53. this.options._payload._stream = stream;
  54. this.localStream = stream;
  55. this._pc = Negotiator.startConnection(
  56. this.type,
  57. this.peer,
  58. this.id,
  59. this.provider,
  60. this.options._payload
  61. )
  62. };
  63. /**
  64. * Exposed functionality for users.
  65. */
  66. /** Allows user to close connection. */
  67. MediaConnection.prototype.close = function() {
  68. if (this.open) {
  69. this.open = false;
  70. this.emit('close')
  71. }
  72. };