adapter.js 168 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.adapter = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* eslint-env node */
  3. 'use strict';
  4. // SDP helpers.
  5. var SDPUtils = {};
  6. // Generate an alphanumeric identifier for cname or mids.
  7. // TODO: use UUIDs instead? https://gist.github.com/jed/982883
  8. SDPUtils.generateIdentifier = function() {
  9. return Math.random().toString(36).substr(2, 10);
  10. };
  11. // The RTCP CNAME used by all peerconnections from the same JS.
  12. SDPUtils.localCName = SDPUtils.generateIdentifier();
  13. // Splits SDP into lines, dealing with both CRLF and LF.
  14. SDPUtils.splitLines = function(blob) {
  15. return blob.trim().split('\n').map(function(line) {
  16. return line.trim();
  17. });
  18. };
  19. // Splits SDP into sessionpart and mediasections. Ensures CRLF.
  20. SDPUtils.splitSections = function(blob) {
  21. var parts = blob.split('\nm=');
  22. return parts.map(function(part, index) {
  23. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  24. });
  25. };
  26. // returns the session description.
  27. SDPUtils.getDescription = function(blob) {
  28. var sections = SDPUtils.splitSections(blob);
  29. return sections && sections[0];
  30. };
  31. // returns the individual media sections.
  32. SDPUtils.getMediaSections = function(blob) {
  33. var sections = SDPUtils.splitSections(blob);
  34. sections.shift();
  35. return sections;
  36. };
  37. // Returns lines that start with a certain prefix.
  38. SDPUtils.matchPrefix = function(blob, prefix) {
  39. return SDPUtils.splitLines(blob).filter(function(line) {
  40. return line.indexOf(prefix) === 0;
  41. });
  42. };
  43. // Parses an ICE candidate line. Sample input:
  44. // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
  45. // rport 55996"
  46. SDPUtils.parseCandidate = function(line) {
  47. var parts;
  48. // Parse both variants.
  49. if (line.indexOf('a=candidate:') === 0) {
  50. parts = line.substring(12).split(' ');
  51. } else {
  52. parts = line.substring(10).split(' ');
  53. }
  54. var candidate = {
  55. foundation: parts[0],
  56. component: parseInt(parts[1], 10),
  57. protocol: parts[2].toLowerCase(),
  58. priority: parseInt(parts[3], 10),
  59. ip: parts[4],
  60. port: parseInt(parts[5], 10),
  61. // skip parts[6] == 'typ'
  62. type: parts[7]
  63. };
  64. for (var i = 8; i < parts.length; i += 2) {
  65. switch (parts[i]) {
  66. case 'raddr':
  67. candidate.relatedAddress = parts[i + 1];
  68. break;
  69. case 'rport':
  70. candidate.relatedPort = parseInt(parts[i + 1], 10);
  71. break;
  72. case 'tcptype':
  73. candidate.tcpType = parts[i + 1];
  74. break;
  75. case 'ufrag':
  76. candidate.ufrag = parts[i + 1]; // for backward compability.
  77. candidate.usernameFragment = parts[i + 1];
  78. break;
  79. default: // extension handling, in particular ufrag
  80. candidate[parts[i]] = parts[i + 1];
  81. break;
  82. }
  83. }
  84. return candidate;
  85. };
  86. // Translates a candidate object into SDP candidate attribute.
  87. SDPUtils.writeCandidate = function(candidate) {
  88. var sdp = [];
  89. sdp.push(candidate.foundation);
  90. sdp.push(candidate.component);
  91. sdp.push(candidate.protocol.toUpperCase());
  92. sdp.push(candidate.priority);
  93. sdp.push(candidate.ip);
  94. sdp.push(candidate.port);
  95. var type = candidate.type;
  96. sdp.push('typ');
  97. sdp.push(type);
  98. if (type !== 'host' && candidate.relatedAddress &&
  99. candidate.relatedPort) {
  100. sdp.push('raddr');
  101. sdp.push(candidate.relatedAddress); // was: relAddr
  102. sdp.push('rport');
  103. sdp.push(candidate.relatedPort); // was: relPort
  104. }
  105. if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
  106. sdp.push('tcptype');
  107. sdp.push(candidate.tcpType);
  108. }
  109. if (candidate.ufrag) {
  110. sdp.push('ufrag');
  111. sdp.push(candidate.ufrag);
  112. }
  113. return 'candidate:' + sdp.join(' ');
  114. };
  115. // Parses an ice-options line, returns an array of option tags.
  116. // a=ice-options:foo bar
  117. SDPUtils.parseIceOptions = function(line) {
  118. return line.substr(14).split(' ');
  119. }
  120. // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
  121. // a=rtpmap:111 opus/48000/2
  122. SDPUtils.parseRtpMap = function(line) {
  123. var parts = line.substr(9).split(' ');
  124. var parsed = {
  125. payloadType: parseInt(parts.shift(), 10) // was: id
  126. };
  127. parts = parts[0].split('/');
  128. parsed.name = parts[0];
  129. parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
  130. // was: channels
  131. parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
  132. return parsed;
  133. };
  134. // Generate an a=rtpmap line from RTCRtpCodecCapability or
  135. // RTCRtpCodecParameters.
  136. SDPUtils.writeRtpMap = function(codec) {
  137. var pt = codec.payloadType;
  138. if (codec.preferredPayloadType !== undefined) {
  139. pt = codec.preferredPayloadType;
  140. }
  141. return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
  142. (codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n';
  143. };
  144. // Parses an a=extmap line (headerextension from RFC 5285). Sample input:
  145. // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  146. // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
  147. SDPUtils.parseExtmap = function(line) {
  148. var parts = line.substr(9).split(' ');
  149. return {
  150. id: parseInt(parts[0], 10),
  151. direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
  152. uri: parts[1]
  153. };
  154. };
  155. // Generates a=extmap line from RTCRtpHeaderExtensionParameters or
  156. // RTCRtpHeaderExtension.
  157. SDPUtils.writeExtmap = function(headerExtension) {
  158. return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
  159. (headerExtension.direction && headerExtension.direction !== 'sendrecv'
  160. ? '/' + headerExtension.direction
  161. : '') +
  162. ' ' + headerExtension.uri + '\r\n';
  163. };
  164. // Parses an ftmp line, returns dictionary. Sample input:
  165. // a=fmtp:96 vbr=on;cng=on
  166. // Also deals with vbr=on; cng=on
  167. SDPUtils.parseFmtp = function(line) {
  168. var parsed = {};
  169. var kv;
  170. var parts = line.substr(line.indexOf(' ') + 1).split(';');
  171. for (var j = 0; j < parts.length; j++) {
  172. kv = parts[j].trim().split('=');
  173. parsed[kv[0].trim()] = kv[1];
  174. }
  175. return parsed;
  176. };
  177. // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
  178. SDPUtils.writeFmtp = function(codec) {
  179. var line = '';
  180. var pt = codec.payloadType;
  181. if (codec.preferredPayloadType !== undefined) {
  182. pt = codec.preferredPayloadType;
  183. }
  184. if (codec.parameters && Object.keys(codec.parameters).length) {
  185. var params = [];
  186. Object.keys(codec.parameters).forEach(function(param) {
  187. params.push(param + '=' + codec.parameters[param]);
  188. });
  189. line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
  190. }
  191. return line;
  192. };
  193. // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
  194. // a=rtcp-fb:98 nack rpsi
  195. SDPUtils.parseRtcpFb = function(line) {
  196. var parts = line.substr(line.indexOf(' ') + 1).split(' ');
  197. return {
  198. type: parts.shift(),
  199. parameter: parts.join(' ')
  200. };
  201. };
  202. // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
  203. SDPUtils.writeRtcpFb = function(codec) {
  204. var lines = '';
  205. var pt = codec.payloadType;
  206. if (codec.preferredPayloadType !== undefined) {
  207. pt = codec.preferredPayloadType;
  208. }
  209. if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
  210. // FIXME: special handling for trr-int?
  211. codec.rtcpFeedback.forEach(function(fb) {
  212. lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
  213. (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
  214. '\r\n';
  215. });
  216. }
  217. return lines;
  218. };
  219. // Parses an RFC 5576 ssrc media attribute. Sample input:
  220. // a=ssrc:3735928559 cname:something
  221. SDPUtils.parseSsrcMedia = function(line) {
  222. var sp = line.indexOf(' ');
  223. var parts = {
  224. ssrc: parseInt(line.substr(7, sp - 7), 10)
  225. };
  226. var colon = line.indexOf(':', sp);
  227. if (colon > -1) {
  228. parts.attribute = line.substr(sp + 1, colon - sp - 1);
  229. parts.value = line.substr(colon + 1);
  230. } else {
  231. parts.attribute = line.substr(sp + 1);
  232. }
  233. return parts;
  234. };
  235. // Extracts the MID (RFC 5888) from a media section.
  236. // returns the MID or undefined if no mid line was found.
  237. SDPUtils.getMid = function(mediaSection) {
  238. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
  239. if (mid) {
  240. return mid.substr(6);
  241. }
  242. }
  243. SDPUtils.parseFingerprint = function(line) {
  244. var parts = line.substr(14).split(' ');
  245. return {
  246. algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
  247. value: parts[1]
  248. };
  249. };
  250. // Extracts DTLS parameters from SDP media section or sessionpart.
  251. // FIXME: for consistency with other functions this should only
  252. // get the fingerprint line as input. See also getIceParameters.
  253. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
  254. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
  255. 'a=fingerprint:');
  256. // Note: a=setup line is ignored since we use the 'auto' role.
  257. // Note2: 'algorithm' is not case sensitive except in Edge.
  258. return {
  259. role: 'auto',
  260. fingerprints: lines.map(SDPUtils.parseFingerprint)
  261. };
  262. };
  263. // Serializes DTLS parameters to SDP.
  264. SDPUtils.writeDtlsParameters = function(params, setupType) {
  265. var sdp = 'a=setup:' + setupType + '\r\n';
  266. params.fingerprints.forEach(function(fp) {
  267. sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
  268. });
  269. return sdp;
  270. };
  271. // Parses ICE information from SDP media section or sessionpart.
  272. // FIXME: for consistency with other functions this should only
  273. // get the ice-ufrag and ice-pwd lines as input.
  274. SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
  275. var lines = SDPUtils.splitLines(mediaSection);
  276. // Search in session part, too.
  277. lines = lines.concat(SDPUtils.splitLines(sessionpart));
  278. var iceParameters = {
  279. usernameFragment: lines.filter(function(line) {
  280. return line.indexOf('a=ice-ufrag:') === 0;
  281. })[0].substr(12),
  282. password: lines.filter(function(line) {
  283. return line.indexOf('a=ice-pwd:') === 0;
  284. })[0].substr(10)
  285. };
  286. return iceParameters;
  287. };
  288. // Serializes ICE parameters to SDP.
  289. SDPUtils.writeIceParameters = function(params) {
  290. return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
  291. 'a=ice-pwd:' + params.password + '\r\n';
  292. };
  293. // Parses the SDP media section and returns RTCRtpParameters.
  294. SDPUtils.parseRtpParameters = function(mediaSection) {
  295. var description = {
  296. codecs: [],
  297. headerExtensions: [],
  298. fecMechanisms: [],
  299. rtcp: []
  300. };
  301. var lines = SDPUtils.splitLines(mediaSection);
  302. var mline = lines[0].split(' ');
  303. for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
  304. var pt = mline[i];
  305. var rtpmapline = SDPUtils.matchPrefix(
  306. mediaSection, 'a=rtpmap:' + pt + ' ')[0];
  307. if (rtpmapline) {
  308. var codec = SDPUtils.parseRtpMap(rtpmapline);
  309. var fmtps = SDPUtils.matchPrefix(
  310. mediaSection, 'a=fmtp:' + pt + ' ');
  311. // Only the first a=fmtp:<pt> is considered.
  312. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
  313. codec.rtcpFeedback = SDPUtils.matchPrefix(
  314. mediaSection, 'a=rtcp-fb:' + pt + ' ')
  315. .map(SDPUtils.parseRtcpFb);
  316. description.codecs.push(codec);
  317. // parse FEC mechanisms from rtpmap lines.
  318. switch (codec.name.toUpperCase()) {
  319. case 'RED':
  320. case 'ULPFEC':
  321. description.fecMechanisms.push(codec.name.toUpperCase());
  322. break;
  323. default: // only RED and ULPFEC are recognized as FEC mechanisms.
  324. break;
  325. }
  326. }
  327. }
  328. SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
  329. description.headerExtensions.push(SDPUtils.parseExtmap(line));
  330. });
  331. // FIXME: parse rtcp.
  332. return description;
  333. };
  334. // Generates parts of the SDP media section describing the capabilities /
  335. // parameters.
  336. SDPUtils.writeRtpDescription = function(kind, caps) {
  337. var sdp = '';
  338. // Build the mline.
  339. sdp += 'm=' + kind + ' ';
  340. sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
  341. sdp += ' UDP/TLS/RTP/SAVPF ';
  342. sdp += caps.codecs.map(function(codec) {
  343. if (codec.preferredPayloadType !== undefined) {
  344. return codec.preferredPayloadType;
  345. }
  346. return codec.payloadType;
  347. }).join(' ') + '\r\n';
  348. sdp += 'c=IN IP4 0.0.0.0\r\n';
  349. sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
  350. // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
  351. caps.codecs.forEach(function(codec) {
  352. sdp += SDPUtils.writeRtpMap(codec);
  353. sdp += SDPUtils.writeFmtp(codec);
  354. sdp += SDPUtils.writeRtcpFb(codec);
  355. });
  356. var maxptime = 0;
  357. caps.codecs.forEach(function(codec) {
  358. if (codec.maxptime > maxptime) {
  359. maxptime = codec.maxptime;
  360. }
  361. });
  362. if (maxptime > 0) {
  363. sdp += 'a=maxptime:' + maxptime + '\r\n';
  364. }
  365. sdp += 'a=rtcp-mux\r\n';
  366. caps.headerExtensions.forEach(function(extension) {
  367. sdp += SDPUtils.writeExtmap(extension);
  368. });
  369. // FIXME: write fecMechanisms.
  370. return sdp;
  371. };
  372. // Parses the SDP media section and returns an array of
  373. // RTCRtpEncodingParameters.
  374. SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
  375. var encodingParameters = [];
  376. var description = SDPUtils.parseRtpParameters(mediaSection);
  377. var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
  378. var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
  379. // filter a=ssrc:... cname:, ignore PlanB-msid
  380. var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  381. .map(function(line) {
  382. return SDPUtils.parseSsrcMedia(line);
  383. })
  384. .filter(function(parts) {
  385. return parts.attribute === 'cname';
  386. });
  387. var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
  388. var secondarySsrc;
  389. var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
  390. .map(function(line) {
  391. var parts = line.split(' ');
  392. parts.shift();
  393. return parts.map(function(part) {
  394. return parseInt(part, 10);
  395. });
  396. });
  397. if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
  398. secondarySsrc = flows[0][1];
  399. }
  400. description.codecs.forEach(function(codec) {
  401. if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
  402. var encParam = {
  403. ssrc: primarySsrc,
  404. codecPayloadType: parseInt(codec.parameters.apt, 10),
  405. rtx: {
  406. ssrc: secondarySsrc
  407. }
  408. };
  409. encodingParameters.push(encParam);
  410. if (hasRed) {
  411. encParam = JSON.parse(JSON.stringify(encParam));
  412. encParam.fec = {
  413. ssrc: secondarySsrc,
  414. mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
  415. };
  416. encodingParameters.push(encParam);
  417. }
  418. }
  419. });
  420. if (encodingParameters.length === 0 && primarySsrc) {
  421. encodingParameters.push({
  422. ssrc: primarySsrc
  423. });
  424. }
  425. // we support both b=AS and b=TIAS but interpret AS as TIAS.
  426. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
  427. if (bandwidth.length) {
  428. if (bandwidth[0].indexOf('b=TIAS:') === 0) {
  429. bandwidth = parseInt(bandwidth[0].substr(7), 10);
  430. } else if (bandwidth[0].indexOf('b=AS:') === 0) {
  431. // use formula from JSEP to convert b=AS to TIAS value.
  432. bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95
  433. - (50 * 40 * 8);
  434. } else {
  435. bandwidth = undefined;
  436. }
  437. encodingParameters.forEach(function(params) {
  438. params.maxBitrate = bandwidth;
  439. });
  440. }
  441. return encodingParameters;
  442. };
  443. // parses http://draft.ortc.org/#rtcrtcpparameters*
  444. SDPUtils.parseRtcpParameters = function(mediaSection) {
  445. var rtcpParameters = {};
  446. var cname;
  447. // Gets the first SSRC. Note that with RTX there might be multiple
  448. // SSRCs.
  449. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  450. .map(function(line) {
  451. return SDPUtils.parseSsrcMedia(line);
  452. })
  453. .filter(function(obj) {
  454. return obj.attribute === 'cname';
  455. })[0];
  456. if (remoteSsrc) {
  457. rtcpParameters.cname = remoteSsrc.value;
  458. rtcpParameters.ssrc = remoteSsrc.ssrc;
  459. }
  460. // Edge uses the compound attribute instead of reducedSize
  461. // compound is !reducedSize
  462. var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
  463. rtcpParameters.reducedSize = rsize.length > 0;
  464. rtcpParameters.compound = rsize.length === 0;
  465. // parses the rtcp-mux attrіbute.
  466. // Note that Edge does not support unmuxed RTCP.
  467. var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
  468. rtcpParameters.mux = mux.length > 0;
  469. return rtcpParameters;
  470. };
  471. // parses either a=msid: or a=ssrc:... msid lines and returns
  472. // the id of the MediaStream and MediaStreamTrack.
  473. SDPUtils.parseMsid = function(mediaSection) {
  474. var parts;
  475. var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
  476. if (spec.length === 1) {
  477. parts = spec[0].substr(7).split(' ');
  478. return {stream: parts[0], track: parts[1]};
  479. }
  480. var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  481. .map(function(line) {
  482. return SDPUtils.parseSsrcMedia(line);
  483. })
  484. .filter(function(parts) {
  485. return parts.attribute === 'msid';
  486. });
  487. if (planB.length > 0) {
  488. parts = planB[0].value.split(' ');
  489. return {stream: parts[0], track: parts[1]};
  490. }
  491. };
  492. // Generate a session ID for SDP.
  493. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
  494. // recommends using a cryptographically random +ve 64-bit value
  495. // but right now this should be acceptable and within the right range
  496. SDPUtils.generateSessionId = function() {
  497. return Math.random().toString().substr(2, 21);
  498. };
  499. // Write boilder plate for start of SDP
  500. // sessId argument is optional - if not supplied it will
  501. // be generated randomly
  502. // sessVersion is optional and defaults to 2
  503. SDPUtils.writeSessionBoilerplate = function(sessId, sessVer) {
  504. var sessionId;
  505. var version = sessVer !== undefined ? sessVer : 2;
  506. if (sessId) {
  507. sessionId = sessId;
  508. } else {
  509. sessionId = SDPUtils.generateSessionId();
  510. }
  511. // FIXME: sess-id should be an NTP timestamp.
  512. return 'v=0\r\n' +
  513. 'o=thisisadapterortc ' + sessionId + ' ' + version + ' IN IP4 127.0.0.1\r\n' +
  514. 's=-\r\n' +
  515. 't=0 0\r\n';
  516. };
  517. SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
  518. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  519. // Map ICE parameters (ufrag, pwd) to SDP.
  520. sdp += SDPUtils.writeIceParameters(
  521. transceiver.iceGatherer.getLocalParameters());
  522. // Map DTLS parameters to SDP.
  523. sdp += SDPUtils.writeDtlsParameters(
  524. transceiver.dtlsTransport.getLocalParameters(),
  525. type === 'offer' ? 'actpass' : 'active');
  526. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  527. if (transceiver.direction) {
  528. sdp += 'a=' + transceiver.direction + '\r\n';
  529. } else if (transceiver.rtpSender && transceiver.rtpReceiver) {
  530. sdp += 'a=sendrecv\r\n';
  531. } else if (transceiver.rtpSender) {
  532. sdp += 'a=sendonly\r\n';
  533. } else if (transceiver.rtpReceiver) {
  534. sdp += 'a=recvonly\r\n';
  535. } else {
  536. sdp += 'a=inactive\r\n';
  537. }
  538. if (transceiver.rtpSender) {
  539. // spec.
  540. var msid = 'msid:' + stream.id + ' ' +
  541. transceiver.rtpSender.track.id + '\r\n';
  542. sdp += 'a=' + msid;
  543. // for Chrome.
  544. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  545. ' ' + msid;
  546. if (transceiver.sendEncodingParameters[0].rtx) {
  547. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  548. ' ' + msid;
  549. sdp += 'a=ssrc-group:FID ' +
  550. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  551. transceiver.sendEncodingParameters[0].rtx.ssrc +
  552. '\r\n';
  553. }
  554. }
  555. // FIXME: this should be written by writeRtpDescription.
  556. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  557. ' cname:' + SDPUtils.localCName + '\r\n';
  558. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  559. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  560. ' cname:' + SDPUtils.localCName + '\r\n';
  561. }
  562. return sdp;
  563. };
  564. // Gets the direction from the mediaSection or the sessionpart.
  565. SDPUtils.getDirection = function(mediaSection, sessionpart) {
  566. // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
  567. var lines = SDPUtils.splitLines(mediaSection);
  568. for (var i = 0; i < lines.length; i++) {
  569. switch (lines[i]) {
  570. case 'a=sendrecv':
  571. case 'a=sendonly':
  572. case 'a=recvonly':
  573. case 'a=inactive':
  574. return lines[i].substr(2);
  575. default:
  576. // FIXME: What should happen here?
  577. }
  578. }
  579. if (sessionpart) {
  580. return SDPUtils.getDirection(sessionpart);
  581. }
  582. return 'sendrecv';
  583. };
  584. SDPUtils.getKind = function(mediaSection) {
  585. var lines = SDPUtils.splitLines(mediaSection);
  586. var mline = lines[0].split(' ');
  587. return mline[0].substr(2);
  588. };
  589. SDPUtils.isRejected = function(mediaSection) {
  590. return mediaSection.split(' ', 2)[1] === '0';
  591. };
  592. SDPUtils.parseMLine = function(mediaSection) {
  593. var lines = SDPUtils.splitLines(mediaSection);
  594. var parts = lines[0].substr(2).split(' ');
  595. return {
  596. kind: parts[0],
  597. port: parseInt(parts[1], 10),
  598. protocol: parts[2],
  599. fmt: parts.slice(3).join(' ')
  600. };
  601. };
  602. SDPUtils.parseOLine = function(mediaSection) {
  603. var line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];
  604. var parts = line.substr(2).split(' ');
  605. return {
  606. username: parts[0],
  607. sessionId: parts[1],
  608. sessionVersion: parseInt(parts[2], 10),
  609. netType: parts[3],
  610. addressType: parts[4],
  611. address: parts[5],
  612. };
  613. }
  614. // Expose public methods.
  615. if (typeof module === 'object') {
  616. module.exports = SDPUtils;
  617. }
  618. },{}],2:[function(require,module,exports){
  619. /*
  620. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  621. *
  622. * Use of this source code is governed by a BSD-style license
  623. * that can be found in the LICENSE file in the root of the source
  624. * tree.
  625. */
  626. /* eslint-env node */
  627. 'use strict';
  628. var SDPUtils = require('sdp');
  629. function writeMediaSection(transceiver, caps, type, stream, dtlsRole) {
  630. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  631. // Map ICE parameters (ufrag, pwd) to SDP.
  632. sdp += SDPUtils.writeIceParameters(
  633. transceiver.iceGatherer.getLocalParameters());
  634. // Map DTLS parameters to SDP.
  635. sdp += SDPUtils.writeDtlsParameters(
  636. transceiver.dtlsTransport.getLocalParameters(),
  637. type === 'offer' ? 'actpass' : dtlsRole || 'active');
  638. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  639. if (transceiver.rtpSender && transceiver.rtpReceiver) {
  640. sdp += 'a=sendrecv\r\n';
  641. } else if (transceiver.rtpSender) {
  642. sdp += 'a=sendonly\r\n';
  643. } else if (transceiver.rtpReceiver) {
  644. sdp += 'a=recvonly\r\n';
  645. } else {
  646. sdp += 'a=inactive\r\n';
  647. }
  648. if (transceiver.rtpSender) {
  649. var trackId = transceiver.rtpSender._initialTrackId ||
  650. transceiver.rtpSender.track.id;
  651. transceiver.rtpSender._initialTrackId = trackId;
  652. // spec.
  653. var msid = 'msid:' + (stream ? stream.id : '-') + ' ' +
  654. trackId + '\r\n';
  655. sdp += 'a=' + msid;
  656. // for Chrome. Legacy should no longer be required.
  657. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  658. ' ' + msid;
  659. // RTX
  660. if (transceiver.sendEncodingParameters[0].rtx) {
  661. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  662. ' ' + msid;
  663. sdp += 'a=ssrc-group:FID ' +
  664. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  665. transceiver.sendEncodingParameters[0].rtx.ssrc +
  666. '\r\n';
  667. }
  668. }
  669. // FIXME: this should be written by writeRtpDescription.
  670. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  671. ' cname:' + SDPUtils.localCName + '\r\n';
  672. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  673. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  674. ' cname:' + SDPUtils.localCName + '\r\n';
  675. }
  676. return sdp;
  677. }
  678. // Edge does not like
  679. // 1) stun: filtered after 14393 unless ?transport=udp is present
  680. // 2) turn: that does not have all of turn:host:port?transport=udp
  681. // 3) turn: with ipv6 addresses
  682. // 4) turn: occurring muliple times
  683. function filterIceServers(iceServers, edgeVersion) {
  684. var hasTurn = false;
  685. iceServers = JSON.parse(JSON.stringify(iceServers));
  686. return iceServers.filter(function(server) {
  687. if (server && (server.urls || server.url)) {
  688. var urls = server.urls || server.url;
  689. if (server.url && !server.urls) {
  690. console.warn('RTCIceServer.url is deprecated! Use urls instead.');
  691. }
  692. var isString = typeof urls === 'string';
  693. if (isString) {
  694. urls = [urls];
  695. }
  696. urls = urls.filter(function(url) {
  697. var validTurn = url.indexOf('turn:') === 0 &&
  698. url.indexOf('transport=udp') !== -1 &&
  699. url.indexOf('turn:[') === -1 &&
  700. !hasTurn;
  701. if (validTurn) {
  702. hasTurn = true;
  703. return true;
  704. }
  705. return url.indexOf('stun:') === 0 && edgeVersion >= 14393 &&
  706. url.indexOf('?transport=udp') === -1;
  707. });
  708. delete server.url;
  709. server.urls = isString ? urls[0] : urls;
  710. return !!urls.length;
  711. }
  712. });
  713. }
  714. // Determines the intersection of local and remote capabilities.
  715. function getCommonCapabilities(localCapabilities, remoteCapabilities) {
  716. var commonCapabilities = {
  717. codecs: [],
  718. headerExtensions: [],
  719. fecMechanisms: []
  720. };
  721. var findCodecByPayloadType = function(pt, codecs) {
  722. pt = parseInt(pt, 10);
  723. for (var i = 0; i < codecs.length; i++) {
  724. if (codecs[i].payloadType === pt ||
  725. codecs[i].preferredPayloadType === pt) {
  726. return codecs[i];
  727. }
  728. }
  729. };
  730. var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) {
  731. var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs);
  732. var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs);
  733. return lCodec && rCodec &&
  734. lCodec.name.toLowerCase() === rCodec.name.toLowerCase();
  735. };
  736. localCapabilities.codecs.forEach(function(lCodec) {
  737. for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
  738. var rCodec = remoteCapabilities.codecs[i];
  739. if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
  740. lCodec.clockRate === rCodec.clockRate) {
  741. if (lCodec.name.toLowerCase() === 'rtx' &&
  742. lCodec.parameters && rCodec.parameters.apt) {
  743. // for RTX we need to find the local rtx that has a apt
  744. // which points to the same local codec as the remote one.
  745. if (!rtxCapabilityMatches(lCodec, rCodec,
  746. localCapabilities.codecs, remoteCapabilities.codecs)) {
  747. continue;
  748. }
  749. }
  750. rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy
  751. // number of channels is the highest common number of channels
  752. rCodec.numChannels = Math.min(lCodec.numChannels,
  753. rCodec.numChannels);
  754. // push rCodec so we reply with offerer payload type
  755. commonCapabilities.codecs.push(rCodec);
  756. // determine common feedback mechanisms
  757. rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
  758. for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
  759. if (lCodec.rtcpFeedback[j].type === fb.type &&
  760. lCodec.rtcpFeedback[j].parameter === fb.parameter) {
  761. return true;
  762. }
  763. }
  764. return false;
  765. });
  766. // FIXME: also need to determine .parameters
  767. // see https://github.com/openpeer/ortc/issues/569
  768. break;
  769. }
  770. }
  771. });
  772. localCapabilities.headerExtensions.forEach(function(lHeaderExtension) {
  773. for (var i = 0; i < remoteCapabilities.headerExtensions.length;
  774. i++) {
  775. var rHeaderExtension = remoteCapabilities.headerExtensions[i];
  776. if (lHeaderExtension.uri === rHeaderExtension.uri) {
  777. commonCapabilities.headerExtensions.push(rHeaderExtension);
  778. break;
  779. }
  780. }
  781. });
  782. // FIXME: fecMechanisms
  783. return commonCapabilities;
  784. }
  785. // is action=setLocalDescription with type allowed in signalingState
  786. function isActionAllowedInSignalingState(action, type, signalingState) {
  787. return {
  788. offer: {
  789. setLocalDescription: ['stable', 'have-local-offer'],
  790. setRemoteDescription: ['stable', 'have-remote-offer']
  791. },
  792. answer: {
  793. setLocalDescription: ['have-remote-offer', 'have-local-pranswer'],
  794. setRemoteDescription: ['have-local-offer', 'have-remote-pranswer']
  795. }
  796. }[type][action].indexOf(signalingState) !== -1;
  797. }
  798. function maybeAddCandidate(iceTransport, candidate) {
  799. // Edge's internal representation adds some fields therefore
  800. // not all fieldѕ are taken into account.
  801. var alreadyAdded = iceTransport.getRemoteCandidates()
  802. .find(function(remoteCandidate) {
  803. return candidate.foundation === remoteCandidate.foundation &&
  804. candidate.ip === remoteCandidate.ip &&
  805. candidate.port === remoteCandidate.port &&
  806. candidate.priority === remoteCandidate.priority &&
  807. candidate.protocol === remoteCandidate.protocol &&
  808. candidate.type === remoteCandidate.type;
  809. });
  810. if (!alreadyAdded) {
  811. iceTransport.addRemoteCandidate(candidate);
  812. }
  813. return !alreadyAdded;
  814. }
  815. function makeError(name, description) {
  816. var e = new Error(description);
  817. e.name = name;
  818. // legacy error codes from https://heycam.github.io/webidl/#idl-DOMException-error-names
  819. e.code = {
  820. NotSupportedError: 9,
  821. InvalidStateError: 11,
  822. InvalidAccessError: 15,
  823. TypeError: undefined,
  824. OperationError: undefined
  825. }[name];
  826. return e;
  827. }
  828. module.exports = function(window, edgeVersion) {
  829. // https://w3c.github.io/mediacapture-main/#mediastream
  830. // Helper function to add the track to the stream and
  831. // dispatch the event ourselves.
  832. function addTrackToStreamAndFireEvent(track, stream) {
  833. stream.addTrack(track);
  834. stream.dispatchEvent(new window.MediaStreamTrackEvent('addtrack',
  835. {track: track}));
  836. }
  837. function removeTrackFromStreamAndFireEvent(track, stream) {
  838. stream.removeTrack(track);
  839. stream.dispatchEvent(new window.MediaStreamTrackEvent('removetrack',
  840. {track: track}));
  841. }
  842. function fireAddTrack(pc, track, receiver, streams) {
  843. var trackEvent = new Event('track');
  844. trackEvent.track = track;
  845. trackEvent.receiver = receiver;
  846. trackEvent.transceiver = {receiver: receiver};
  847. trackEvent.streams = streams;
  848. window.setTimeout(function() {
  849. pc._dispatchEvent('track', trackEvent);
  850. });
  851. }
  852. var RTCPeerConnection = function(config) {
  853. var pc = this;
  854. var _eventTarget = document.createDocumentFragment();
  855. ['addEventListener', 'removeEventListener', 'dispatchEvent']
  856. .forEach(function(method) {
  857. pc[method] = _eventTarget[method].bind(_eventTarget);
  858. });
  859. this.canTrickleIceCandidates = null;
  860. this.needNegotiation = false;
  861. this.localStreams = [];
  862. this.remoteStreams = [];
  863. this.localDescription = null;
  864. this.remoteDescription = null;
  865. this.signalingState = 'stable';
  866. this.iceConnectionState = 'new';
  867. this.connectionState = 'new';
  868. this.iceGatheringState = 'new';
  869. config = JSON.parse(JSON.stringify(config || {}));
  870. this.usingBundle = config.bundlePolicy === 'max-bundle';
  871. if (config.rtcpMuxPolicy === 'negotiate') {
  872. throw(makeError('NotSupportedError',
  873. 'rtcpMuxPolicy \'negotiate\' is not supported'));
  874. } else if (!config.rtcpMuxPolicy) {
  875. config.rtcpMuxPolicy = 'require';
  876. }
  877. switch (config.iceTransportPolicy) {
  878. case 'all':
  879. case 'relay':
  880. break;
  881. default:
  882. config.iceTransportPolicy = 'all';
  883. break;
  884. }
  885. switch (config.bundlePolicy) {
  886. case 'balanced':
  887. case 'max-compat':
  888. case 'max-bundle':
  889. break;
  890. default:
  891. config.bundlePolicy = 'balanced';
  892. break;
  893. }
  894. config.iceServers = filterIceServers(config.iceServers || [], edgeVersion);
  895. this._iceGatherers = [];
  896. if (config.iceCandidatePoolSize) {
  897. for (var i = config.iceCandidatePoolSize; i > 0; i--) {
  898. this._iceGatherers.push(new window.RTCIceGatherer({
  899. iceServers: config.iceServers,
  900. gatherPolicy: config.iceTransportPolicy
  901. }));
  902. }
  903. } else {
  904. config.iceCandidatePoolSize = 0;
  905. }
  906. this._config = config;
  907. // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
  908. // everything that is needed to describe a SDP m-line.
  909. this.transceivers = [];
  910. this._sdpSessionId = SDPUtils.generateSessionId();
  911. this._sdpSessionVersion = 0;
  912. this._dtlsRole = undefined; // role for a=setup to use in answers.
  913. this._isClosed = false;
  914. };
  915. // set up event handlers on prototype
  916. RTCPeerConnection.prototype.onicecandidate = null;
  917. RTCPeerConnection.prototype.onaddstream = null;
  918. RTCPeerConnection.prototype.ontrack = null;
  919. RTCPeerConnection.prototype.onremovestream = null;
  920. RTCPeerConnection.prototype.onsignalingstatechange = null;
  921. RTCPeerConnection.prototype.oniceconnectionstatechange = null;
  922. RTCPeerConnection.prototype.onconnectionstatechange = null;
  923. RTCPeerConnection.prototype.onicegatheringstatechange = null;
  924. RTCPeerConnection.prototype.onnegotiationneeded = null;
  925. RTCPeerConnection.prototype.ondatachannel = null;
  926. RTCPeerConnection.prototype._dispatchEvent = function(name, event) {
  927. if (this._isClosed) {
  928. return;
  929. }
  930. this.dispatchEvent(event);
  931. if (typeof this['on' + name] === 'function') {
  932. this['on' + name](event);
  933. }
  934. };
  935. RTCPeerConnection.prototype._emitGatheringStateChange = function() {
  936. var event = new Event('icegatheringstatechange');
  937. this._dispatchEvent('icegatheringstatechange', event);
  938. };
  939. RTCPeerConnection.prototype.getConfiguration = function() {
  940. return this._config;
  941. };
  942. RTCPeerConnection.prototype.getLocalStreams = function() {
  943. return this.localStreams;
  944. };
  945. RTCPeerConnection.prototype.getRemoteStreams = function() {
  946. return this.remoteStreams;
  947. };
  948. // internal helper to create a transceiver object.
  949. // (which is not yet the same as the WebRTC 1.0 transceiver)
  950. RTCPeerConnection.prototype._createTransceiver = function(kind, doNotAdd) {
  951. var hasBundleTransport = this.transceivers.length > 0;
  952. var transceiver = {
  953. track: null,
  954. iceGatherer: null,
  955. iceTransport: null,
  956. dtlsTransport: null,
  957. localCapabilities: null,
  958. remoteCapabilities: null,
  959. rtpSender: null,
  960. rtpReceiver: null,
  961. kind: kind,
  962. mid: null,
  963. sendEncodingParameters: null,
  964. recvEncodingParameters: null,
  965. stream: null,
  966. associatedRemoteMediaStreams: [],
  967. wantReceive: true
  968. };
  969. if (this.usingBundle && hasBundleTransport) {
  970. transceiver.iceTransport = this.transceivers[0].iceTransport;
  971. transceiver.dtlsTransport = this.transceivers[0].dtlsTransport;
  972. } else {
  973. var transports = this._createIceAndDtlsTransports();
  974. transceiver.iceTransport = transports.iceTransport;
  975. transceiver.dtlsTransport = transports.dtlsTransport;
  976. }
  977. if (!doNotAdd) {
  978. this.transceivers.push(transceiver);
  979. }
  980. return transceiver;
  981. };
  982. RTCPeerConnection.prototype.addTrack = function(track, stream) {
  983. if (this._isClosed) {
  984. throw makeError('InvalidStateError',
  985. 'Attempted to call addTrack on a closed peerconnection.');
  986. }
  987. var alreadyExists = this.transceivers.find(function(s) {
  988. return s.track === track;
  989. });
  990. if (alreadyExists) {
  991. throw makeError('InvalidAccessError', 'Track already exists.');
  992. }
  993. var transceiver;
  994. for (var i = 0; i < this.transceivers.length; i++) {
  995. if (!this.transceivers[i].track &&
  996. this.transceivers[i].kind === track.kind) {
  997. transceiver = this.transceivers[i];
  998. }
  999. }
  1000. if (!transceiver) {
  1001. transceiver = this._createTransceiver(track.kind);
  1002. }
  1003. this._maybeFireNegotiationNeeded();
  1004. if (this.localStreams.indexOf(stream) === -1) {
  1005. this.localStreams.push(stream);
  1006. }
  1007. transceiver.track = track;
  1008. transceiver.stream = stream;
  1009. transceiver.rtpSender = new window.RTCRtpSender(track,
  1010. transceiver.dtlsTransport);
  1011. return transceiver.rtpSender;
  1012. };
  1013. RTCPeerConnection.prototype.addStream = function(stream) {
  1014. var pc = this;
  1015. if (edgeVersion >= 15025) {
  1016. stream.getTracks().forEach(function(track) {
  1017. pc.addTrack(track, stream);
  1018. });
  1019. } else {
  1020. // Clone is necessary for local demos mostly, attaching directly
  1021. // to two different senders does not work (build 10547).
  1022. // Fixed in 15025 (or earlier)
  1023. var clonedStream = stream.clone();
  1024. stream.getTracks().forEach(function(track, idx) {
  1025. var clonedTrack = clonedStream.getTracks()[idx];
  1026. track.addEventListener('enabled', function(event) {
  1027. clonedTrack.enabled = event.enabled;
  1028. });
  1029. });
  1030. clonedStream.getTracks().forEach(function(track) {
  1031. pc.addTrack(track, clonedStream);
  1032. });
  1033. }
  1034. };
  1035. RTCPeerConnection.prototype.removeTrack = function(sender) {
  1036. if (this._isClosed) {
  1037. throw makeError('InvalidStateError',
  1038. 'Attempted to call removeTrack on a closed peerconnection.');
  1039. }
  1040. if (!(sender instanceof window.RTCRtpSender)) {
  1041. throw new TypeError('Argument 1 of RTCPeerConnection.removeTrack ' +
  1042. 'does not implement interface RTCRtpSender.');
  1043. }
  1044. var transceiver = this.transceivers.find(function(t) {
  1045. return t.rtpSender === sender;
  1046. });
  1047. if (!transceiver) {
  1048. throw makeError('InvalidAccessError',
  1049. 'Sender was not created by this connection.');
  1050. }
  1051. var stream = transceiver.stream;
  1052. transceiver.rtpSender.stop();
  1053. transceiver.rtpSender = null;
  1054. transceiver.track = null;
  1055. transceiver.stream = null;
  1056. // remove the stream from the set of local streams
  1057. var localStreams = this.transceivers.map(function(t) {
  1058. return t.stream;
  1059. });
  1060. if (localStreams.indexOf(stream) === -1 &&
  1061. this.localStreams.indexOf(stream) > -1) {
  1062. this.localStreams.splice(this.localStreams.indexOf(stream), 1);
  1063. }
  1064. this._maybeFireNegotiationNeeded();
  1065. };
  1066. RTCPeerConnection.prototype.removeStream = function(stream) {
  1067. var pc = this;
  1068. stream.getTracks().forEach(function(track) {
  1069. var sender = pc.getSenders().find(function(s) {
  1070. return s.track === track;
  1071. });
  1072. if (sender) {
  1073. pc.removeTrack(sender);
  1074. }
  1075. });
  1076. };
  1077. RTCPeerConnection.prototype.getSenders = function() {
  1078. return this.transceivers.filter(function(transceiver) {
  1079. return !!transceiver.rtpSender;
  1080. })
  1081. .map(function(transceiver) {
  1082. return transceiver.rtpSender;
  1083. });
  1084. };
  1085. RTCPeerConnection.prototype.getReceivers = function() {
  1086. return this.transceivers.filter(function(transceiver) {
  1087. return !!transceiver.rtpReceiver;
  1088. })
  1089. .map(function(transceiver) {
  1090. return transceiver.rtpReceiver;
  1091. });
  1092. };
  1093. RTCPeerConnection.prototype._createIceGatherer = function(sdpMLineIndex,
  1094. usingBundle) {
  1095. var pc = this;
  1096. if (usingBundle && sdpMLineIndex > 0) {
  1097. return this.transceivers[0].iceGatherer;
  1098. } else if (this._iceGatherers.length) {
  1099. return this._iceGatherers.shift();
  1100. }
  1101. var iceGatherer = new window.RTCIceGatherer({
  1102. iceServers: this._config.iceServers,
  1103. gatherPolicy: this._config.iceTransportPolicy
  1104. });
  1105. Object.defineProperty(iceGatherer, 'state',
  1106. {value: 'new', writable: true}
  1107. );
  1108. this.transceivers[sdpMLineIndex].bufferedCandidateEvents = [];
  1109. this.transceivers[sdpMLineIndex].bufferCandidates = function(event) {
  1110. var end = !event.candidate || Object.keys(event.candidate).length === 0;
  1111. // polyfill since RTCIceGatherer.state is not implemented in
  1112. // Edge 10547 yet.
  1113. iceGatherer.state = end ? 'completed' : 'gathering';
  1114. if (pc.transceivers[sdpMLineIndex].bufferedCandidateEvents !== null) {
  1115. pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event);
  1116. }
  1117. };
  1118. iceGatherer.addEventListener('localcandidate',
  1119. this.transceivers[sdpMLineIndex].bufferCandidates);
  1120. return iceGatherer;
  1121. };
  1122. // start gathering from an RTCIceGatherer.
  1123. RTCPeerConnection.prototype._gather = function(mid, sdpMLineIndex) {
  1124. var pc = this;
  1125. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  1126. if (iceGatherer.onlocalcandidate) {
  1127. return;
  1128. }
  1129. var bufferedCandidateEvents =
  1130. this.transceivers[sdpMLineIndex].bufferedCandidateEvents;
  1131. this.transceivers[sdpMLineIndex].bufferedCandidateEvents = null;
  1132. iceGatherer.removeEventListener('localcandidate',
  1133. this.transceivers[sdpMLineIndex].bufferCandidates);
  1134. iceGatherer.onlocalcandidate = function(evt) {
  1135. if (pc.usingBundle && sdpMLineIndex > 0) {
  1136. // if we know that we use bundle we can drop candidates with
  1137. // ѕdpMLineIndex > 0. If we don't do this then our state gets
  1138. // confused since we dispose the extra ice gatherer.
  1139. return;
  1140. }
  1141. var event = new Event('icecandidate');
  1142. event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
  1143. var cand = evt.candidate;
  1144. // Edge emits an empty object for RTCIceCandidateComplete‥
  1145. var end = !cand || Object.keys(cand).length === 0;
  1146. if (end) {
  1147. // polyfill since RTCIceGatherer.state is not implemented in
  1148. // Edge 10547 yet.
  1149. if (iceGatherer.state === 'new' || iceGatherer.state === 'gathering') {
  1150. iceGatherer.state = 'completed';
  1151. }
  1152. } else {
  1153. if (iceGatherer.state === 'new') {
  1154. iceGatherer.state = 'gathering';
  1155. }
  1156. // RTCIceCandidate doesn't have a component, needs to be added
  1157. cand.component = 1;
  1158. var serializedCandidate = SDPUtils.writeCandidate(cand);
  1159. event.candidate = Object.assign(event.candidate,
  1160. SDPUtils.parseCandidate(serializedCandidate));
  1161. event.candidate.candidate = serializedCandidate;
  1162. }
  1163. // update local description.
  1164. var sections = SDPUtils.getMediaSections(pc.localDescription.sdp);
  1165. if (!end) {
  1166. sections[event.candidate.sdpMLineIndex] +=
  1167. 'a=' + event.candidate.candidate + '\r\n';
  1168. } else {
  1169. sections[event.candidate.sdpMLineIndex] +=
  1170. 'a=end-of-candidates\r\n';
  1171. }
  1172. pc.localDescription.sdp =
  1173. SDPUtils.getDescription(pc.localDescription.sdp) +
  1174. sections.join('');
  1175. var complete = pc.transceivers.every(function(transceiver) {
  1176. return transceiver.iceGatherer &&
  1177. transceiver.iceGatherer.state === 'completed';
  1178. });
  1179. if (pc.iceGatheringState !== 'gathering') {
  1180. pc.iceGatheringState = 'gathering';
  1181. pc._emitGatheringStateChange();
  1182. }
  1183. // Emit candidate. Also emit null candidate when all gatherers are
  1184. // complete.
  1185. if (!end) {
  1186. pc._dispatchEvent('icecandidate', event);
  1187. }
  1188. if (complete) {
  1189. pc._dispatchEvent('icecandidate', new Event('icecandidate'));
  1190. pc.iceGatheringState = 'complete';
  1191. pc._emitGatheringStateChange();
  1192. }
  1193. };
  1194. // emit already gathered candidates.
  1195. window.setTimeout(function() {
  1196. bufferedCandidateEvents.forEach(function(e) {
  1197. iceGatherer.onlocalcandidate(e);
  1198. });
  1199. }, 0);
  1200. };
  1201. // Create ICE transport and DTLS transport.
  1202. RTCPeerConnection.prototype._createIceAndDtlsTransports = function() {
  1203. var pc = this;
  1204. var iceTransport = new window.RTCIceTransport(null);
  1205. iceTransport.onicestatechange = function() {
  1206. pc._updateIceConnectionState();
  1207. pc._updateConnectionState();
  1208. };
  1209. var dtlsTransport = new window.RTCDtlsTransport(iceTransport);
  1210. dtlsTransport.ondtlsstatechange = function() {
  1211. pc._updateConnectionState();
  1212. };
  1213. dtlsTransport.onerror = function() {
  1214. // onerror does not set state to failed by itself.
  1215. Object.defineProperty(dtlsTransport, 'state',
  1216. {value: 'failed', writable: true});
  1217. pc._updateConnectionState();
  1218. };
  1219. return {
  1220. iceTransport: iceTransport,
  1221. dtlsTransport: dtlsTransport
  1222. };
  1223. };
  1224. // Destroy ICE gatherer, ICE transport and DTLS transport.
  1225. // Without triggering the callbacks.
  1226. RTCPeerConnection.prototype._disposeIceAndDtlsTransports = function(
  1227. sdpMLineIndex) {
  1228. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  1229. if (iceGatherer) {
  1230. delete iceGatherer.onlocalcandidate;
  1231. delete this.transceivers[sdpMLineIndex].iceGatherer;
  1232. }
  1233. var iceTransport = this.transceivers[sdpMLineIndex].iceTransport;
  1234. if (iceTransport) {
  1235. delete iceTransport.onicestatechange;
  1236. delete this.transceivers[sdpMLineIndex].iceTransport;
  1237. }
  1238. var dtlsTransport = this.transceivers[sdpMLineIndex].dtlsTransport;
  1239. if (dtlsTransport) {
  1240. delete dtlsTransport.ondtlsstatechange;
  1241. delete dtlsTransport.onerror;
  1242. delete this.transceivers[sdpMLineIndex].dtlsTransport;
  1243. }
  1244. };
  1245. // Start the RTP Sender and Receiver for a transceiver.
  1246. RTCPeerConnection.prototype._transceive = function(transceiver,
  1247. send, recv) {
  1248. var params = getCommonCapabilities(transceiver.localCapabilities,
  1249. transceiver.remoteCapabilities);
  1250. if (send && transceiver.rtpSender) {
  1251. params.encodings = transceiver.sendEncodingParameters;
  1252. params.rtcp = {
  1253. cname: SDPUtils.localCName,
  1254. compound: transceiver.rtcpParameters.compound
  1255. };
  1256. if (transceiver.recvEncodingParameters.length) {
  1257. params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
  1258. }
  1259. transceiver.rtpSender.send(params);
  1260. }
  1261. if (recv && transceiver.rtpReceiver && params.codecs.length > 0) {
  1262. // remove RTX field in Edge 14942
  1263. if (transceiver.kind === 'video'
  1264. && transceiver.recvEncodingParameters
  1265. && edgeVersion < 15019) {
  1266. transceiver.recvEncodingParameters.forEach(function(p) {
  1267. delete p.rtx;
  1268. });
  1269. }
  1270. if (transceiver.recvEncodingParameters.length) {
  1271. params.encodings = transceiver.recvEncodingParameters;
  1272. } else {
  1273. params.encodings = [{}];
  1274. }
  1275. params.rtcp = {
  1276. compound: transceiver.rtcpParameters.compound
  1277. };
  1278. if (transceiver.rtcpParameters.cname) {
  1279. params.rtcp.cname = transceiver.rtcpParameters.cname;
  1280. }
  1281. if (transceiver.sendEncodingParameters.length) {
  1282. params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
  1283. }
  1284. transceiver.rtpReceiver.receive(params);
  1285. }
  1286. };
  1287. RTCPeerConnection.prototype.setLocalDescription = function(description) {
  1288. var pc = this;
  1289. // Note: pranswer is not supported.
  1290. if (['offer', 'answer'].indexOf(description.type) === -1) {
  1291. return Promise.reject(makeError('TypeError',
  1292. 'Unsupported type "' + description.type + '"'));
  1293. }
  1294. if (!isActionAllowedInSignalingState('setLocalDescription',
  1295. description.type, pc.signalingState) || pc._isClosed) {
  1296. return Promise.reject(makeError('InvalidStateError',
  1297. 'Can not set local ' + description.type +
  1298. ' in state ' + pc.signalingState));
  1299. }
  1300. var sections;
  1301. var sessionpart;
  1302. if (description.type === 'offer') {
  1303. // VERY limited support for SDP munging. Limited to:
  1304. // * changing the order of codecs
  1305. sections = SDPUtils.splitSections(description.sdp);
  1306. sessionpart = sections.shift();
  1307. sections.forEach(function(mediaSection, sdpMLineIndex) {
  1308. var caps = SDPUtils.parseRtpParameters(mediaSection);
  1309. pc.transceivers[sdpMLineIndex].localCapabilities = caps;
  1310. });
  1311. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  1312. pc._gather(transceiver.mid, sdpMLineIndex);
  1313. });
  1314. } else if (description.type === 'answer') {
  1315. sections = SDPUtils.splitSections(pc.remoteDescription.sdp);
  1316. sessionpart = sections.shift();
  1317. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  1318. 'a=ice-lite').length > 0;
  1319. sections.forEach(function(mediaSection, sdpMLineIndex) {
  1320. var transceiver = pc.transceivers[sdpMLineIndex];
  1321. var iceGatherer = transceiver.iceGatherer;
  1322. var iceTransport = transceiver.iceTransport;
  1323. var dtlsTransport = transceiver.dtlsTransport;
  1324. var localCapabilities = transceiver.localCapabilities;
  1325. var remoteCapabilities = transceiver.remoteCapabilities;
  1326. // treat bundle-only as not-rejected.
  1327. var rejected = SDPUtils.isRejected(mediaSection) &&
  1328. SDPUtils.matchPrefix(mediaSection, 'a=bundle-only').length === 0;
  1329. if (!rejected && !transceiver.rejected) {
  1330. var remoteIceParameters = SDPUtils.getIceParameters(
  1331. mediaSection, sessionpart);
  1332. var remoteDtlsParameters = SDPUtils.getDtlsParameters(
  1333. mediaSection, sessionpart);
  1334. if (isIceLite) {
  1335. remoteDtlsParameters.role = 'server';
  1336. }
  1337. if (!pc.usingBundle || sdpMLineIndex === 0) {
  1338. pc._gather(transceiver.mid, sdpMLineIndex);
  1339. if (iceTransport.state === 'new') {
  1340. iceTransport.start(iceGatherer, remoteIceParameters,
  1341. isIceLite ? 'controlling' : 'controlled');
  1342. }
  1343. if (dtlsTransport.state === 'new') {
  1344. dtlsTransport.start(remoteDtlsParameters);
  1345. }
  1346. }
  1347. // Calculate intersection of capabilities.
  1348. var params = getCommonCapabilities(localCapabilities,
  1349. remoteCapabilities);
  1350. // Start the RTCRtpSender. The RTCRtpReceiver for this
  1351. // transceiver has already been started in setRemoteDescription.
  1352. pc._transceive(transceiver,
  1353. params.codecs.length > 0,
  1354. false);
  1355. }
  1356. });
  1357. }
  1358. pc.localDescription = {
  1359. type: description.type,
  1360. sdp: description.sdp
  1361. };
  1362. if (description.type === 'offer') {
  1363. pc._updateSignalingState('have-local-offer');
  1364. } else {
  1365. pc._updateSignalingState('stable');
  1366. }
  1367. return Promise.resolve();
  1368. };
  1369. RTCPeerConnection.prototype.setRemoteDescription = function(description) {
  1370. var pc = this;
  1371. // Note: pranswer is not supported.
  1372. if (['offer', 'answer'].indexOf(description.type) === -1) {
  1373. return Promise.reject(makeError('TypeError',
  1374. 'Unsupported type "' + description.type + '"'));
  1375. }
  1376. if (!isActionAllowedInSignalingState('setRemoteDescription',
  1377. description.type, pc.signalingState) || pc._isClosed) {
  1378. return Promise.reject(makeError('InvalidStateError',
  1379. 'Can not set remote ' + description.type +
  1380. ' in state ' + pc.signalingState));
  1381. }
  1382. var streams = {};
  1383. pc.remoteStreams.forEach(function(stream) {
  1384. streams[stream.id] = stream;
  1385. });
  1386. var receiverList = [];
  1387. var sections = SDPUtils.splitSections(description.sdp);
  1388. var sessionpart = sections.shift();
  1389. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  1390. 'a=ice-lite').length > 0;
  1391. var usingBundle = SDPUtils.matchPrefix(sessionpart,
  1392. 'a=group:BUNDLE ').length > 0;
  1393. pc.usingBundle = usingBundle;
  1394. var iceOptions = SDPUtils.matchPrefix(sessionpart,
  1395. 'a=ice-options:')[0];
  1396. if (iceOptions) {
  1397. pc.canTrickleIceCandidates = iceOptions.substr(14).split(' ')
  1398. .indexOf('trickle') >= 0;
  1399. } else {
  1400. pc.canTrickleIceCandidates = false;
  1401. }
  1402. sections.forEach(function(mediaSection, sdpMLineIndex) {
  1403. var lines = SDPUtils.splitLines(mediaSection);
  1404. var kind = SDPUtils.getKind(mediaSection);
  1405. // treat bundle-only as not-rejected.
  1406. var rejected = SDPUtils.isRejected(mediaSection) &&
  1407. SDPUtils.matchPrefix(mediaSection, 'a=bundle-only').length === 0;
  1408. var protocol = lines[0].substr(2).split(' ')[2];
  1409. var direction = SDPUtils.getDirection(mediaSection, sessionpart);
  1410. var remoteMsid = SDPUtils.parseMsid(mediaSection);
  1411. var mid = SDPUtils.getMid(mediaSection) || SDPUtils.generateIdentifier();
  1412. // Reject datachannels which are not implemented yet.
  1413. if ((kind === 'application' && protocol === 'DTLS/SCTP') || rejected) {
  1414. // TODO: this is dangerous in the case where a non-rejected m-line
  1415. // becomes rejected.
  1416. pc.transceivers[sdpMLineIndex] = {
  1417. mid: mid,
  1418. kind: kind,
  1419. rejected: true
  1420. };
  1421. return;
  1422. }
  1423. if (!rejected && pc.transceivers[sdpMLineIndex] &&
  1424. pc.transceivers[sdpMLineIndex].rejected) {
  1425. // recycle a rejected transceiver.
  1426. pc.transceivers[sdpMLineIndex] = pc._createTransceiver(kind, true);
  1427. }
  1428. var transceiver;
  1429. var iceGatherer;
  1430. var iceTransport;
  1431. var dtlsTransport;
  1432. var rtpReceiver;
  1433. var sendEncodingParameters;
  1434. var recvEncodingParameters;
  1435. var localCapabilities;
  1436. var track;
  1437. // FIXME: ensure the mediaSection has rtcp-mux set.
  1438. var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection);
  1439. var remoteIceParameters;
  1440. var remoteDtlsParameters;
  1441. if (!rejected) {
  1442. remoteIceParameters = SDPUtils.getIceParameters(mediaSection,
  1443. sessionpart);
  1444. remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection,
  1445. sessionpart);
  1446. remoteDtlsParameters.role = 'client';
  1447. }
  1448. recvEncodingParameters =
  1449. SDPUtils.parseRtpEncodingParameters(mediaSection);
  1450. var rtcpParameters = SDPUtils.parseRtcpParameters(mediaSection);
  1451. var isComplete = SDPUtils.matchPrefix(mediaSection,
  1452. 'a=end-of-candidates', sessionpart).length > 0;
  1453. var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
  1454. .map(function(cand) {
  1455. return SDPUtils.parseCandidate(cand);
  1456. })
  1457. .filter(function(cand) {
  1458. return cand.component === 1;
  1459. });
  1460. // Check if we can use BUNDLE and dispose transports.
  1461. if ((description.type === 'offer' || description.type === 'answer') &&
  1462. !rejected && usingBundle && sdpMLineIndex > 0 &&
  1463. pc.transceivers[sdpMLineIndex]) {
  1464. pc._disposeIceAndDtlsTransports(sdpMLineIndex);
  1465. pc.transceivers[sdpMLineIndex].iceGatherer =
  1466. pc.transceivers[0].iceGatherer;
  1467. pc.transceivers[sdpMLineIndex].iceTransport =
  1468. pc.transceivers[0].iceTransport;
  1469. pc.transceivers[sdpMLineIndex].dtlsTransport =
  1470. pc.transceivers[0].dtlsTransport;
  1471. if (pc.transceivers[sdpMLineIndex].rtpSender) {
  1472. pc.transceivers[sdpMLineIndex].rtpSender.setTransport(
  1473. pc.transceivers[0].dtlsTransport);
  1474. }
  1475. if (pc.transceivers[sdpMLineIndex].rtpReceiver) {
  1476. pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(
  1477. pc.transceivers[0].dtlsTransport);
  1478. }
  1479. }
  1480. if (description.type === 'offer' && !rejected) {
  1481. transceiver = pc.transceivers[sdpMLineIndex] ||
  1482. pc._createTransceiver(kind);
  1483. transceiver.mid = mid;
  1484. if (!transceiver.iceGatherer) {
  1485. transceiver.iceGatherer = pc._createIceGatherer(sdpMLineIndex,
  1486. usingBundle);
  1487. }
  1488. if (cands.length && transceiver.iceTransport.state === 'new') {
  1489. if (isComplete && (!usingBundle || sdpMLineIndex === 0)) {
  1490. transceiver.iceTransport.setRemoteCandidates(cands);
  1491. } else {
  1492. cands.forEach(function(candidate) {
  1493. maybeAddCandidate(transceiver.iceTransport, candidate);
  1494. });
  1495. }
  1496. }
  1497. localCapabilities = window.RTCRtpReceiver.getCapabilities(kind);
  1498. // filter RTX until additional stuff needed for RTX is implemented
  1499. // in adapter.js
  1500. if (edgeVersion < 15019) {
  1501. localCapabilities.codecs = localCapabilities.codecs.filter(
  1502. function(codec) {
  1503. return codec.name !== 'rtx';
  1504. });
  1505. }
  1506. sendEncodingParameters = transceiver.sendEncodingParameters || [{
  1507. ssrc: (2 * sdpMLineIndex + 2) * 1001
  1508. }];
  1509. // TODO: rewrite to use http://w3c.github.io/webrtc-pc/#set-associated-remote-streams
  1510. var isNewTrack = false;
  1511. if (direction === 'sendrecv' || direction === 'sendonly') {
  1512. isNewTrack = !transceiver.rtpReceiver;
  1513. rtpReceiver = transceiver.rtpReceiver ||
  1514. new window.RTCRtpReceiver(transceiver.dtlsTransport, kind);
  1515. if (isNewTrack) {
  1516. var stream;
  1517. track = rtpReceiver.track;
  1518. // FIXME: does not work with Plan B.
  1519. if (remoteMsid && remoteMsid.stream === '-') {
  1520. // no-op. a stream id of '-' means: no associated stream.
  1521. } else if (remoteMsid) {
  1522. if (!streams[remoteMsid.stream]) {
  1523. streams[remoteMsid.stream] = new window.MediaStream();
  1524. Object.defineProperty(streams[remoteMsid.stream], 'id', {
  1525. get: function() {
  1526. return remoteMsid.stream;
  1527. }
  1528. });
  1529. }
  1530. Object.defineProperty(track, 'id', {
  1531. get: function() {
  1532. return remoteMsid.track;
  1533. }
  1534. });
  1535. stream = streams[remoteMsid.stream];
  1536. } else {
  1537. if (!streams.default) {
  1538. streams.default = new window.MediaStream();
  1539. }
  1540. stream = streams.default;
  1541. }
  1542. if (stream) {
  1543. addTrackToStreamAndFireEvent(track, stream);
  1544. transceiver.associatedRemoteMediaStreams.push(stream);
  1545. }
  1546. receiverList.push([track, rtpReceiver, stream]);
  1547. }
  1548. } else if (transceiver.rtpReceiver && transceiver.rtpReceiver.track) {
  1549. transceiver.associatedRemoteMediaStreams.forEach(function(s) {
  1550. var nativeTrack = s.getTracks().find(function(t) {
  1551. return t.id === transceiver.rtpReceiver.track.id;
  1552. });
  1553. if (nativeTrack) {
  1554. removeTrackFromStreamAndFireEvent(nativeTrack, s);
  1555. }
  1556. });
  1557. transceiver.associatedRemoteMediaStreams = [];
  1558. }
  1559. transceiver.localCapabilities = localCapabilities;
  1560. transceiver.remoteCapabilities = remoteCapabilities;
  1561. transceiver.rtpReceiver = rtpReceiver;
  1562. transceiver.rtcpParameters = rtcpParameters;
  1563. transceiver.sendEncodingParameters = sendEncodingParameters;
  1564. transceiver.recvEncodingParameters = recvEncodingParameters;
  1565. // Start the RTCRtpReceiver now. The RTPSender is started in
  1566. // setLocalDescription.
  1567. pc._transceive(pc.transceivers[sdpMLineIndex],
  1568. false,
  1569. isNewTrack);
  1570. } else if (description.type === 'answer' && !rejected) {
  1571. transceiver = pc.transceivers[sdpMLineIndex];
  1572. iceGatherer = transceiver.iceGatherer;
  1573. iceTransport = transceiver.iceTransport;
  1574. dtlsTransport = transceiver.dtlsTransport;
  1575. rtpReceiver = transceiver.rtpReceiver;
  1576. sendEncodingParameters = transceiver.sendEncodingParameters;
  1577. localCapabilities = transceiver.localCapabilities;
  1578. pc.transceivers[sdpMLineIndex].recvEncodingParameters =
  1579. recvEncodingParameters;
  1580. pc.transceivers[sdpMLineIndex].remoteCapabilities =
  1581. remoteCapabilities;
  1582. pc.transceivers[sdpMLineIndex].rtcpParameters = rtcpParameters;
  1583. if (cands.length && iceTransport.state === 'new') {
  1584. if ((isIceLite || isComplete) &&
  1585. (!usingBundle || sdpMLineIndex === 0)) {
  1586. iceTransport.setRemoteCandidates(cands);
  1587. } else {
  1588. cands.forEach(function(candidate) {
  1589. maybeAddCandidate(transceiver.iceTransport, candidate);
  1590. });
  1591. }
  1592. }
  1593. if (!usingBundle || sdpMLineIndex === 0) {
  1594. if (iceTransport.state === 'new') {
  1595. iceTransport.start(iceGatherer, remoteIceParameters,
  1596. 'controlling');
  1597. }
  1598. if (dtlsTransport.state === 'new') {
  1599. dtlsTransport.start(remoteDtlsParameters);
  1600. }
  1601. }
  1602. pc._transceive(transceiver,
  1603. direction === 'sendrecv' || direction === 'recvonly',
  1604. direction === 'sendrecv' || direction === 'sendonly');
  1605. // TODO: rewrite to use http://w3c.github.io/webrtc-pc/#set-associated-remote-streams
  1606. if (rtpReceiver &&
  1607. (direction === 'sendrecv' || direction === 'sendonly')) {
  1608. track = rtpReceiver.track;
  1609. if (remoteMsid) {
  1610. if (!streams[remoteMsid.stream]) {
  1611. streams[remoteMsid.stream] = new window.MediaStream();
  1612. }
  1613. addTrackToStreamAndFireEvent(track, streams[remoteMsid.stream]);
  1614. receiverList.push([track, rtpReceiver, streams[remoteMsid.stream]]);
  1615. } else {
  1616. if (!streams.default) {
  1617. streams.default = new window.MediaStream();
  1618. }
  1619. addTrackToStreamAndFireEvent(track, streams.default);
  1620. receiverList.push([track, rtpReceiver, streams.default]);
  1621. }
  1622. } else {
  1623. // FIXME: actually the receiver should be created later.
  1624. delete transceiver.rtpReceiver;
  1625. }
  1626. }
  1627. });
  1628. if (pc._dtlsRole === undefined) {
  1629. pc._dtlsRole = description.type === 'offer' ? 'active' : 'passive';
  1630. }
  1631. pc.remoteDescription = {
  1632. type: description.type,
  1633. sdp: description.sdp
  1634. };
  1635. if (description.type === 'offer') {
  1636. pc._updateSignalingState('have-remote-offer');
  1637. } else {
  1638. pc._updateSignalingState('stable');
  1639. }
  1640. Object.keys(streams).forEach(function(sid) {
  1641. var stream = streams[sid];
  1642. if (stream.getTracks().length) {
  1643. if (pc.remoteStreams.indexOf(stream) === -1) {
  1644. pc.remoteStreams.push(stream);
  1645. var event = new Event('addstream');
  1646. event.stream = stream;
  1647. window.setTimeout(function() {
  1648. pc._dispatchEvent('addstream', event);
  1649. });
  1650. }
  1651. receiverList.forEach(function(item) {
  1652. var track = item[0];
  1653. var receiver = item[1];
  1654. if (stream.id !== item[2].id) {
  1655. return;
  1656. }
  1657. fireAddTrack(pc, track, receiver, [stream]);
  1658. });
  1659. }
  1660. });
  1661. receiverList.forEach(function(item) {
  1662. if (item[2]) {
  1663. return;
  1664. }
  1665. fireAddTrack(pc, item[0], item[1], []);
  1666. });
  1667. // check whether addIceCandidate({}) was called within four seconds after
  1668. // setRemoteDescription.
  1669. window.setTimeout(function() {
  1670. if (!(pc && pc.transceivers)) {
  1671. return;
  1672. }
  1673. pc.transceivers.forEach(function(transceiver) {
  1674. if (transceiver.iceTransport &&
  1675. transceiver.iceTransport.state === 'new' &&
  1676. transceiver.iceTransport.getRemoteCandidates().length > 0) {
  1677. console.warn('Timeout for addRemoteCandidate. Consider sending ' +
  1678. 'an end-of-candidates notification');
  1679. transceiver.iceTransport.addRemoteCandidate({});
  1680. }
  1681. });
  1682. }, 4000);
  1683. return Promise.resolve();
  1684. };
  1685. RTCPeerConnection.prototype.close = function() {
  1686. this.transceivers.forEach(function(transceiver) {
  1687. /* not yet
  1688. if (transceiver.iceGatherer) {
  1689. transceiver.iceGatherer.close();
  1690. }
  1691. */
  1692. if (transceiver.iceTransport) {
  1693. transceiver.iceTransport.stop();
  1694. }
  1695. if (transceiver.dtlsTransport) {
  1696. transceiver.dtlsTransport.stop();
  1697. }
  1698. if (transceiver.rtpSender) {
  1699. transceiver.rtpSender.stop();
  1700. }
  1701. if (transceiver.rtpReceiver) {
  1702. transceiver.rtpReceiver.stop();
  1703. }
  1704. });
  1705. // FIXME: clean up tracks, local streams, remote streams, etc
  1706. this._isClosed = true;
  1707. this._updateSignalingState('closed');
  1708. };
  1709. // Update the signaling state.
  1710. RTCPeerConnection.prototype._updateSignalingState = function(newState) {
  1711. this.signalingState = newState;
  1712. var event = new Event('signalingstatechange');
  1713. this._dispatchEvent('signalingstatechange', event);
  1714. };
  1715. // Determine whether to fire the negotiationneeded event.
  1716. RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() {
  1717. var pc = this;
  1718. if (this.signalingState !== 'stable' || this.needNegotiation === true) {
  1719. return;
  1720. }
  1721. this.needNegotiation = true;
  1722. window.setTimeout(function() {
  1723. if (pc.needNegotiation) {
  1724. pc.needNegotiation = false;
  1725. var event = new Event('negotiationneeded');
  1726. pc._dispatchEvent('negotiationneeded', event);
  1727. }
  1728. }, 0);
  1729. };
  1730. // Update the ice connection state.
  1731. RTCPeerConnection.prototype._updateIceConnectionState = function() {
  1732. var newState;
  1733. var states = {
  1734. 'new': 0,
  1735. closed: 0,
  1736. checking: 0,
  1737. connected: 0,
  1738. completed: 0,
  1739. disconnected: 0,
  1740. failed: 0
  1741. };
  1742. this.transceivers.forEach(function(transceiver) {
  1743. states[transceiver.iceTransport.state]++;
  1744. });
  1745. newState = 'new';
  1746. if (states.failed > 0) {
  1747. newState = 'failed';
  1748. } else if (states.checking > 0) {
  1749. newState = 'checking';
  1750. } else if (states.disconnected > 0) {
  1751. newState = 'disconnected';
  1752. } else if (states.new > 0) {
  1753. newState = 'new';
  1754. } else if (states.connected > 0) {
  1755. newState = 'connected';
  1756. } else if (states.completed > 0) {
  1757. newState = 'completed';
  1758. }
  1759. if (newState !== this.iceConnectionState) {
  1760. this.iceConnectionState = newState;
  1761. var event = new Event('iceconnectionstatechange');
  1762. this._dispatchEvent('iceconnectionstatechange', event);
  1763. }
  1764. };
  1765. // Update the connection state.
  1766. RTCPeerConnection.prototype._updateConnectionState = function() {
  1767. var newState;
  1768. var states = {
  1769. 'new': 0,
  1770. closed: 0,
  1771. connecting: 0,
  1772. connected: 0,
  1773. completed: 0,
  1774. disconnected: 0,
  1775. failed: 0
  1776. };
  1777. this.transceivers.forEach(function(transceiver) {
  1778. states[transceiver.iceTransport.state]++;
  1779. states[transceiver.dtlsTransport.state]++;
  1780. });
  1781. // ICETransport.completed and connected are the same for this purpose.
  1782. states.connected += states.completed;
  1783. newState = 'new';
  1784. if (states.failed > 0) {
  1785. newState = 'failed';
  1786. } else if (states.connecting > 0) {
  1787. newState = 'connecting';
  1788. } else if (states.disconnected > 0) {
  1789. newState = 'disconnected';
  1790. } else if (states.new > 0) {
  1791. newState = 'new';
  1792. } else if (states.connected > 0) {
  1793. newState = 'connected';
  1794. }
  1795. if (newState !== this.connectionState) {
  1796. this.connectionState = newState;
  1797. var event = new Event('connectionstatechange');
  1798. this._dispatchEvent('connectionstatechange', event);
  1799. }
  1800. };
  1801. RTCPeerConnection.prototype.createOffer = function() {
  1802. var pc = this;
  1803. if (pc._isClosed) {
  1804. return Promise.reject(makeError('InvalidStateError',
  1805. 'Can not call createOffer after close'));
  1806. }
  1807. var numAudioTracks = pc.transceivers.filter(function(t) {
  1808. return t.kind === 'audio';
  1809. }).length;
  1810. var numVideoTracks = pc.transceivers.filter(function(t) {
  1811. return t.kind === 'video';
  1812. }).length;
  1813. // Determine number of audio and video tracks we need to send/recv.
  1814. var offerOptions = arguments[0];
  1815. if (offerOptions) {
  1816. // Reject Chrome legacy constraints.
  1817. if (offerOptions.mandatory || offerOptions.optional) {
  1818. throw new TypeError(
  1819. 'Legacy mandatory/optional constraints not supported.');
  1820. }
  1821. if (offerOptions.offerToReceiveAudio !== undefined) {
  1822. if (offerOptions.offerToReceiveAudio === true) {
  1823. numAudioTracks = 1;
  1824. } else if (offerOptions.offerToReceiveAudio === false) {
  1825. numAudioTracks = 0;
  1826. } else {
  1827. numAudioTracks = offerOptions.offerToReceiveAudio;
  1828. }
  1829. }
  1830. if (offerOptions.offerToReceiveVideo !== undefined) {
  1831. if (offerOptions.offerToReceiveVideo === true) {
  1832. numVideoTracks = 1;
  1833. } else if (offerOptions.offerToReceiveVideo === false) {
  1834. numVideoTracks = 0;
  1835. } else {
  1836. numVideoTracks = offerOptions.offerToReceiveVideo;
  1837. }
  1838. }
  1839. }
  1840. pc.transceivers.forEach(function(transceiver) {
  1841. if (transceiver.kind === 'audio') {
  1842. numAudioTracks--;
  1843. if (numAudioTracks < 0) {
  1844. transceiver.wantReceive = false;
  1845. }
  1846. } else if (transceiver.kind === 'video') {
  1847. numVideoTracks--;
  1848. if (numVideoTracks < 0) {
  1849. transceiver.wantReceive = false;
  1850. }
  1851. }
  1852. });
  1853. // Create M-lines for recvonly streams.
  1854. while (numAudioTracks > 0 || numVideoTracks > 0) {
  1855. if (numAudioTracks > 0) {
  1856. pc._createTransceiver('audio');
  1857. numAudioTracks--;
  1858. }
  1859. if (numVideoTracks > 0) {
  1860. pc._createTransceiver('video');
  1861. numVideoTracks--;
  1862. }
  1863. }
  1864. var sdp = SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,
  1865. pc._sdpSessionVersion++);
  1866. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  1867. // For each track, create an ice gatherer, ice transport,
  1868. // dtls transport, potentially rtpsender and rtpreceiver.
  1869. var track = transceiver.track;
  1870. var kind = transceiver.kind;
  1871. var mid = transceiver.mid || SDPUtils.generateIdentifier();
  1872. transceiver.mid = mid;
  1873. if (!transceiver.iceGatherer) {
  1874. transceiver.iceGatherer = pc._createIceGatherer(sdpMLineIndex,
  1875. pc.usingBundle);
  1876. }
  1877. var localCapabilities = window.RTCRtpSender.getCapabilities(kind);
  1878. // filter RTX until additional stuff needed for RTX is implemented
  1879. // in adapter.js
  1880. if (edgeVersion < 15019) {
  1881. localCapabilities.codecs = localCapabilities.codecs.filter(
  1882. function(codec) {
  1883. return codec.name !== 'rtx';
  1884. });
  1885. }
  1886. localCapabilities.codecs.forEach(function(codec) {
  1887. // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
  1888. // by adding level-asymmetry-allowed=1
  1889. if (codec.name === 'H264' &&
  1890. codec.parameters['level-asymmetry-allowed'] === undefined) {
  1891. codec.parameters['level-asymmetry-allowed'] = '1';
  1892. }
  1893. // for subsequent offers, we might have to re-use the payload
  1894. // type of the last offer.
  1895. if (transceiver.remoteCapabilities &&
  1896. transceiver.remoteCapabilities.codecs) {
  1897. transceiver.remoteCapabilities.codecs.forEach(function(remoteCodec) {
  1898. if (codec.name.toLowerCase() === remoteCodec.name.toLowerCase() &&
  1899. codec.clockRate === remoteCodec.clockRate) {
  1900. codec.preferredPayloadType = remoteCodec.payloadType;
  1901. }
  1902. });
  1903. }
  1904. });
  1905. localCapabilities.headerExtensions.forEach(function(hdrExt) {
  1906. var remoteExtensions = transceiver.remoteCapabilities &&
  1907. transceiver.remoteCapabilities.headerExtensions || [];
  1908. remoteExtensions.forEach(function(rHdrExt) {
  1909. if (hdrExt.uri === rHdrExt.uri) {
  1910. hdrExt.id = rHdrExt.id;
  1911. }
  1912. });
  1913. });
  1914. // generate an ssrc now, to be used later in rtpSender.send
  1915. var sendEncodingParameters = transceiver.sendEncodingParameters || [{
  1916. ssrc: (2 * sdpMLineIndex + 1) * 1001
  1917. }];
  1918. if (track) {
  1919. // add RTX
  1920. if (edgeVersion >= 15019 && kind === 'video' &&
  1921. !sendEncodingParameters[0].rtx) {
  1922. sendEncodingParameters[0].rtx = {
  1923. ssrc: sendEncodingParameters[0].ssrc + 1
  1924. };
  1925. }
  1926. }
  1927. if (transceiver.wantReceive) {
  1928. transceiver.rtpReceiver = new window.RTCRtpReceiver(
  1929. transceiver.dtlsTransport, kind);
  1930. }
  1931. transceiver.localCapabilities = localCapabilities;
  1932. transceiver.sendEncodingParameters = sendEncodingParameters;
  1933. });
  1934. // always offer BUNDLE and dispose on return if not supported.
  1935. if (pc._config.bundlePolicy !== 'max-compat') {
  1936. sdp += 'a=group:BUNDLE ' + pc.transceivers.map(function(t) {
  1937. return t.mid;
  1938. }).join(' ') + '\r\n';
  1939. }
  1940. sdp += 'a=ice-options:trickle\r\n';
  1941. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  1942. sdp += writeMediaSection(transceiver, transceiver.localCapabilities,
  1943. 'offer', transceiver.stream, pc._dtlsRole);
  1944. sdp += 'a=rtcp-rsize\r\n';
  1945. if (transceiver.iceGatherer && pc.iceGatheringState !== 'new' &&
  1946. (sdpMLineIndex === 0 || !pc.usingBundle)) {
  1947. transceiver.iceGatherer.getLocalCandidates().forEach(function(cand) {
  1948. cand.component = 1;
  1949. sdp += 'a=' + SDPUtils.writeCandidate(cand) + '\r\n';
  1950. });
  1951. if (transceiver.iceGatherer.state === 'completed') {
  1952. sdp += 'a=end-of-candidates\r\n';
  1953. }
  1954. }
  1955. });
  1956. var desc = new window.RTCSessionDescription({
  1957. type: 'offer',
  1958. sdp: sdp
  1959. });
  1960. return Promise.resolve(desc);
  1961. };
  1962. RTCPeerConnection.prototype.createAnswer = function() {
  1963. var pc = this;
  1964. if (pc._isClosed) {
  1965. return Promise.reject(makeError('InvalidStateError',
  1966. 'Can not call createAnswer after close'));
  1967. }
  1968. if (!(pc.signalingState === 'have-remote-offer' ||
  1969. pc.signalingState === 'have-local-pranswer')) {
  1970. return Promise.reject(makeError('InvalidStateError',
  1971. 'Can not call createAnswer in signalingState ' + pc.signalingState));
  1972. }
  1973. var sdp = SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,
  1974. pc._sdpSessionVersion++);
  1975. if (pc.usingBundle) {
  1976. sdp += 'a=group:BUNDLE ' + pc.transceivers.map(function(t) {
  1977. return t.mid;
  1978. }).join(' ') + '\r\n';
  1979. }
  1980. var mediaSectionsInOffer = SDPUtils.getMediaSections(
  1981. pc.remoteDescription.sdp).length;
  1982. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  1983. if (sdpMLineIndex + 1 > mediaSectionsInOffer) {
  1984. return;
  1985. }
  1986. if (transceiver.rejected) {
  1987. if (transceiver.kind === 'application') {
  1988. sdp += 'm=application 0 DTLS/SCTP 5000\r\n';
  1989. } else if (transceiver.kind === 'audio') {
  1990. sdp += 'm=audio 0 UDP/TLS/RTP/SAVPF 0\r\n' +
  1991. 'a=rtpmap:0 PCMU/8000\r\n';
  1992. } else if (transceiver.kind === 'video') {
  1993. sdp += 'm=video 0 UDP/TLS/RTP/SAVPF 120\r\n' +
  1994. 'a=rtpmap:120 VP8/90000\r\n';
  1995. }
  1996. sdp += 'c=IN IP4 0.0.0.0\r\n' +
  1997. 'a=inactive\r\n' +
  1998. 'a=mid:' + transceiver.mid + '\r\n';
  1999. return;
  2000. }
  2001. // FIXME: look at direction.
  2002. if (transceiver.stream) {
  2003. var localTrack;
  2004. if (transceiver.kind === 'audio') {
  2005. localTrack = transceiver.stream.getAudioTracks()[0];
  2006. } else if (transceiver.kind === 'video') {
  2007. localTrack = transceiver.stream.getVideoTracks()[0];
  2008. }
  2009. if (localTrack) {
  2010. // add RTX
  2011. if (edgeVersion >= 15019 && transceiver.kind === 'video' &&
  2012. !transceiver.sendEncodingParameters[0].rtx) {
  2013. transceiver.sendEncodingParameters[0].rtx = {
  2014. ssrc: transceiver.sendEncodingParameters[0].ssrc + 1
  2015. };
  2016. }
  2017. }
  2018. }
  2019. // Calculate intersection of capabilities.
  2020. var commonCapabilities = getCommonCapabilities(
  2021. transceiver.localCapabilities,
  2022. transceiver.remoteCapabilities);
  2023. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  2024. return c.name.toLowerCase() === 'rtx';
  2025. }).length;
  2026. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  2027. delete transceiver.sendEncodingParameters[0].rtx;
  2028. }
  2029. sdp += writeMediaSection(transceiver, commonCapabilities,
  2030. 'answer', transceiver.stream, pc._dtlsRole);
  2031. if (transceiver.rtcpParameters &&
  2032. transceiver.rtcpParameters.reducedSize) {
  2033. sdp += 'a=rtcp-rsize\r\n';
  2034. }
  2035. });
  2036. var desc = new window.RTCSessionDescription({
  2037. type: 'answer',
  2038. sdp: sdp
  2039. });
  2040. return Promise.resolve(desc);
  2041. };
  2042. RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
  2043. var pc = this;
  2044. var sections;
  2045. if (candidate && !(candidate.sdpMLineIndex !== undefined ||
  2046. candidate.sdpMid)) {
  2047. return Promise.reject(new TypeError('sdpMLineIndex or sdpMid required'));
  2048. }
  2049. // TODO: needs to go into ops queue.
  2050. return new Promise(function(resolve, reject) {
  2051. if (!pc.remoteDescription) {
  2052. return reject(makeError('InvalidStateError',
  2053. 'Can not add ICE candidate without a remote description'));
  2054. } else if (!candidate || candidate.candidate === '') {
  2055. for (var j = 0; j < pc.transceivers.length; j++) {
  2056. if (pc.transceivers[j].rejected) {
  2057. continue;
  2058. }
  2059. pc.transceivers[j].iceTransport.addRemoteCandidate({});
  2060. sections = SDPUtils.getMediaSections(pc.remoteDescription.sdp);
  2061. sections[j] += 'a=end-of-candidates\r\n';
  2062. pc.remoteDescription.sdp =
  2063. SDPUtils.getDescription(pc.remoteDescription.sdp) +
  2064. sections.join('');
  2065. if (pc.usingBundle) {
  2066. break;
  2067. }
  2068. }
  2069. } else {
  2070. var sdpMLineIndex = candidate.sdpMLineIndex;
  2071. if (candidate.sdpMid) {
  2072. for (var i = 0; i < pc.transceivers.length; i++) {
  2073. if (pc.transceivers[i].mid === candidate.sdpMid) {
  2074. sdpMLineIndex = i;
  2075. break;
  2076. }
  2077. }
  2078. }
  2079. var transceiver = pc.transceivers[sdpMLineIndex];
  2080. if (transceiver) {
  2081. if (transceiver.rejected) {
  2082. return resolve();
  2083. }
  2084. var cand = Object.keys(candidate.candidate).length > 0 ?
  2085. SDPUtils.parseCandidate(candidate.candidate) : {};
  2086. // Ignore Chrome's invalid candidates since Edge does not like them.
  2087. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
  2088. return resolve();
  2089. }
  2090. // Ignore RTCP candidates, we assume RTCP-MUX.
  2091. if (cand.component && cand.component !== 1) {
  2092. return resolve();
  2093. }
  2094. // when using bundle, avoid adding candidates to the wrong
  2095. // ice transport. And avoid adding candidates added in the SDP.
  2096. if (sdpMLineIndex === 0 || (sdpMLineIndex > 0 &&
  2097. transceiver.iceTransport !== pc.transceivers[0].iceTransport)) {
  2098. if (!maybeAddCandidate(transceiver.iceTransport, cand)) {
  2099. return reject(makeError('OperationError',
  2100. 'Can not add ICE candidate'));
  2101. }
  2102. }
  2103. // update the remoteDescription.
  2104. var candidateString = candidate.candidate.trim();
  2105. if (candidateString.indexOf('a=') === 0) {
  2106. candidateString = candidateString.substr(2);
  2107. }
  2108. sections = SDPUtils.getMediaSections(pc.remoteDescription.sdp);
  2109. sections[sdpMLineIndex] += 'a=' +
  2110. (cand.type ? candidateString : 'end-of-candidates')
  2111. + '\r\n';
  2112. pc.remoteDescription.sdp = sections.join('');
  2113. } else {
  2114. return reject(makeError('OperationError',
  2115. 'Can not add ICE candidate'));
  2116. }
  2117. }
  2118. resolve();
  2119. });
  2120. };
  2121. RTCPeerConnection.prototype.getStats = function() {
  2122. var promises = [];
  2123. this.transceivers.forEach(function(transceiver) {
  2124. ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
  2125. 'dtlsTransport'].forEach(function(method) {
  2126. if (transceiver[method]) {
  2127. promises.push(transceiver[method].getStats());
  2128. }
  2129. });
  2130. });
  2131. var fixStatsType = function(stat) {
  2132. return {
  2133. inboundrtp: 'inbound-rtp',
  2134. outboundrtp: 'outbound-rtp',
  2135. candidatepair: 'candidate-pair',
  2136. localcandidate: 'local-candidate',
  2137. remotecandidate: 'remote-candidate'
  2138. }[stat.type] || stat.type;
  2139. };
  2140. return new Promise(function(resolve) {
  2141. // shim getStats with maplike support
  2142. var results = new Map();
  2143. Promise.all(promises).then(function(res) {
  2144. res.forEach(function(result) {
  2145. Object.keys(result).forEach(function(id) {
  2146. result[id].type = fixStatsType(result[id]);
  2147. results.set(id, result[id]);
  2148. });
  2149. });
  2150. resolve(results);
  2151. });
  2152. });
  2153. };
  2154. // legacy callback shims. Should be moved to adapter.js some days.
  2155. var methods = ['createOffer', 'createAnswer'];
  2156. methods.forEach(function(method) {
  2157. var nativeMethod = RTCPeerConnection.prototype[method];
  2158. RTCPeerConnection.prototype[method] = function() {
  2159. var args = arguments;
  2160. if (typeof args[0] === 'function' ||
  2161. typeof args[1] === 'function') { // legacy
  2162. return nativeMethod.apply(this, [arguments[2]])
  2163. .then(function(description) {
  2164. if (typeof args[0] === 'function') {
  2165. args[0].apply(null, [description]);
  2166. }
  2167. }, function(error) {
  2168. if (typeof args[1] === 'function') {
  2169. args[1].apply(null, [error]);
  2170. }
  2171. });
  2172. }
  2173. return nativeMethod.apply(this, arguments);
  2174. };
  2175. });
  2176. methods = ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'];
  2177. methods.forEach(function(method) {
  2178. var nativeMethod = RTCPeerConnection.prototype[method];
  2179. RTCPeerConnection.prototype[method] = function() {
  2180. var args = arguments;
  2181. if (typeof args[1] === 'function' ||
  2182. typeof args[2] === 'function') { // legacy
  2183. return nativeMethod.apply(this, arguments)
  2184. .then(function() {
  2185. if (typeof args[1] === 'function') {
  2186. args[1].apply(null);
  2187. }
  2188. }, function(error) {
  2189. if (typeof args[2] === 'function') {
  2190. args[2].apply(null, [error]);
  2191. }
  2192. });
  2193. }
  2194. return nativeMethod.apply(this, arguments);
  2195. };
  2196. });
  2197. // getStats is special. It doesn't have a spec legacy method yet we support
  2198. // getStats(something, cb) without error callbacks.
  2199. ['getStats'].forEach(function(method) {
  2200. var nativeMethod = RTCPeerConnection.prototype[method];
  2201. RTCPeerConnection.prototype[method] = function() {
  2202. var args = arguments;
  2203. if (typeof args[1] === 'function') {
  2204. return nativeMethod.apply(this, arguments)
  2205. .then(function() {
  2206. if (typeof args[1] === 'function') {
  2207. args[1].apply(null);
  2208. }
  2209. });
  2210. }
  2211. return nativeMethod.apply(this, arguments);
  2212. };
  2213. });
  2214. return RTCPeerConnection;
  2215. };
  2216. },{"sdp":1}],3:[function(require,module,exports){
  2217. arguments[4][1][0].apply(exports,arguments)
  2218. },{"dup":1}],4:[function(require,module,exports){
  2219. (function (global){
  2220. /*
  2221. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2222. *
  2223. * Use of this source code is governed by a BSD-style license
  2224. * that can be found in the LICENSE file in the root of the source
  2225. * tree.
  2226. */
  2227. /* eslint-env node */
  2228. 'use strict';
  2229. var adapterFactory = require('./adapter_factory.js');
  2230. module.exports = adapterFactory({window: global.window});
  2231. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2232. },{"./adapter_factory.js":5}],5:[function(require,module,exports){
  2233. /*
  2234. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2235. *
  2236. * Use of this source code is governed by a BSD-style license
  2237. * that can be found in the LICENSE file in the root of the source
  2238. * tree.
  2239. */
  2240. /* eslint-env node */
  2241. 'use strict';
  2242. var utils = require('./utils');
  2243. // Shimming starts here.
  2244. module.exports = function(dependencies, opts) {
  2245. var window = dependencies && dependencies.window;
  2246. var options = {
  2247. shimChrome: true,
  2248. shimFirefox: true,
  2249. shimEdge: true,
  2250. shimSafari: true,
  2251. };
  2252. for (var key in opts) {
  2253. if (hasOwnProperty.call(opts, key)) {
  2254. options[key] = opts[key];
  2255. }
  2256. }
  2257. // Utils.
  2258. var logging = utils.log;
  2259. var browserDetails = utils.detectBrowser(window);
  2260. // Uncomment the line below if you want logging to occur, including logging
  2261. // for the switch statement below. Can also be turned on in the browser via
  2262. // adapter.disableLog(false), but then logging from the switch statement below
  2263. // will not appear.
  2264. // require('./utils').disableLog(false);
  2265. // Browser shims.
  2266. var chromeShim = require('./chrome/chrome_shim') || null;
  2267. var edgeShim = require('./edge/edge_shim') || null;
  2268. var firefoxShim = require('./firefox/firefox_shim') || null;
  2269. var safariShim = require('./safari/safari_shim') || null;
  2270. var commonShim = require('./common_shim') || null;
  2271. // Export to the adapter global object visible in the browser.
  2272. var adapter = {
  2273. browserDetails: browserDetails,
  2274. commonShim: commonShim,
  2275. extractVersion: utils.extractVersion,
  2276. disableLog: utils.disableLog,
  2277. disableWarnings: utils.disableWarnings
  2278. };
  2279. // Shim browser if found.
  2280. switch (browserDetails.browser) {
  2281. case 'chrome':
  2282. if (!chromeShim || !chromeShim.shimPeerConnection ||
  2283. !options.shimChrome) {
  2284. logging('Chrome shim is not included in this adapter release.');
  2285. return adapter;
  2286. }
  2287. logging('adapter.js shimming chrome.');
  2288. // Export to the adapter global object visible in the browser.
  2289. adapter.browserShim = chromeShim;
  2290. commonShim.shimCreateObjectURL(window);
  2291. chromeShim.shimGetUserMedia(window);
  2292. chromeShim.shimMediaStream(window);
  2293. chromeShim.shimSourceObject(window);
  2294. chromeShim.shimPeerConnection(window);
  2295. chromeShim.shimOnTrack(window);
  2296. chromeShim.shimAddTrackRemoveTrack(window);
  2297. chromeShim.shimGetSendersWithDtmf(window);
  2298. commonShim.shimRTCIceCandidate(window);
  2299. commonShim.shimMaxMessageSize(window);
  2300. commonShim.shimSendThrowTypeError(window);
  2301. break;
  2302. case 'firefox':
  2303. if (!firefoxShim || !firefoxShim.shimPeerConnection ||
  2304. !options.shimFirefox) {
  2305. logging('Firefox shim is not included in this adapter release.');
  2306. return adapter;
  2307. }
  2308. logging('adapter.js shimming firefox.');
  2309. // Export to the adapter global object visible in the browser.
  2310. adapter.browserShim = firefoxShim;
  2311. commonShim.shimCreateObjectURL(window);
  2312. firefoxShim.shimGetUserMedia(window);
  2313. firefoxShim.shimSourceObject(window);
  2314. firefoxShim.shimPeerConnection(window);
  2315. firefoxShim.shimOnTrack(window);
  2316. firefoxShim.shimRemoveStream(window);
  2317. commonShim.shimRTCIceCandidate(window);
  2318. commonShim.shimMaxMessageSize(window);
  2319. commonShim.shimSendThrowTypeError(window);
  2320. break;
  2321. case 'edge':
  2322. if (!edgeShim || !edgeShim.shimPeerConnection || !options.shimEdge) {
  2323. logging('MS edge shim is not included in this adapter release.');
  2324. return adapter;
  2325. }
  2326. logging('adapter.js shimming edge.');
  2327. // Export to the adapter global object visible in the browser.
  2328. adapter.browserShim = edgeShim;
  2329. commonShim.shimCreateObjectURL(window);
  2330. edgeShim.shimGetUserMedia(window);
  2331. edgeShim.shimPeerConnection(window);
  2332. edgeShim.shimReplaceTrack(window);
  2333. // the edge shim implements the full RTCIceCandidate object.
  2334. commonShim.shimMaxMessageSize(window);
  2335. commonShim.shimSendThrowTypeError(window);
  2336. break;
  2337. case 'safari':
  2338. if (!safariShim || !options.shimSafari) {
  2339. logging('Safari shim is not included in this adapter release.');
  2340. return adapter;
  2341. }
  2342. logging('adapter.js shimming safari.');
  2343. // Export to the adapter global object visible in the browser.
  2344. adapter.browserShim = safariShim;
  2345. commonShim.shimCreateObjectURL(window);
  2346. safariShim.shimRTCIceServerUrls(window);
  2347. safariShim.shimCallbacksAPI(window);
  2348. safariShim.shimLocalStreamsAPI(window);
  2349. safariShim.shimRemoteStreamsAPI(window);
  2350. safariShim.shimTrackEventTransceiver(window);
  2351. safariShim.shimGetUserMedia(window);
  2352. safariShim.shimCreateOfferLegacy(window);
  2353. commonShim.shimRTCIceCandidate(window);
  2354. commonShim.shimMaxMessageSize(window);
  2355. commonShim.shimSendThrowTypeError(window);
  2356. break;
  2357. default:
  2358. logging('Unsupported browser!');
  2359. break;
  2360. }
  2361. return adapter;
  2362. };
  2363. },{"./chrome/chrome_shim":6,"./common_shim":8,"./edge/edge_shim":9,"./firefox/firefox_shim":11,"./safari/safari_shim":13,"./utils":14}],6:[function(require,module,exports){
  2364. /*
  2365. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2366. *
  2367. * Use of this source code is governed by a BSD-style license
  2368. * that can be found in the LICENSE file in the root of the source
  2369. * tree.
  2370. */
  2371. /* eslint-env node */
  2372. 'use strict';
  2373. var utils = require('../utils.js');
  2374. var logging = utils.log;
  2375. module.exports = {
  2376. shimGetUserMedia: require('./getusermedia'),
  2377. shimMediaStream: function(window) {
  2378. window.MediaStream = window.MediaStream || window.webkitMediaStream;
  2379. },
  2380. shimOnTrack: function(window) {
  2381. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  2382. window.RTCPeerConnection.prototype)) {
  2383. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  2384. get: function() {
  2385. return this._ontrack;
  2386. },
  2387. set: function(f) {
  2388. if (this._ontrack) {
  2389. this.removeEventListener('track', this._ontrack);
  2390. }
  2391. this.addEventListener('track', this._ontrack = f);
  2392. }
  2393. });
  2394. var origSetRemoteDescription =
  2395. window.RTCPeerConnection.prototype.setRemoteDescription;
  2396. window.RTCPeerConnection.prototype.setRemoteDescription = function() {
  2397. var pc = this;
  2398. if (!pc._ontrackpoly) {
  2399. pc._ontrackpoly = function(e) {
  2400. // onaddstream does not fire when a track is added to an existing
  2401. // stream. But stream.onaddtrack is implemented so we use that.
  2402. e.stream.addEventListener('addtrack', function(te) {
  2403. var receiver;
  2404. if (window.RTCPeerConnection.prototype.getReceivers) {
  2405. receiver = pc.getReceivers().find(function(r) {
  2406. return r.track && r.track.id === te.track.id;
  2407. });
  2408. } else {
  2409. receiver = {track: te.track};
  2410. }
  2411. var event = new Event('track');
  2412. event.track = te.track;
  2413. event.receiver = receiver;
  2414. event.transceiver = {receiver: receiver};
  2415. event.streams = [e.stream];
  2416. pc.dispatchEvent(event);
  2417. });
  2418. e.stream.getTracks().forEach(function(track) {
  2419. var receiver;
  2420. if (window.RTCPeerConnection.prototype.getReceivers) {
  2421. receiver = pc.getReceivers().find(function(r) {
  2422. return r.track && r.track.id === track.id;
  2423. });
  2424. } else {
  2425. receiver = {track: track};
  2426. }
  2427. var event = new Event('track');
  2428. event.track = track;
  2429. event.receiver = receiver;
  2430. event.transceiver = {receiver: receiver};
  2431. event.streams = [e.stream];
  2432. pc.dispatchEvent(event);
  2433. });
  2434. };
  2435. pc.addEventListener('addstream', pc._ontrackpoly);
  2436. }
  2437. return origSetRemoteDescription.apply(pc, arguments);
  2438. };
  2439. } else if (!('RTCRtpTransceiver' in window)) {
  2440. utils.wrapPeerConnectionEvent(window, 'track', function(e) {
  2441. if (!e.transceiver) {
  2442. e.transceiver = {receiver: e.receiver};
  2443. }
  2444. return e;
  2445. });
  2446. }
  2447. },
  2448. shimGetSendersWithDtmf: function(window) {
  2449. // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
  2450. if (typeof window === 'object' && window.RTCPeerConnection &&
  2451. !('getSenders' in window.RTCPeerConnection.prototype) &&
  2452. 'createDTMFSender' in window.RTCPeerConnection.prototype) {
  2453. var shimSenderWithDtmf = function(pc, track) {
  2454. return {
  2455. track: track,
  2456. get dtmf() {
  2457. if (this._dtmf === undefined) {
  2458. if (track.kind === 'audio') {
  2459. this._dtmf = pc.createDTMFSender(track);
  2460. } else {
  2461. this._dtmf = null;
  2462. }
  2463. }
  2464. return this._dtmf;
  2465. },
  2466. _pc: pc
  2467. };
  2468. };
  2469. // augment addTrack when getSenders is not available.
  2470. if (!window.RTCPeerConnection.prototype.getSenders) {
  2471. window.RTCPeerConnection.prototype.getSenders = function() {
  2472. this._senders = this._senders || [];
  2473. return this._senders.slice(); // return a copy of the internal state.
  2474. };
  2475. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  2476. window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
  2477. var pc = this;
  2478. var sender = origAddTrack.apply(pc, arguments);
  2479. if (!sender) {
  2480. sender = shimSenderWithDtmf(pc, track);
  2481. pc._senders.push(sender);
  2482. }
  2483. return sender;
  2484. };
  2485. var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  2486. window.RTCPeerConnection.prototype.removeTrack = function(sender) {
  2487. var pc = this;
  2488. origRemoveTrack.apply(pc, arguments);
  2489. var idx = pc._senders.indexOf(sender);
  2490. if (idx !== -1) {
  2491. pc._senders.splice(idx, 1);
  2492. }
  2493. };
  2494. }
  2495. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  2496. window.RTCPeerConnection.prototype.addStream = function(stream) {
  2497. var pc = this;
  2498. pc._senders = pc._senders || [];
  2499. origAddStream.apply(pc, [stream]);
  2500. stream.getTracks().forEach(function(track) {
  2501. pc._senders.push(shimSenderWithDtmf(pc, track));
  2502. });
  2503. };
  2504. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  2505. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  2506. var pc = this;
  2507. pc._senders = pc._senders || [];
  2508. origRemoveStream.apply(pc, [stream]);
  2509. stream.getTracks().forEach(function(track) {
  2510. var sender = pc._senders.find(function(s) {
  2511. return s.track === track;
  2512. });
  2513. if (sender) {
  2514. pc._senders.splice(pc._senders.indexOf(sender), 1); // remove sender
  2515. }
  2516. });
  2517. };
  2518. } else if (typeof window === 'object' && window.RTCPeerConnection &&
  2519. 'getSenders' in window.RTCPeerConnection.prototype &&
  2520. 'createDTMFSender' in window.RTCPeerConnection.prototype &&
  2521. window.RTCRtpSender &&
  2522. !('dtmf' in window.RTCRtpSender.prototype)) {
  2523. var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  2524. window.RTCPeerConnection.prototype.getSenders = function() {
  2525. var pc = this;
  2526. var senders = origGetSenders.apply(pc, []);
  2527. senders.forEach(function(sender) {
  2528. sender._pc = pc;
  2529. });
  2530. return senders;
  2531. };
  2532. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  2533. get: function() {
  2534. if (this._dtmf === undefined) {
  2535. if (this.track.kind === 'audio') {
  2536. this._dtmf = this._pc.createDTMFSender(this.track);
  2537. } else {
  2538. this._dtmf = null;
  2539. }
  2540. }
  2541. return this._dtmf;
  2542. }
  2543. });
  2544. }
  2545. },
  2546. shimSourceObject: function(window) {
  2547. var URL = window && window.URL;
  2548. if (typeof window === 'object') {
  2549. if (window.HTMLMediaElement &&
  2550. !('srcObject' in window.HTMLMediaElement.prototype)) {
  2551. // Shim the srcObject property, once, when HTMLMediaElement is found.
  2552. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
  2553. get: function() {
  2554. return this._srcObject;
  2555. },
  2556. set: function(stream) {
  2557. var self = this;
  2558. // Use _srcObject as a private property for this shim
  2559. this._srcObject = stream;
  2560. if (this.src) {
  2561. URL.revokeObjectURL(this.src);
  2562. }
  2563. if (!stream) {
  2564. this.src = '';
  2565. return undefined;
  2566. }
  2567. this.src = URL.createObjectURL(stream);
  2568. // We need to recreate the blob url when a track is added or
  2569. // removed. Doing it manually since we want to avoid a recursion.
  2570. stream.addEventListener('addtrack', function() {
  2571. if (self.src) {
  2572. URL.revokeObjectURL(self.src);
  2573. }
  2574. self.src = URL.createObjectURL(stream);
  2575. });
  2576. stream.addEventListener('removetrack', function() {
  2577. if (self.src) {
  2578. URL.revokeObjectURL(self.src);
  2579. }
  2580. self.src = URL.createObjectURL(stream);
  2581. });
  2582. }
  2583. });
  2584. }
  2585. }
  2586. },
  2587. shimAddTrackRemoveTrackWithNative: function(window) {
  2588. // shim addTrack/removeTrack with native variants in order to make
  2589. // the interactions with legacy getLocalStreams behave as in other browsers.
  2590. // Keeps a mapping stream.id => [stream, rtpsenders...]
  2591. window.RTCPeerConnection.prototype.getLocalStreams = function() {
  2592. var pc = this;
  2593. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  2594. return Object.keys(this._shimmedLocalStreams).map(function(streamId) {
  2595. return pc._shimmedLocalStreams[streamId][0];
  2596. });
  2597. };
  2598. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  2599. window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
  2600. if (!stream) {
  2601. return origAddTrack.apply(this, arguments);
  2602. }
  2603. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  2604. var sender = origAddTrack.apply(this, arguments);
  2605. if (!this._shimmedLocalStreams[stream.id]) {
  2606. this._shimmedLocalStreams[stream.id] = [stream, sender];
  2607. } else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) {
  2608. this._shimmedLocalStreams[stream.id].push(sender);
  2609. }
  2610. return sender;
  2611. };
  2612. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  2613. window.RTCPeerConnection.prototype.addStream = function(stream) {
  2614. var pc = this;
  2615. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  2616. stream.getTracks().forEach(function(track) {
  2617. var alreadyExists = pc.getSenders().find(function(s) {
  2618. return s.track === track;
  2619. });
  2620. if (alreadyExists) {
  2621. throw new DOMException('Track already exists.',
  2622. 'InvalidAccessError');
  2623. }
  2624. });
  2625. var existingSenders = pc.getSenders();
  2626. origAddStream.apply(this, arguments);
  2627. var newSenders = pc.getSenders().filter(function(newSender) {
  2628. return existingSenders.indexOf(newSender) === -1;
  2629. });
  2630. this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders);
  2631. };
  2632. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  2633. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  2634. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  2635. delete this._shimmedLocalStreams[stream.id];
  2636. return origRemoveStream.apply(this, arguments);
  2637. };
  2638. var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  2639. window.RTCPeerConnection.prototype.removeTrack = function(sender) {
  2640. var pc = this;
  2641. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  2642. if (sender) {
  2643. Object.keys(this._shimmedLocalStreams).forEach(function(streamId) {
  2644. var idx = pc._shimmedLocalStreams[streamId].indexOf(sender);
  2645. if (idx !== -1) {
  2646. pc._shimmedLocalStreams[streamId].splice(idx, 1);
  2647. }
  2648. if (pc._shimmedLocalStreams[streamId].length === 1) {
  2649. delete pc._shimmedLocalStreams[streamId];
  2650. }
  2651. });
  2652. }
  2653. return origRemoveTrack.apply(this, arguments);
  2654. };
  2655. },
  2656. shimAddTrackRemoveTrack: function(window) {
  2657. var browserDetails = utils.detectBrowser(window);
  2658. // shim addTrack and removeTrack.
  2659. if (window.RTCPeerConnection.prototype.addTrack &&
  2660. browserDetails.version >= 65) {
  2661. return this.shimAddTrackRemoveTrackWithNative(window);
  2662. }
  2663. // also shim pc.getLocalStreams when addTrack is shimmed
  2664. // to return the original streams.
  2665. var origGetLocalStreams = window.RTCPeerConnection.prototype
  2666. .getLocalStreams;
  2667. window.RTCPeerConnection.prototype.getLocalStreams = function() {
  2668. var pc = this;
  2669. var nativeStreams = origGetLocalStreams.apply(this);
  2670. pc._reverseStreams = pc._reverseStreams || {};
  2671. return nativeStreams.map(function(stream) {
  2672. return pc._reverseStreams[stream.id];
  2673. });
  2674. };
  2675. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  2676. window.RTCPeerConnection.prototype.addStream = function(stream) {
  2677. var pc = this;
  2678. pc._streams = pc._streams || {};
  2679. pc._reverseStreams = pc._reverseStreams || {};
  2680. stream.getTracks().forEach(function(track) {
  2681. var alreadyExists = pc.getSenders().find(function(s) {
  2682. return s.track === track;
  2683. });
  2684. if (alreadyExists) {
  2685. throw new DOMException('Track already exists.',
  2686. 'InvalidAccessError');
  2687. }
  2688. });
  2689. // Add identity mapping for consistency with addTrack.
  2690. // Unless this is being used with a stream from addTrack.
  2691. if (!pc._reverseStreams[stream.id]) {
  2692. var newStream = new window.MediaStream(stream.getTracks());
  2693. pc._streams[stream.id] = newStream;
  2694. pc._reverseStreams[newStream.id] = stream;
  2695. stream = newStream;
  2696. }
  2697. origAddStream.apply(pc, [stream]);
  2698. };
  2699. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  2700. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  2701. var pc = this;
  2702. pc._streams = pc._streams || {};
  2703. pc._reverseStreams = pc._reverseStreams || {};
  2704. origRemoveStream.apply(pc, [(pc._streams[stream.id] || stream)]);
  2705. delete pc._reverseStreams[(pc._streams[stream.id] ?
  2706. pc._streams[stream.id].id : stream.id)];
  2707. delete pc._streams[stream.id];
  2708. };
  2709. window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
  2710. var pc = this;
  2711. if (pc.signalingState === 'closed') {
  2712. throw new DOMException(
  2713. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  2714. 'InvalidStateError');
  2715. }
  2716. var streams = [].slice.call(arguments, 1);
  2717. if (streams.length !== 1 ||
  2718. !streams[0].getTracks().find(function(t) {
  2719. return t === track;
  2720. })) {
  2721. // this is not fully correct but all we can manage without
  2722. // [[associated MediaStreams]] internal slot.
  2723. throw new DOMException(
  2724. 'The adapter.js addTrack polyfill only supports a single ' +
  2725. ' stream which is associated with the specified track.',
  2726. 'NotSupportedError');
  2727. }
  2728. var alreadyExists = pc.getSenders().find(function(s) {
  2729. return s.track === track;
  2730. });
  2731. if (alreadyExists) {
  2732. throw new DOMException('Track already exists.',
  2733. 'InvalidAccessError');
  2734. }
  2735. pc._streams = pc._streams || {};
  2736. pc._reverseStreams = pc._reverseStreams || {};
  2737. var oldStream = pc._streams[stream.id];
  2738. if (oldStream) {
  2739. // this is using odd Chrome behaviour, use with caution:
  2740. // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
  2741. // Note: we rely on the high-level addTrack/dtmf shim to
  2742. // create the sender with a dtmf sender.
  2743. oldStream.addTrack(track);
  2744. // Trigger ONN async.
  2745. Promise.resolve().then(function() {
  2746. pc.dispatchEvent(new Event('negotiationneeded'));
  2747. });
  2748. } else {
  2749. var newStream = new window.MediaStream([track]);
  2750. pc._streams[stream.id] = newStream;
  2751. pc._reverseStreams[newStream.id] = stream;
  2752. pc.addStream(newStream);
  2753. }
  2754. return pc.getSenders().find(function(s) {
  2755. return s.track === track;
  2756. });
  2757. };
  2758. // replace the internal stream id with the external one and
  2759. // vice versa.
  2760. function replaceInternalStreamId(pc, description) {
  2761. var sdp = description.sdp;
  2762. Object.keys(pc._reverseStreams || []).forEach(function(internalId) {
  2763. var externalStream = pc._reverseStreams[internalId];
  2764. var internalStream = pc._streams[externalStream.id];
  2765. sdp = sdp.replace(new RegExp(internalStream.id, 'g'),
  2766. externalStream.id);
  2767. });
  2768. return new RTCSessionDescription({
  2769. type: description.type,
  2770. sdp: sdp
  2771. });
  2772. }
  2773. function replaceExternalStreamId(pc, description) {
  2774. var sdp = description.sdp;
  2775. Object.keys(pc._reverseStreams || []).forEach(function(internalId) {
  2776. var externalStream = pc._reverseStreams[internalId];
  2777. var internalStream = pc._streams[externalStream.id];
  2778. sdp = sdp.replace(new RegExp(externalStream.id, 'g'),
  2779. internalStream.id);
  2780. });
  2781. return new RTCSessionDescription({
  2782. type: description.type,
  2783. sdp: sdp
  2784. });
  2785. }
  2786. ['createOffer', 'createAnswer'].forEach(function(method) {
  2787. var nativeMethod = window.RTCPeerConnection.prototype[method];
  2788. window.RTCPeerConnection.prototype[method] = function() {
  2789. var pc = this;
  2790. var args = arguments;
  2791. var isLegacyCall = arguments.length &&
  2792. typeof arguments[0] === 'function';
  2793. if (isLegacyCall) {
  2794. return nativeMethod.apply(pc, [
  2795. function(description) {
  2796. var desc = replaceInternalStreamId(pc, description);
  2797. args[0].apply(null, [desc]);
  2798. },
  2799. function(err) {
  2800. if (args[1]) {
  2801. args[1].apply(null, err);
  2802. }
  2803. }, arguments[2]
  2804. ]);
  2805. }
  2806. return nativeMethod.apply(pc, arguments)
  2807. .then(function(description) {
  2808. return replaceInternalStreamId(pc, description);
  2809. });
  2810. };
  2811. });
  2812. var origSetLocalDescription =
  2813. window.RTCPeerConnection.prototype.setLocalDescription;
  2814. window.RTCPeerConnection.prototype.setLocalDescription = function() {
  2815. var pc = this;
  2816. if (!arguments.length || !arguments[0].type) {
  2817. return origSetLocalDescription.apply(pc, arguments);
  2818. }
  2819. arguments[0] = replaceExternalStreamId(pc, arguments[0]);
  2820. return origSetLocalDescription.apply(pc, arguments);
  2821. };
  2822. // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
  2823. var origLocalDescription = Object.getOwnPropertyDescriptor(
  2824. window.RTCPeerConnection.prototype, 'localDescription');
  2825. Object.defineProperty(window.RTCPeerConnection.prototype,
  2826. 'localDescription', {
  2827. get: function() {
  2828. var pc = this;
  2829. var description = origLocalDescription.get.apply(this);
  2830. if (description.type === '') {
  2831. return description;
  2832. }
  2833. return replaceInternalStreamId(pc, description);
  2834. }
  2835. });
  2836. window.RTCPeerConnection.prototype.removeTrack = function(sender) {
  2837. var pc = this;
  2838. if (pc.signalingState === 'closed') {
  2839. throw new DOMException(
  2840. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  2841. 'InvalidStateError');
  2842. }
  2843. // We can not yet check for sender instanceof RTCRtpSender
  2844. // since we shim RTPSender. So we check if sender._pc is set.
  2845. if (!sender._pc) {
  2846. throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' +
  2847. 'does not implement interface RTCRtpSender.', 'TypeError');
  2848. }
  2849. var isLocal = sender._pc === pc;
  2850. if (!isLocal) {
  2851. throw new DOMException('Sender was not created by this connection.',
  2852. 'InvalidAccessError');
  2853. }
  2854. // Search for the native stream the senders track belongs to.
  2855. pc._streams = pc._streams || {};
  2856. var stream;
  2857. Object.keys(pc._streams).forEach(function(streamid) {
  2858. var hasTrack = pc._streams[streamid].getTracks().find(function(track) {
  2859. return sender.track === track;
  2860. });
  2861. if (hasTrack) {
  2862. stream = pc._streams[streamid];
  2863. }
  2864. });
  2865. if (stream) {
  2866. if (stream.getTracks().length === 1) {
  2867. // if this is the last track of the stream, remove the stream. This
  2868. // takes care of any shimmed _senders.
  2869. pc.removeStream(pc._reverseStreams[stream.id]);
  2870. } else {
  2871. // relying on the same odd chrome behaviour as above.
  2872. stream.removeTrack(sender.track);
  2873. }
  2874. pc.dispatchEvent(new Event('negotiationneeded'));
  2875. }
  2876. };
  2877. },
  2878. shimPeerConnection: function(window) {
  2879. var browserDetails = utils.detectBrowser(window);
  2880. // The RTCPeerConnection object.
  2881. if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {
  2882. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  2883. // Translate iceTransportPolicy to iceTransports,
  2884. // see https://code.google.com/p/webrtc/issues/detail?id=4869
  2885. // this was fixed in M56 along with unprefixing RTCPeerConnection.
  2886. logging('PeerConnection');
  2887. if (pcConfig && pcConfig.iceTransportPolicy) {
  2888. pcConfig.iceTransports = pcConfig.iceTransportPolicy;
  2889. }
  2890. return new window.webkitRTCPeerConnection(pcConfig, pcConstraints);
  2891. };
  2892. window.RTCPeerConnection.prototype =
  2893. window.webkitRTCPeerConnection.prototype;
  2894. // wrap static methods. Currently just generateCertificate.
  2895. if (window.webkitRTCPeerConnection.generateCertificate) {
  2896. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  2897. get: function() {
  2898. return window.webkitRTCPeerConnection.generateCertificate;
  2899. }
  2900. });
  2901. }
  2902. } else {
  2903. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  2904. var OrigPeerConnection = window.RTCPeerConnection;
  2905. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  2906. if (pcConfig && pcConfig.iceServers) {
  2907. var newIceServers = [];
  2908. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2909. var server = pcConfig.iceServers[i];
  2910. if (!server.hasOwnProperty('urls') &&
  2911. server.hasOwnProperty('url')) {
  2912. utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  2913. server = JSON.parse(JSON.stringify(server));
  2914. server.urls = server.url;
  2915. newIceServers.push(server);
  2916. } else {
  2917. newIceServers.push(pcConfig.iceServers[i]);
  2918. }
  2919. }
  2920. pcConfig.iceServers = newIceServers;
  2921. }
  2922. return new OrigPeerConnection(pcConfig, pcConstraints);
  2923. };
  2924. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  2925. // wrap static methods. Currently just generateCertificate.
  2926. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  2927. get: function() {
  2928. return OrigPeerConnection.generateCertificate;
  2929. }
  2930. });
  2931. }
  2932. var origGetStats = window.RTCPeerConnection.prototype.getStats;
  2933. window.RTCPeerConnection.prototype.getStats = function(selector,
  2934. successCallback, errorCallback) {
  2935. var pc = this;
  2936. var args = arguments;
  2937. // If selector is a function then we are in the old style stats so just
  2938. // pass back the original getStats format to avoid breaking old users.
  2939. if (arguments.length > 0 && typeof selector === 'function') {
  2940. return origGetStats.apply(this, arguments);
  2941. }
  2942. // When spec-style getStats is supported, return those when called with
  2943. // either no arguments or the selector argument is null.
  2944. if (origGetStats.length === 0 && (arguments.length === 0 ||
  2945. typeof arguments[0] !== 'function')) {
  2946. return origGetStats.apply(this, []);
  2947. }
  2948. var fixChromeStats_ = function(response) {
  2949. var standardReport = {};
  2950. var reports = response.result();
  2951. reports.forEach(function(report) {
  2952. var standardStats = {
  2953. id: report.id,
  2954. timestamp: report.timestamp,
  2955. type: {
  2956. localcandidate: 'local-candidate',
  2957. remotecandidate: 'remote-candidate'
  2958. }[report.type] || report.type
  2959. };
  2960. report.names().forEach(function(name) {
  2961. standardStats[name] = report.stat(name);
  2962. });
  2963. standardReport[standardStats.id] = standardStats;
  2964. });
  2965. return standardReport;
  2966. };
  2967. // shim getStats with maplike support
  2968. var makeMapStats = function(stats) {
  2969. return new Map(Object.keys(stats).map(function(key) {
  2970. return [key, stats[key]];
  2971. }));
  2972. };
  2973. if (arguments.length >= 2) {
  2974. var successCallbackWrapper_ = function(response) {
  2975. args[1](makeMapStats(fixChromeStats_(response)));
  2976. };
  2977. return origGetStats.apply(this, [successCallbackWrapper_,
  2978. arguments[0]]);
  2979. }
  2980. // promise-support
  2981. return new Promise(function(resolve, reject) {
  2982. origGetStats.apply(pc, [
  2983. function(response) {
  2984. resolve(makeMapStats(fixChromeStats_(response)));
  2985. }, reject]);
  2986. }).then(successCallback, errorCallback);
  2987. };
  2988. // add promise support -- natively available in Chrome 51
  2989. if (browserDetails.version < 51) {
  2990. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  2991. .forEach(function(method) {
  2992. var nativeMethod = window.RTCPeerConnection.prototype[method];
  2993. window.RTCPeerConnection.prototype[method] = function() {
  2994. var args = arguments;
  2995. var pc = this;
  2996. var promise = new Promise(function(resolve, reject) {
  2997. nativeMethod.apply(pc, [args[0], resolve, reject]);
  2998. });
  2999. if (args.length < 2) {
  3000. return promise;
  3001. }
  3002. return promise.then(function() {
  3003. args[1].apply(null, []);
  3004. },
  3005. function(err) {
  3006. if (args.length >= 3) {
  3007. args[2].apply(null, [err]);
  3008. }
  3009. });
  3010. };
  3011. });
  3012. }
  3013. // promise support for createOffer and createAnswer. Available (without
  3014. // bugs) since M52: crbug/619289
  3015. if (browserDetails.version < 52) {
  3016. ['createOffer', 'createAnswer'].forEach(function(method) {
  3017. var nativeMethod = window.RTCPeerConnection.prototype[method];
  3018. window.RTCPeerConnection.prototype[method] = function() {
  3019. var pc = this;
  3020. if (arguments.length < 1 || (arguments.length === 1 &&
  3021. typeof arguments[0] === 'object')) {
  3022. var opts = arguments.length === 1 ? arguments[0] : undefined;
  3023. return new Promise(function(resolve, reject) {
  3024. nativeMethod.apply(pc, [resolve, reject, opts]);
  3025. });
  3026. }
  3027. return nativeMethod.apply(this, arguments);
  3028. };
  3029. });
  3030. }
  3031. // shim implicit creation of RTCSessionDescription/RTCIceCandidate
  3032. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  3033. .forEach(function(method) {
  3034. var nativeMethod = window.RTCPeerConnection.prototype[method];
  3035. window.RTCPeerConnection.prototype[method] = function() {
  3036. arguments[0] = new ((method === 'addIceCandidate') ?
  3037. window.RTCIceCandidate :
  3038. window.RTCSessionDescription)(arguments[0]);
  3039. return nativeMethod.apply(this, arguments);
  3040. };
  3041. });
  3042. // support for addIceCandidate(null or undefined)
  3043. var nativeAddIceCandidate =
  3044. window.RTCPeerConnection.prototype.addIceCandidate;
  3045. window.RTCPeerConnection.prototype.addIceCandidate = function() {
  3046. if (!arguments[0]) {
  3047. if (arguments[1]) {
  3048. arguments[1].apply(null);
  3049. }
  3050. return Promise.resolve();
  3051. }
  3052. return nativeAddIceCandidate.apply(this, arguments);
  3053. };
  3054. }
  3055. };
  3056. },{"../utils.js":14,"./getusermedia":7}],7:[function(require,module,exports){
  3057. /*
  3058. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3059. *
  3060. * Use of this source code is governed by a BSD-style license
  3061. * that can be found in the LICENSE file in the root of the source
  3062. * tree.
  3063. */
  3064. /* eslint-env node */
  3065. 'use strict';
  3066. var utils = require('../utils.js');
  3067. var logging = utils.log;
  3068. // Expose public methods.
  3069. module.exports = function(window) {
  3070. var browserDetails = utils.detectBrowser(window);
  3071. var navigator = window && window.navigator;
  3072. var constraintsToChrome_ = function(c) {
  3073. if (typeof c !== 'object' || c.mandatory || c.optional) {
  3074. return c;
  3075. }
  3076. var cc = {};
  3077. Object.keys(c).forEach(function(key) {
  3078. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  3079. return;
  3080. }
  3081. var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
  3082. if (r.exact !== undefined && typeof r.exact === 'number') {
  3083. r.min = r.max = r.exact;
  3084. }
  3085. var oldname_ = function(prefix, name) {
  3086. if (prefix) {
  3087. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  3088. }
  3089. return (name === 'deviceId') ? 'sourceId' : name;
  3090. };
  3091. if (r.ideal !== undefined) {
  3092. cc.optional = cc.optional || [];
  3093. var oc = {};
  3094. if (typeof r.ideal === 'number') {
  3095. oc[oldname_('min', key)] = r.ideal;
  3096. cc.optional.push(oc);
  3097. oc = {};
  3098. oc[oldname_('max', key)] = r.ideal;
  3099. cc.optional.push(oc);
  3100. } else {
  3101. oc[oldname_('', key)] = r.ideal;
  3102. cc.optional.push(oc);
  3103. }
  3104. }
  3105. if (r.exact !== undefined && typeof r.exact !== 'number') {
  3106. cc.mandatory = cc.mandatory || {};
  3107. cc.mandatory[oldname_('', key)] = r.exact;
  3108. } else {
  3109. ['min', 'max'].forEach(function(mix) {
  3110. if (r[mix] !== undefined) {
  3111. cc.mandatory = cc.mandatory || {};
  3112. cc.mandatory[oldname_(mix, key)] = r[mix];
  3113. }
  3114. });
  3115. }
  3116. });
  3117. if (c.advanced) {
  3118. cc.optional = (cc.optional || []).concat(c.advanced);
  3119. }
  3120. return cc;
  3121. };
  3122. var shimConstraints_ = function(constraints, func) {
  3123. if (browserDetails.version >= 61) {
  3124. return func(constraints);
  3125. }
  3126. constraints = JSON.parse(JSON.stringify(constraints));
  3127. if (constraints && typeof constraints.audio === 'object') {
  3128. var remap = function(obj, a, b) {
  3129. if (a in obj && !(b in obj)) {
  3130. obj[b] = obj[a];
  3131. delete obj[a];
  3132. }
  3133. };
  3134. constraints = JSON.parse(JSON.stringify(constraints));
  3135. remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
  3136. remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
  3137. constraints.audio = constraintsToChrome_(constraints.audio);
  3138. }
  3139. if (constraints && typeof constraints.video === 'object') {
  3140. // Shim facingMode for mobile & surface pro.
  3141. var face = constraints.video.facingMode;
  3142. face = face && ((typeof face === 'object') ? face : {ideal: face});
  3143. var getSupportedFacingModeLies = browserDetails.version < 66;
  3144. if ((face && (face.exact === 'user' || face.exact === 'environment' ||
  3145. face.ideal === 'user' || face.ideal === 'environment')) &&
  3146. !(navigator.mediaDevices.getSupportedConstraints &&
  3147. navigator.mediaDevices.getSupportedConstraints().facingMode &&
  3148. !getSupportedFacingModeLies)) {
  3149. delete constraints.video.facingMode;
  3150. var matches;
  3151. if (face.exact === 'environment' || face.ideal === 'environment') {
  3152. matches = ['back', 'rear'];
  3153. } else if (face.exact === 'user' || face.ideal === 'user') {
  3154. matches = ['front'];
  3155. }
  3156. if (matches) {
  3157. // Look for matches in label, or use last cam for back (typical).
  3158. return navigator.mediaDevices.enumerateDevices()
  3159. .then(function(devices) {
  3160. devices = devices.filter(function(d) {
  3161. return d.kind === 'videoinput';
  3162. });
  3163. var dev = devices.find(function(d) {
  3164. return matches.some(function(match) {
  3165. return d.label.toLowerCase().indexOf(match) !== -1;
  3166. });
  3167. });
  3168. if (!dev && devices.length && matches.indexOf('back') !== -1) {
  3169. dev = devices[devices.length - 1]; // more likely the back cam
  3170. }
  3171. if (dev) {
  3172. constraints.video.deviceId = face.exact ? {exact: dev.deviceId} :
  3173. {ideal: dev.deviceId};
  3174. }
  3175. constraints.video = constraintsToChrome_(constraints.video);
  3176. logging('chrome: ' + JSON.stringify(constraints));
  3177. return func(constraints);
  3178. });
  3179. }
  3180. }
  3181. constraints.video = constraintsToChrome_(constraints.video);
  3182. }
  3183. logging('chrome: ' + JSON.stringify(constraints));
  3184. return func(constraints);
  3185. };
  3186. var shimError_ = function(e) {
  3187. return {
  3188. name: {
  3189. PermissionDeniedError: 'NotAllowedError',
  3190. PermissionDismissedError: 'NotAllowedError',
  3191. InvalidStateError: 'NotAllowedError',
  3192. DevicesNotFoundError: 'NotFoundError',
  3193. ConstraintNotSatisfiedError: 'OverconstrainedError',
  3194. TrackStartError: 'NotReadableError',
  3195. MediaDeviceFailedDueToShutdown: 'NotAllowedError',
  3196. MediaDeviceKillSwitchOn: 'NotAllowedError',
  3197. TabCaptureError: 'AbortError',
  3198. ScreenCaptureError: 'AbortError',
  3199. DeviceCaptureError: 'AbortError'
  3200. }[e.name] || e.name,
  3201. message: e.message,
  3202. constraint: e.constraintName,
  3203. toString: function() {
  3204. return this.name + (this.message && ': ') + this.message;
  3205. }
  3206. };
  3207. };
  3208. var getUserMedia_ = function(constraints, onSuccess, onError) {
  3209. shimConstraints_(constraints, function(c) {
  3210. navigator.webkitGetUserMedia(c, onSuccess, function(e) {
  3211. if (onError) {
  3212. onError(shimError_(e));
  3213. }
  3214. });
  3215. });
  3216. };
  3217. navigator.getUserMedia = getUserMedia_;
  3218. // Returns the result of getUserMedia as a Promise.
  3219. var getUserMediaPromise_ = function(constraints) {
  3220. return new Promise(function(resolve, reject) {
  3221. navigator.getUserMedia(constraints, resolve, reject);
  3222. });
  3223. };
  3224. if (!navigator.mediaDevices) {
  3225. navigator.mediaDevices = {
  3226. getUserMedia: getUserMediaPromise_,
  3227. enumerateDevices: function() {
  3228. return new Promise(function(resolve) {
  3229. var kinds = {audio: 'audioinput', video: 'videoinput'};
  3230. return window.MediaStreamTrack.getSources(function(devices) {
  3231. resolve(devices.map(function(device) {
  3232. return {label: device.label,
  3233. kind: kinds[device.kind],
  3234. deviceId: device.id,
  3235. groupId: ''};
  3236. }));
  3237. });
  3238. });
  3239. },
  3240. getSupportedConstraints: function() {
  3241. return {
  3242. deviceId: true, echoCancellation: true, facingMode: true,
  3243. frameRate: true, height: true, width: true
  3244. };
  3245. }
  3246. };
  3247. }
  3248. // A shim for getUserMedia method on the mediaDevices object.
  3249. // TODO(KaptenJansson) remove once implemented in Chrome stable.
  3250. if (!navigator.mediaDevices.getUserMedia) {
  3251. navigator.mediaDevices.getUserMedia = function(constraints) {
  3252. return getUserMediaPromise_(constraints);
  3253. };
  3254. } else {
  3255. // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
  3256. // function which returns a Promise, it does not accept spec-style
  3257. // constraints.
  3258. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  3259. bind(navigator.mediaDevices);
  3260. navigator.mediaDevices.getUserMedia = function(cs) {
  3261. return shimConstraints_(cs, function(c) {
  3262. return origGetUserMedia(c).then(function(stream) {
  3263. if (c.audio && !stream.getAudioTracks().length ||
  3264. c.video && !stream.getVideoTracks().length) {
  3265. stream.getTracks().forEach(function(track) {
  3266. track.stop();
  3267. });
  3268. throw new DOMException('', 'NotFoundError');
  3269. }
  3270. return stream;
  3271. }, function(e) {
  3272. return Promise.reject(shimError_(e));
  3273. });
  3274. });
  3275. };
  3276. }
  3277. // Dummy devicechange event methods.
  3278. // TODO(KaptenJansson) remove once implemented in Chrome stable.
  3279. if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
  3280. navigator.mediaDevices.addEventListener = function() {
  3281. logging('Dummy mediaDevices.addEventListener called.');
  3282. };
  3283. }
  3284. if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
  3285. navigator.mediaDevices.removeEventListener = function() {
  3286. logging('Dummy mediaDevices.removeEventListener called.');
  3287. };
  3288. }
  3289. };
  3290. },{"../utils.js":14}],8:[function(require,module,exports){
  3291. /*
  3292. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  3293. *
  3294. * Use of this source code is governed by a BSD-style license
  3295. * that can be found in the LICENSE file in the root of the source
  3296. * tree.
  3297. */
  3298. /* eslint-env node */
  3299. 'use strict';
  3300. var SDPUtils = require('sdp');
  3301. var utils = require('./utils');
  3302. module.exports = {
  3303. shimRTCIceCandidate: function(window) {
  3304. // foundation is arbitrarily chosen as an indicator for full support for
  3305. // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
  3306. if (window.RTCIceCandidate && 'foundation' in
  3307. window.RTCIceCandidate.prototype) {
  3308. return;
  3309. }
  3310. var NativeRTCIceCandidate = window.RTCIceCandidate;
  3311. window.RTCIceCandidate = function(args) {
  3312. // Remove the a= which shouldn't be part of the candidate string.
  3313. if (typeof args === 'object' && args.candidate &&
  3314. args.candidate.indexOf('a=') === 0) {
  3315. args = JSON.parse(JSON.stringify(args));
  3316. args.candidate = args.candidate.substr(2);
  3317. }
  3318. if (args.candidate && args.candidate.length) {
  3319. // Augment the native candidate with the parsed fields.
  3320. var nativeCandidate = new NativeRTCIceCandidate(args);
  3321. var parsedCandidate = SDPUtils.parseCandidate(args.candidate);
  3322. var augmentedCandidate = Object.assign(nativeCandidate,
  3323. parsedCandidate);
  3324. // Add a serializer that does not serialize the extra attributes.
  3325. augmentedCandidate.toJSON = function() {
  3326. return {
  3327. candidate: augmentedCandidate.candidate,
  3328. sdpMid: augmentedCandidate.sdpMid,
  3329. sdpMLineIndex: augmentedCandidate.sdpMLineIndex,
  3330. usernameFragment: augmentedCandidate.usernameFragment,
  3331. };
  3332. };
  3333. return augmentedCandidate;
  3334. }
  3335. return new NativeRTCIceCandidate(args);
  3336. };
  3337. window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;
  3338. // Hook up the augmented candidate in onicecandidate and
  3339. // addEventListener('icecandidate', ...)
  3340. utils.wrapPeerConnectionEvent(window, 'icecandidate', function(e) {
  3341. if (e.candidate) {
  3342. Object.defineProperty(e, 'candidate', {
  3343. value: new window.RTCIceCandidate(e.candidate),
  3344. writable: 'false'
  3345. });
  3346. }
  3347. return e;
  3348. });
  3349. },
  3350. // shimCreateObjectURL must be called before shimSourceObject to avoid loop.
  3351. shimCreateObjectURL: function(window) {
  3352. var URL = window && window.URL;
  3353. if (!(typeof window === 'object' && window.HTMLMediaElement &&
  3354. 'srcObject' in window.HTMLMediaElement.prototype &&
  3355. URL.createObjectURL && URL.revokeObjectURL)) {
  3356. // Only shim CreateObjectURL using srcObject if srcObject exists.
  3357. return undefined;
  3358. }
  3359. var nativeCreateObjectURL = URL.createObjectURL.bind(URL);
  3360. var nativeRevokeObjectURL = URL.revokeObjectURL.bind(URL);
  3361. var streams = new Map(), newId = 0;
  3362. URL.createObjectURL = function(stream) {
  3363. if ('getTracks' in stream) {
  3364. var url = 'polyblob:' + (++newId);
  3365. streams.set(url, stream);
  3366. utils.deprecated('URL.createObjectURL(stream)',
  3367. 'elem.srcObject = stream');
  3368. return url;
  3369. }
  3370. return nativeCreateObjectURL(stream);
  3371. };
  3372. URL.revokeObjectURL = function(url) {
  3373. nativeRevokeObjectURL(url);
  3374. streams.delete(url);
  3375. };
  3376. var dsc = Object.getOwnPropertyDescriptor(window.HTMLMediaElement.prototype,
  3377. 'src');
  3378. Object.defineProperty(window.HTMLMediaElement.prototype, 'src', {
  3379. get: function() {
  3380. return dsc.get.apply(this);
  3381. },
  3382. set: function(url) {
  3383. this.srcObject = streams.get(url) || null;
  3384. return dsc.set.apply(this, [url]);
  3385. }
  3386. });
  3387. var nativeSetAttribute = window.HTMLMediaElement.prototype.setAttribute;
  3388. window.HTMLMediaElement.prototype.setAttribute = function() {
  3389. if (arguments.length === 2 &&
  3390. ('' + arguments[0]).toLowerCase() === 'src') {
  3391. this.srcObject = streams.get(arguments[1]) || null;
  3392. }
  3393. return nativeSetAttribute.apply(this, arguments);
  3394. };
  3395. },
  3396. shimMaxMessageSize: function(window) {
  3397. if (window.RTCSctpTransport || !window.RTCPeerConnection) {
  3398. return;
  3399. }
  3400. var browserDetails = utils.detectBrowser(window);
  3401. if (!('sctp' in window.RTCPeerConnection.prototype)) {
  3402. Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {
  3403. get: function() {
  3404. return typeof this._sctp === 'undefined' ? null : this._sctp;
  3405. }
  3406. });
  3407. }
  3408. var sctpInDescription = function(description) {
  3409. var sections = SDPUtils.splitSections(description.sdp);
  3410. sections.shift();
  3411. return sections.some(function(mediaSection) {
  3412. var mLine = SDPUtils.parseMLine(mediaSection);
  3413. return mLine && mLine.kind === 'application'
  3414. && mLine.protocol.indexOf('SCTP') !== -1;
  3415. });
  3416. };
  3417. var getRemoteFirefoxVersion = function(description) {
  3418. // TODO: Is there a better solution for detecting Firefox?
  3419. var match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
  3420. if (match === null || match.length < 2) {
  3421. return -1;
  3422. }
  3423. var version = parseInt(match[1], 10);
  3424. // Test for NaN (yes, this is ugly)
  3425. return version !== version ? -1 : version;
  3426. };
  3427. var getCanSendMaxMessageSize = function(remoteIsFirefox) {
  3428. // Every implementation we know can send at least 64 KiB.
  3429. // Note: Although Chrome is technically able to send up to 256 KiB, the
  3430. // data does not reach the other peer reliably.
  3431. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419
  3432. var canSendMaxMessageSize = 65536;
  3433. if (browserDetails.browser === 'firefox') {
  3434. if (browserDetails.version < 57) {
  3435. if (remoteIsFirefox === -1) {
  3436. // FF < 57 will send in 16 KiB chunks using the deprecated PPID
  3437. // fragmentation.
  3438. canSendMaxMessageSize = 16384;
  3439. } else {
  3440. // However, other FF (and RAWRTC) can reassemble PPID-fragmented
  3441. // messages. Thus, supporting ~2 GiB when sending.
  3442. canSendMaxMessageSize = 2147483637;
  3443. }
  3444. } else {
  3445. // Currently, all FF >= 57 will reset the remote maximum message size
  3446. // to the default value when a data channel is created at a later
  3447. // stage. :(
  3448. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  3449. canSendMaxMessageSize =
  3450. browserDetails.version === 57 ? 65535 : 65536;
  3451. }
  3452. }
  3453. return canSendMaxMessageSize;
  3454. };
  3455. var getMaxMessageSize = function(description, remoteIsFirefox) {
  3456. // Note: 65536 bytes is the default value from the SDP spec. Also,
  3457. // every implementation we know supports receiving 65536 bytes.
  3458. var maxMessageSize = 65536;
  3459. // FF 57 has a slightly incorrect default remote max message size, so
  3460. // we need to adjust it here to avoid a failure when sending.
  3461. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697
  3462. if (browserDetails.browser === 'firefox'
  3463. && browserDetails.version === 57) {
  3464. maxMessageSize = 65535;
  3465. }
  3466. var match = SDPUtils.matchPrefix(description.sdp, 'a=max-message-size:');
  3467. if (match.length > 0) {
  3468. maxMessageSize = parseInt(match[0].substr(19), 10);
  3469. } else if (browserDetails.browser === 'firefox' &&
  3470. remoteIsFirefox !== -1) {
  3471. // If the maximum message size is not present in the remote SDP and
  3472. // both local and remote are Firefox, the remote peer can receive
  3473. // ~2 GiB.
  3474. maxMessageSize = 2147483637;
  3475. }
  3476. return maxMessageSize;
  3477. };
  3478. var origSetRemoteDescription =
  3479. window.RTCPeerConnection.prototype.setRemoteDescription;
  3480. window.RTCPeerConnection.prototype.setRemoteDescription = function() {
  3481. var pc = this;
  3482. pc._sctp = null;
  3483. if (sctpInDescription(arguments[0])) {
  3484. // Check if the remote is FF.
  3485. var isFirefox = getRemoteFirefoxVersion(arguments[0]);
  3486. // Get the maximum message size the local peer is capable of sending
  3487. var canSendMMS = getCanSendMaxMessageSize(isFirefox);
  3488. // Get the maximum message size of the remote peer.
  3489. var remoteMMS = getMaxMessageSize(arguments[0], isFirefox);
  3490. // Determine final maximum message size
  3491. var maxMessageSize;
  3492. if (canSendMMS === 0 && remoteMMS === 0) {
  3493. maxMessageSize = Number.POSITIVE_INFINITY;
  3494. } else if (canSendMMS === 0 || remoteMMS === 0) {
  3495. maxMessageSize = Math.max(canSendMMS, remoteMMS);
  3496. } else {
  3497. maxMessageSize = Math.min(canSendMMS, remoteMMS);
  3498. }
  3499. // Create a dummy RTCSctpTransport object and the 'maxMessageSize'
  3500. // attribute.
  3501. var sctp = {};
  3502. Object.defineProperty(sctp, 'maxMessageSize', {
  3503. get: function() {
  3504. return maxMessageSize;
  3505. }
  3506. });
  3507. pc._sctp = sctp;
  3508. }
  3509. return origSetRemoteDescription.apply(pc, arguments);
  3510. };
  3511. },
  3512. shimSendThrowTypeError: function(window) {
  3513. if (!window.RTCPeerConnection) {
  3514. return;
  3515. }
  3516. // Note: Although Firefox >= 57 has a native implementation, the maximum
  3517. // message size can be reset for all data channels at a later stage.
  3518. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  3519. var origCreateDataChannel =
  3520. window.RTCPeerConnection.prototype.createDataChannel;
  3521. window.RTCPeerConnection.prototype.createDataChannel = function() {
  3522. var pc = this;
  3523. var dataChannel = origCreateDataChannel.apply(pc, arguments);
  3524. var origDataChannelSend = dataChannel.send;
  3525. // Patch 'send' method
  3526. dataChannel.send = function() {
  3527. var dc = this;
  3528. var data = arguments[0];
  3529. var length = data.length || data.size || data.byteLength;
  3530. if (length > pc.sctp.maxMessageSize) {
  3531. throw new DOMException('Message too large (can send a maximum of ' +
  3532. pc.sctp.maxMessageSize + ' bytes)', 'TypeError');
  3533. }
  3534. return origDataChannelSend.apply(dc, arguments);
  3535. };
  3536. return dataChannel;
  3537. };
  3538. }
  3539. };
  3540. },{"./utils":14,"sdp":3}],9:[function(require,module,exports){
  3541. /*
  3542. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3543. *
  3544. * Use of this source code is governed by a BSD-style license
  3545. * that can be found in the LICENSE file in the root of the source
  3546. * tree.
  3547. */
  3548. /* eslint-env node */
  3549. 'use strict';
  3550. var utils = require('../utils');
  3551. var shimRTCPeerConnection = require('rtcpeerconnection-shim');
  3552. module.exports = {
  3553. shimGetUserMedia: require('./getusermedia'),
  3554. shimPeerConnection: function(window) {
  3555. var browserDetails = utils.detectBrowser(window);
  3556. if (window.RTCIceGatherer) {
  3557. if (!window.RTCIceCandidate) {
  3558. window.RTCIceCandidate = function(args) {
  3559. return args;
  3560. };
  3561. }
  3562. if (!window.RTCSessionDescription) {
  3563. window.RTCSessionDescription = function(args) {
  3564. return args;
  3565. };
  3566. }
  3567. // this adds an additional event listener to MediaStrackTrack that signals
  3568. // when a tracks enabled property was changed. Workaround for a bug in
  3569. // addStream, see below. No longer required in 15025+
  3570. if (browserDetails.version < 15025) {
  3571. var origMSTEnabled = Object.getOwnPropertyDescriptor(
  3572. window.MediaStreamTrack.prototype, 'enabled');
  3573. Object.defineProperty(window.MediaStreamTrack.prototype, 'enabled', {
  3574. set: function(value) {
  3575. origMSTEnabled.set.call(this, value);
  3576. var ev = new Event('enabled');
  3577. ev.enabled = value;
  3578. this.dispatchEvent(ev);
  3579. }
  3580. });
  3581. }
  3582. }
  3583. // ORTC defines the DTMF sender a bit different.
  3584. // https://github.com/w3c/ortc/issues/714
  3585. if (window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
  3586. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  3587. get: function() {
  3588. if (this._dtmf === undefined) {
  3589. if (this.track.kind === 'audio') {
  3590. this._dtmf = new window.RTCDtmfSender(this);
  3591. } else if (this.track.kind === 'video') {
  3592. this._dtmf = null;
  3593. }
  3594. }
  3595. return this._dtmf;
  3596. }
  3597. });
  3598. }
  3599. window.RTCPeerConnection =
  3600. shimRTCPeerConnection(window, browserDetails.version);
  3601. },
  3602. shimReplaceTrack: function(window) {
  3603. // ORTC has replaceTrack -- https://github.com/w3c/ortc/issues/614
  3604. if (window.RTCRtpSender &&
  3605. !('replaceTrack' in window.RTCRtpSender.prototype)) {
  3606. window.RTCRtpSender.prototype.replaceTrack =
  3607. window.RTCRtpSender.prototype.setTrack;
  3608. }
  3609. }
  3610. };
  3611. },{"../utils":14,"./getusermedia":10,"rtcpeerconnection-shim":2}],10:[function(require,module,exports){
  3612. /*
  3613. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3614. *
  3615. * Use of this source code is governed by a BSD-style license
  3616. * that can be found in the LICENSE file in the root of the source
  3617. * tree.
  3618. */
  3619. /* eslint-env node */
  3620. 'use strict';
  3621. // Expose public methods.
  3622. module.exports = function(window) {
  3623. var navigator = window && window.navigator;
  3624. var shimError_ = function(e) {
  3625. return {
  3626. name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name,
  3627. message: e.message,
  3628. constraint: e.constraint,
  3629. toString: function() {
  3630. return this.name;
  3631. }
  3632. };
  3633. };
  3634. // getUserMedia error shim.
  3635. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  3636. bind(navigator.mediaDevices);
  3637. navigator.mediaDevices.getUserMedia = function(c) {
  3638. return origGetUserMedia(c).catch(function(e) {
  3639. return Promise.reject(shimError_(e));
  3640. });
  3641. };
  3642. };
  3643. },{}],11:[function(require,module,exports){
  3644. /*
  3645. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3646. *
  3647. * Use of this source code is governed by a BSD-style license
  3648. * that can be found in the LICENSE file in the root of the source
  3649. * tree.
  3650. */
  3651. /* eslint-env node */
  3652. 'use strict';
  3653. var utils = require('../utils');
  3654. module.exports = {
  3655. shimGetUserMedia: require('./getusermedia'),
  3656. shimOnTrack: function(window) {
  3657. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  3658. window.RTCPeerConnection.prototype)) {
  3659. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  3660. get: function() {
  3661. return this._ontrack;
  3662. },
  3663. set: function(f) {
  3664. if (this._ontrack) {
  3665. this.removeEventListener('track', this._ontrack);
  3666. this.removeEventListener('addstream', this._ontrackpoly);
  3667. }
  3668. this.addEventListener('track', this._ontrack = f);
  3669. this.addEventListener('addstream', this._ontrackpoly = function(e) {
  3670. e.stream.getTracks().forEach(function(track) {
  3671. var event = new Event('track');
  3672. event.track = track;
  3673. event.receiver = {track: track};
  3674. event.transceiver = {receiver: event.receiver};
  3675. event.streams = [e.stream];
  3676. this.dispatchEvent(event);
  3677. }.bind(this));
  3678. }.bind(this));
  3679. }
  3680. });
  3681. }
  3682. if (typeof window === 'object' && window.RTCTrackEvent &&
  3683. ('receiver' in window.RTCTrackEvent.prototype) &&
  3684. !('transceiver' in window.RTCTrackEvent.prototype)) {
  3685. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  3686. get: function() {
  3687. return {receiver: this.receiver};
  3688. }
  3689. });
  3690. }
  3691. },
  3692. shimSourceObject: function(window) {
  3693. // Firefox has supported mozSrcObject since FF22, unprefixed in 42.
  3694. if (typeof window === 'object') {
  3695. if (window.HTMLMediaElement &&
  3696. !('srcObject' in window.HTMLMediaElement.prototype)) {
  3697. // Shim the srcObject property, once, when HTMLMediaElement is found.
  3698. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
  3699. get: function() {
  3700. return this.mozSrcObject;
  3701. },
  3702. set: function(stream) {
  3703. this.mozSrcObject = stream;
  3704. }
  3705. });
  3706. }
  3707. }
  3708. },
  3709. shimPeerConnection: function(window) {
  3710. var browserDetails = utils.detectBrowser(window);
  3711. if (typeof window !== 'object' || !(window.RTCPeerConnection ||
  3712. window.mozRTCPeerConnection)) {
  3713. return; // probably media.peerconnection.enabled=false in about:config
  3714. }
  3715. // The RTCPeerConnection object.
  3716. if (!window.RTCPeerConnection) {
  3717. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  3718. if (browserDetails.version < 38) {
  3719. // .urls is not supported in FF < 38.
  3720. // create RTCIceServers with a single url.
  3721. if (pcConfig && pcConfig.iceServers) {
  3722. var newIceServers = [];
  3723. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3724. var server = pcConfig.iceServers[i];
  3725. if (server.hasOwnProperty('urls')) {
  3726. for (var j = 0; j < server.urls.length; j++) {
  3727. var newServer = {
  3728. url: server.urls[j]
  3729. };
  3730. if (server.urls[j].indexOf('turn') === 0) {
  3731. newServer.username = server.username;
  3732. newServer.credential = server.credential;
  3733. }
  3734. newIceServers.push(newServer);
  3735. }
  3736. } else {
  3737. newIceServers.push(pcConfig.iceServers[i]);
  3738. }
  3739. }
  3740. pcConfig.iceServers = newIceServers;
  3741. }
  3742. }
  3743. return new window.mozRTCPeerConnection(pcConfig, pcConstraints);
  3744. };
  3745. window.RTCPeerConnection.prototype =
  3746. window.mozRTCPeerConnection.prototype;
  3747. // wrap static methods. Currently just generateCertificate.
  3748. if (window.mozRTCPeerConnection.generateCertificate) {
  3749. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  3750. get: function() {
  3751. return window.mozRTCPeerConnection.generateCertificate;
  3752. }
  3753. });
  3754. }
  3755. window.RTCSessionDescription = window.mozRTCSessionDescription;
  3756. window.RTCIceCandidate = window.mozRTCIceCandidate;
  3757. }
  3758. // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
  3759. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  3760. .forEach(function(method) {
  3761. var nativeMethod = window.RTCPeerConnection.prototype[method];
  3762. window.RTCPeerConnection.prototype[method] = function() {
  3763. arguments[0] = new ((method === 'addIceCandidate') ?
  3764. window.RTCIceCandidate :
  3765. window.RTCSessionDescription)(arguments[0]);
  3766. return nativeMethod.apply(this, arguments);
  3767. };
  3768. });
  3769. // support for addIceCandidate(null or undefined)
  3770. var nativeAddIceCandidate =
  3771. window.RTCPeerConnection.prototype.addIceCandidate;
  3772. window.RTCPeerConnection.prototype.addIceCandidate = function() {
  3773. if (!arguments[0]) {
  3774. if (arguments[1]) {
  3775. arguments[1].apply(null);
  3776. }
  3777. return Promise.resolve();
  3778. }
  3779. return nativeAddIceCandidate.apply(this, arguments);
  3780. };
  3781. // shim getStats with maplike support
  3782. var makeMapStats = function(stats) {
  3783. var map = new Map();
  3784. Object.keys(stats).forEach(function(key) {
  3785. map.set(key, stats[key]);
  3786. map[key] = stats[key];
  3787. });
  3788. return map;
  3789. };
  3790. var modernStatsTypes = {
  3791. inboundrtp: 'inbound-rtp',
  3792. outboundrtp: 'outbound-rtp',
  3793. candidatepair: 'candidate-pair',
  3794. localcandidate: 'local-candidate',
  3795. remotecandidate: 'remote-candidate'
  3796. };
  3797. var nativeGetStats = window.RTCPeerConnection.prototype.getStats;
  3798. window.RTCPeerConnection.prototype.getStats = function(
  3799. selector,
  3800. onSucc,
  3801. onErr
  3802. ) {
  3803. return nativeGetStats.apply(this, [selector || null])
  3804. .then(function(stats) {
  3805. if (browserDetails.version < 48) {
  3806. stats = makeMapStats(stats);
  3807. }
  3808. if (browserDetails.version < 53 && !onSucc) {
  3809. // Shim only promise getStats with spec-hyphens in type names
  3810. // Leave callback version alone; misc old uses of forEach before Map
  3811. try {
  3812. stats.forEach(function(stat) {
  3813. stat.type = modernStatsTypes[stat.type] || stat.type;
  3814. });
  3815. } catch (e) {
  3816. if (e.name !== 'TypeError') {
  3817. throw e;
  3818. }
  3819. // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
  3820. stats.forEach(function(stat, i) {
  3821. stats.set(i, Object.assign({}, stat, {
  3822. type: modernStatsTypes[stat.type] || stat.type
  3823. }));
  3824. });
  3825. }
  3826. }
  3827. return stats;
  3828. })
  3829. .then(onSucc, onErr);
  3830. };
  3831. },
  3832. shimRemoveStream: function(window) {
  3833. if (!window.RTCPeerConnection ||
  3834. 'removeStream' in window.RTCPeerConnection.prototype) {
  3835. return;
  3836. }
  3837. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  3838. var pc = this;
  3839. utils.deprecated('removeStream', 'removeTrack');
  3840. this.getSenders().forEach(function(sender) {
  3841. if (sender.track && stream.getTracks().indexOf(sender.track) !== -1) {
  3842. pc.removeTrack(sender);
  3843. }
  3844. });
  3845. };
  3846. }
  3847. };
  3848. },{"../utils":14,"./getusermedia":12}],12:[function(require,module,exports){
  3849. /*
  3850. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3851. *
  3852. * Use of this source code is governed by a BSD-style license
  3853. * that can be found in the LICENSE file in the root of the source
  3854. * tree.
  3855. */
  3856. /* eslint-env node */
  3857. 'use strict';
  3858. var utils = require('../utils');
  3859. var logging = utils.log;
  3860. // Expose public methods.
  3861. module.exports = function(window) {
  3862. var browserDetails = utils.detectBrowser(window);
  3863. var navigator = window && window.navigator;
  3864. var MediaStreamTrack = window && window.MediaStreamTrack;
  3865. var shimError_ = function(e) {
  3866. return {
  3867. name: {
  3868. InternalError: 'NotReadableError',
  3869. NotSupportedError: 'TypeError',
  3870. PermissionDeniedError: 'NotAllowedError',
  3871. SecurityError: 'NotAllowedError'
  3872. }[e.name] || e.name,
  3873. message: {
  3874. 'The operation is insecure.': 'The request is not allowed by the ' +
  3875. 'user agent or the platform in the current context.'
  3876. }[e.message] || e.message,
  3877. constraint: e.constraint,
  3878. toString: function() {
  3879. return this.name + (this.message && ': ') + this.message;
  3880. }
  3881. };
  3882. };
  3883. // getUserMedia constraints shim.
  3884. var getUserMedia_ = function(constraints, onSuccess, onError) {
  3885. var constraintsToFF37_ = function(c) {
  3886. if (typeof c !== 'object' || c.require) {
  3887. return c;
  3888. }
  3889. var require = [];
  3890. Object.keys(c).forEach(function(key) {
  3891. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  3892. return;
  3893. }
  3894. var r = c[key] = (typeof c[key] === 'object') ?
  3895. c[key] : {ideal: c[key]};
  3896. if (r.min !== undefined ||
  3897. r.max !== undefined || r.exact !== undefined) {
  3898. require.push(key);
  3899. }
  3900. if (r.exact !== undefined) {
  3901. if (typeof r.exact === 'number') {
  3902. r. min = r.max = r.exact;
  3903. } else {
  3904. c[key] = r.exact;
  3905. }
  3906. delete r.exact;
  3907. }
  3908. if (r.ideal !== undefined) {
  3909. c.advanced = c.advanced || [];
  3910. var oc = {};
  3911. if (typeof r.ideal === 'number') {
  3912. oc[key] = {min: r.ideal, max: r.ideal};
  3913. } else {
  3914. oc[key] = r.ideal;
  3915. }
  3916. c.advanced.push(oc);
  3917. delete r.ideal;
  3918. if (!Object.keys(r).length) {
  3919. delete c[key];
  3920. }
  3921. }
  3922. });
  3923. if (require.length) {
  3924. c.require = require;
  3925. }
  3926. return c;
  3927. };
  3928. constraints = JSON.parse(JSON.stringify(constraints));
  3929. if (browserDetails.version < 38) {
  3930. logging('spec: ' + JSON.stringify(constraints));
  3931. if (constraints.audio) {
  3932. constraints.audio = constraintsToFF37_(constraints.audio);
  3933. }
  3934. if (constraints.video) {
  3935. constraints.video = constraintsToFF37_(constraints.video);
  3936. }
  3937. logging('ff37: ' + JSON.stringify(constraints));
  3938. }
  3939. return navigator.mozGetUserMedia(constraints, onSuccess, function(e) {
  3940. onError(shimError_(e));
  3941. });
  3942. };
  3943. // Returns the result of getUserMedia as a Promise.
  3944. var getUserMediaPromise_ = function(constraints) {
  3945. return new Promise(function(resolve, reject) {
  3946. getUserMedia_(constraints, resolve, reject);
  3947. });
  3948. };
  3949. // Shim for mediaDevices on older versions.
  3950. if (!navigator.mediaDevices) {
  3951. navigator.mediaDevices = {getUserMedia: getUserMediaPromise_,
  3952. addEventListener: function() { },
  3953. removeEventListener: function() { }
  3954. };
  3955. }
  3956. navigator.mediaDevices.enumerateDevices =
  3957. navigator.mediaDevices.enumerateDevices || function() {
  3958. return new Promise(function(resolve) {
  3959. var infos = [
  3960. {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
  3961. {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
  3962. ];
  3963. resolve(infos);
  3964. });
  3965. };
  3966. if (browserDetails.version < 41) {
  3967. // Work around http://bugzil.la/1169665
  3968. var orgEnumerateDevices =
  3969. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
  3970. navigator.mediaDevices.enumerateDevices = function() {
  3971. return orgEnumerateDevices().then(undefined, function(e) {
  3972. if (e.name === 'NotFoundError') {
  3973. return [];
  3974. }
  3975. throw e;
  3976. });
  3977. };
  3978. }
  3979. if (browserDetails.version < 49) {
  3980. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  3981. bind(navigator.mediaDevices);
  3982. navigator.mediaDevices.getUserMedia = function(c) {
  3983. return origGetUserMedia(c).then(function(stream) {
  3984. // Work around https://bugzil.la/802326
  3985. if (c.audio && !stream.getAudioTracks().length ||
  3986. c.video && !stream.getVideoTracks().length) {
  3987. stream.getTracks().forEach(function(track) {
  3988. track.stop();
  3989. });
  3990. throw new DOMException('The object can not be found here.',
  3991. 'NotFoundError');
  3992. }
  3993. return stream;
  3994. }, function(e) {
  3995. return Promise.reject(shimError_(e));
  3996. });
  3997. };
  3998. }
  3999. if (!(browserDetails.version > 55 &&
  4000. 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
  4001. var remap = function(obj, a, b) {
  4002. if (a in obj && !(b in obj)) {
  4003. obj[b] = obj[a];
  4004. delete obj[a];
  4005. }
  4006. };
  4007. var nativeGetUserMedia = navigator.mediaDevices.getUserMedia.
  4008. bind(navigator.mediaDevices);
  4009. navigator.mediaDevices.getUserMedia = function(c) {
  4010. if (typeof c === 'object' && typeof c.audio === 'object') {
  4011. c = JSON.parse(JSON.stringify(c));
  4012. remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
  4013. remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
  4014. }
  4015. return nativeGetUserMedia(c);
  4016. };
  4017. if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
  4018. var nativeGetSettings = MediaStreamTrack.prototype.getSettings;
  4019. MediaStreamTrack.prototype.getSettings = function() {
  4020. var obj = nativeGetSettings.apply(this, arguments);
  4021. remap(obj, 'mozAutoGainControl', 'autoGainControl');
  4022. remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
  4023. return obj;
  4024. };
  4025. }
  4026. if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
  4027. var nativeApplyConstraints = MediaStreamTrack.prototype.applyConstraints;
  4028. MediaStreamTrack.prototype.applyConstraints = function(c) {
  4029. if (this.kind === 'audio' && typeof c === 'object') {
  4030. c = JSON.parse(JSON.stringify(c));
  4031. remap(c, 'autoGainControl', 'mozAutoGainControl');
  4032. remap(c, 'noiseSuppression', 'mozNoiseSuppression');
  4033. }
  4034. return nativeApplyConstraints.apply(this, [c]);
  4035. };
  4036. }
  4037. }
  4038. navigator.getUserMedia = function(constraints, onSuccess, onError) {
  4039. if (browserDetails.version < 44) {
  4040. return getUserMedia_(constraints, onSuccess, onError);
  4041. }
  4042. // Replace Firefox 44+'s deprecation warning with unprefixed version.
  4043. utils.deprecated('navigator.getUserMedia',
  4044. 'navigator.mediaDevices.getUserMedia');
  4045. navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  4046. };
  4047. };
  4048. },{"../utils":14}],13:[function(require,module,exports){
  4049. /*
  4050. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4051. *
  4052. * Use of this source code is governed by a BSD-style license
  4053. * that can be found in the LICENSE file in the root of the source
  4054. * tree.
  4055. */
  4056. 'use strict';
  4057. var utils = require('../utils');
  4058. module.exports = {
  4059. shimLocalStreamsAPI: function(window) {
  4060. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4061. return;
  4062. }
  4063. if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
  4064. window.RTCPeerConnection.prototype.getLocalStreams = function() {
  4065. if (!this._localStreams) {
  4066. this._localStreams = [];
  4067. }
  4068. return this._localStreams;
  4069. };
  4070. }
  4071. if (!('getStreamById' in window.RTCPeerConnection.prototype)) {
  4072. window.RTCPeerConnection.prototype.getStreamById = function(id) {
  4073. var result = null;
  4074. if (this._localStreams) {
  4075. this._localStreams.forEach(function(stream) {
  4076. if (stream.id === id) {
  4077. result = stream;
  4078. }
  4079. });
  4080. }
  4081. if (this._remoteStreams) {
  4082. this._remoteStreams.forEach(function(stream) {
  4083. if (stream.id === id) {
  4084. result = stream;
  4085. }
  4086. });
  4087. }
  4088. return result;
  4089. };
  4090. }
  4091. if (!('addStream' in window.RTCPeerConnection.prototype)) {
  4092. var _addTrack = window.RTCPeerConnection.prototype.addTrack;
  4093. window.RTCPeerConnection.prototype.addStream = function(stream) {
  4094. if (!this._localStreams) {
  4095. this._localStreams = [];
  4096. }
  4097. if (this._localStreams.indexOf(stream) === -1) {
  4098. this._localStreams.push(stream);
  4099. }
  4100. var pc = this;
  4101. stream.getTracks().forEach(function(track) {
  4102. _addTrack.call(pc, track, stream);
  4103. });
  4104. };
  4105. window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
  4106. if (stream) {
  4107. if (!this._localStreams) {
  4108. this._localStreams = [stream];
  4109. } else if (this._localStreams.indexOf(stream) === -1) {
  4110. this._localStreams.push(stream);
  4111. }
  4112. }
  4113. return _addTrack.call(this, track, stream);
  4114. };
  4115. }
  4116. if (!('removeStream' in window.RTCPeerConnection.prototype)) {
  4117. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  4118. if (!this._localStreams) {
  4119. this._localStreams = [];
  4120. }
  4121. var index = this._localStreams.indexOf(stream);
  4122. if (index === -1) {
  4123. return;
  4124. }
  4125. this._localStreams.splice(index, 1);
  4126. var pc = this;
  4127. var tracks = stream.getTracks();
  4128. this.getSenders().forEach(function(sender) {
  4129. if (tracks.indexOf(sender.track) !== -1) {
  4130. pc.removeTrack(sender);
  4131. }
  4132. });
  4133. };
  4134. }
  4135. },
  4136. shimRemoteStreamsAPI: function(window) {
  4137. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4138. return;
  4139. }
  4140. if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
  4141. window.RTCPeerConnection.prototype.getRemoteStreams = function() {
  4142. return this._remoteStreams ? this._remoteStreams : [];
  4143. };
  4144. }
  4145. if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
  4146. Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
  4147. get: function() {
  4148. return this._onaddstream;
  4149. },
  4150. set: function(f) {
  4151. var pc = this;
  4152. if (this._onaddstream) {
  4153. this.removeEventListener('addstream', this._onaddstream);
  4154. this.removeEventListener('track', this._onaddstreampoly);
  4155. }
  4156. this.addEventListener('addstream', this._onaddstream = f);
  4157. this.addEventListener('track', this._onaddstreampoly = function(e) {
  4158. e.streams.forEach(function(stream) {
  4159. if (!pc._remoteStreams) {
  4160. pc._remoteStreams = [];
  4161. }
  4162. if (pc._remoteStreams.indexOf(stream) >= 0) {
  4163. return;
  4164. }
  4165. pc._remoteStreams.push(stream);
  4166. var event = new Event('addstream');
  4167. event.stream = stream;
  4168. pc.dispatchEvent(event);
  4169. });
  4170. });
  4171. }
  4172. });
  4173. }
  4174. },
  4175. shimCallbacksAPI: function(window) {
  4176. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4177. return;
  4178. }
  4179. var prototype = window.RTCPeerConnection.prototype;
  4180. var createOffer = prototype.createOffer;
  4181. var createAnswer = prototype.createAnswer;
  4182. var setLocalDescription = prototype.setLocalDescription;
  4183. var setRemoteDescription = prototype.setRemoteDescription;
  4184. var addIceCandidate = prototype.addIceCandidate;
  4185. prototype.createOffer = function(successCallback, failureCallback) {
  4186. var options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  4187. var promise = createOffer.apply(this, [options]);
  4188. if (!failureCallback) {
  4189. return promise;
  4190. }
  4191. promise.then(successCallback, failureCallback);
  4192. return Promise.resolve();
  4193. };
  4194. prototype.createAnswer = function(successCallback, failureCallback) {
  4195. var options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  4196. var promise = createAnswer.apply(this, [options]);
  4197. if (!failureCallback) {
  4198. return promise;
  4199. }
  4200. promise.then(successCallback, failureCallback);
  4201. return Promise.resolve();
  4202. };
  4203. var withCallback = function(description, successCallback, failureCallback) {
  4204. var promise = setLocalDescription.apply(this, [description]);
  4205. if (!failureCallback) {
  4206. return promise;
  4207. }
  4208. promise.then(successCallback, failureCallback);
  4209. return Promise.resolve();
  4210. };
  4211. prototype.setLocalDescription = withCallback;
  4212. withCallback = function(description, successCallback, failureCallback) {
  4213. var promise = setRemoteDescription.apply(this, [description]);
  4214. if (!failureCallback) {
  4215. return promise;
  4216. }
  4217. promise.then(successCallback, failureCallback);
  4218. return Promise.resolve();
  4219. };
  4220. prototype.setRemoteDescription = withCallback;
  4221. withCallback = function(candidate, successCallback, failureCallback) {
  4222. var promise = addIceCandidate.apply(this, [candidate]);
  4223. if (!failureCallback) {
  4224. return promise;
  4225. }
  4226. promise.then(successCallback, failureCallback);
  4227. return Promise.resolve();
  4228. };
  4229. prototype.addIceCandidate = withCallback;
  4230. },
  4231. shimGetUserMedia: function(window) {
  4232. var navigator = window && window.navigator;
  4233. if (!navigator.getUserMedia) {
  4234. if (navigator.webkitGetUserMedia) {
  4235. navigator.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4236. } else if (navigator.mediaDevices &&
  4237. navigator.mediaDevices.getUserMedia) {
  4238. navigator.getUserMedia = function(constraints, cb, errcb) {
  4239. navigator.mediaDevices.getUserMedia(constraints)
  4240. .then(cb, errcb);
  4241. }.bind(navigator);
  4242. }
  4243. }
  4244. },
  4245. shimRTCIceServerUrls: function(window) {
  4246. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  4247. var OrigPeerConnection = window.RTCPeerConnection;
  4248. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  4249. if (pcConfig && pcConfig.iceServers) {
  4250. var newIceServers = [];
  4251. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  4252. var server = pcConfig.iceServers[i];
  4253. if (!server.hasOwnProperty('urls') &&
  4254. server.hasOwnProperty('url')) {
  4255. utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  4256. server = JSON.parse(JSON.stringify(server));
  4257. server.urls = server.url;
  4258. delete server.url;
  4259. newIceServers.push(server);
  4260. } else {
  4261. newIceServers.push(pcConfig.iceServers[i]);
  4262. }
  4263. }
  4264. pcConfig.iceServers = newIceServers;
  4265. }
  4266. return new OrigPeerConnection(pcConfig, pcConstraints);
  4267. };
  4268. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  4269. // wrap static methods. Currently just generateCertificate.
  4270. if ('generateCertificate' in window.RTCPeerConnection) {
  4271. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  4272. get: function() {
  4273. return OrigPeerConnection.generateCertificate;
  4274. }
  4275. });
  4276. }
  4277. },
  4278. shimTrackEventTransceiver: function(window) {
  4279. // Add event.transceiver member over deprecated event.receiver
  4280. if (typeof window === 'object' && window.RTCPeerConnection &&
  4281. ('receiver' in window.RTCTrackEvent.prototype) &&
  4282. // can't check 'transceiver' in window.RTCTrackEvent.prototype, as it is
  4283. // defined for some reason even when window.RTCTransceiver is not.
  4284. !window.RTCTransceiver) {
  4285. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  4286. get: function() {
  4287. return {receiver: this.receiver};
  4288. }
  4289. });
  4290. }
  4291. },
  4292. shimCreateOfferLegacy: function(window) {
  4293. var origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  4294. window.RTCPeerConnection.prototype.createOffer = function(offerOptions) {
  4295. var pc = this;
  4296. if (offerOptions) {
  4297. var audioTransceiver = pc.getTransceivers().find(function(transceiver) {
  4298. return transceiver.sender.track &&
  4299. transceiver.sender.track.kind === 'audio';
  4300. });
  4301. if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {
  4302. if (audioTransceiver.direction === 'sendrecv') {
  4303. if (audioTransceiver.setDirection) {
  4304. audioTransceiver.setDirection('sendonly');
  4305. } else {
  4306. audioTransceiver.direction = 'sendonly';
  4307. }
  4308. } else if (audioTransceiver.direction === 'recvonly') {
  4309. if (audioTransceiver.setDirection) {
  4310. audioTransceiver.setDirection('inactive');
  4311. } else {
  4312. audioTransceiver.direction = 'inactive';
  4313. }
  4314. }
  4315. } else if (offerOptions.offerToReceiveAudio === true &&
  4316. !audioTransceiver) {
  4317. pc.addTransceiver('audio');
  4318. }
  4319. var videoTransceiver = pc.getTransceivers().find(function(transceiver) {
  4320. return transceiver.sender.track &&
  4321. transceiver.sender.track.kind === 'video';
  4322. });
  4323. if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {
  4324. if (videoTransceiver.direction === 'sendrecv') {
  4325. videoTransceiver.setDirection('sendonly');
  4326. } else if (videoTransceiver.direction === 'recvonly') {
  4327. videoTransceiver.setDirection('inactive');
  4328. }
  4329. } else if (offerOptions.offerToReceiveVideo === true &&
  4330. !videoTransceiver) {
  4331. pc.addTransceiver('video');
  4332. }
  4333. }
  4334. return origCreateOffer.apply(pc, arguments);
  4335. };
  4336. }
  4337. };
  4338. },{"../utils":14}],14:[function(require,module,exports){
  4339. /*
  4340. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4341. *
  4342. * Use of this source code is governed by a BSD-style license
  4343. * that can be found in the LICENSE file in the root of the source
  4344. * tree.
  4345. */
  4346. /* eslint-env node */
  4347. 'use strict';
  4348. var logDisabled_ = true;
  4349. var deprecationWarnings_ = true;
  4350. /**
  4351. * Extract browser version out of the provided user agent string.
  4352. *
  4353. * @param {!string} uastring userAgent string.
  4354. * @param {!string} expr Regular expression used as match criteria.
  4355. * @param {!number} pos position in the version string to be returned.
  4356. * @return {!number} browser version.
  4357. */
  4358. function extractVersion(uastring, expr, pos) {
  4359. var match = uastring.match(expr);
  4360. return match && match.length >= pos && parseInt(match[pos], 10);
  4361. }
  4362. // Wraps the peerconnection event eventNameToWrap in a function
  4363. // which returns the modified event object.
  4364. function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {
  4365. if (!window.RTCPeerConnection) {
  4366. return;
  4367. }
  4368. var proto = window.RTCPeerConnection.prototype;
  4369. var nativeAddEventListener = proto.addEventListener;
  4370. proto.addEventListener = function(nativeEventName, cb) {
  4371. if (nativeEventName !== eventNameToWrap) {
  4372. return nativeAddEventListener.apply(this, arguments);
  4373. }
  4374. var wrappedCallback = function(e) {
  4375. cb(wrapper(e));
  4376. };
  4377. this._eventMap = this._eventMap || {};
  4378. this._eventMap[cb] = wrappedCallback;
  4379. return nativeAddEventListener.apply(this, [nativeEventName,
  4380. wrappedCallback]);
  4381. };
  4382. var nativeRemoveEventListener = proto.removeEventListener;
  4383. proto.removeEventListener = function(nativeEventName, cb) {
  4384. if (nativeEventName !== eventNameToWrap || !this._eventMap
  4385. || !this._eventMap[cb]) {
  4386. return nativeRemoveEventListener.apply(this, arguments);
  4387. }
  4388. var unwrappedCb = this._eventMap[cb];
  4389. delete this._eventMap[cb];
  4390. return nativeRemoveEventListener.apply(this, [nativeEventName,
  4391. unwrappedCb]);
  4392. };
  4393. Object.defineProperty(proto, 'on' + eventNameToWrap, {
  4394. get: function() {
  4395. return this['_on' + eventNameToWrap];
  4396. },
  4397. set: function(cb) {
  4398. if (this['_on' + eventNameToWrap]) {
  4399. this.removeEventListener(eventNameToWrap,
  4400. this['_on' + eventNameToWrap]);
  4401. delete this['_on' + eventNameToWrap];
  4402. }
  4403. if (cb) {
  4404. this.addEventListener(eventNameToWrap,
  4405. this['_on' + eventNameToWrap] = cb);
  4406. }
  4407. }
  4408. });
  4409. }
  4410. // Utility methods.
  4411. module.exports = {
  4412. extractVersion: extractVersion,
  4413. wrapPeerConnectionEvent: wrapPeerConnectionEvent,
  4414. disableLog: function(bool) {
  4415. if (typeof bool !== 'boolean') {
  4416. return new Error('Argument type: ' + typeof bool +
  4417. '. Please use a boolean.');
  4418. }
  4419. logDisabled_ = bool;
  4420. return (bool) ? 'adapter.js logging disabled' :
  4421. 'adapter.js logging enabled';
  4422. },
  4423. /**
  4424. * Disable or enable deprecation warnings
  4425. * @param {!boolean} bool set to true to disable warnings.
  4426. */
  4427. disableWarnings: function(bool) {
  4428. if (typeof bool !== 'boolean') {
  4429. return new Error('Argument type: ' + typeof bool +
  4430. '. Please use a boolean.');
  4431. }
  4432. deprecationWarnings_ = !bool;
  4433. return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
  4434. },
  4435. log: function() {
  4436. if (typeof window === 'object') {
  4437. if (logDisabled_) {
  4438. return;
  4439. }
  4440. if (typeof console !== 'undefined' && typeof console.log === 'function') {
  4441. console.log.apply(console, arguments);
  4442. }
  4443. }
  4444. },
  4445. /**
  4446. * Shows a deprecation warning suggesting the modern and spec-compatible API.
  4447. */
  4448. deprecated: function(oldMethod, newMethod) {
  4449. if (!deprecationWarnings_) {
  4450. return;
  4451. }
  4452. console.warn(oldMethod + ' is deprecated, please use ' + newMethod +
  4453. ' instead.');
  4454. },
  4455. /**
  4456. * Browser detector.
  4457. *
  4458. * @return {object} result containing browser and version
  4459. * properties.
  4460. */
  4461. detectBrowser: function(window) {
  4462. var navigator = window && window.navigator;
  4463. // Returned result object.
  4464. var result = {};
  4465. result.browser = null;
  4466. result.version = null;
  4467. // Fail early if it's not a browser
  4468. if (typeof window === 'undefined' || !window.navigator) {
  4469. result.browser = 'Not a browser.';
  4470. return result;
  4471. }
  4472. if (navigator.mozGetUserMedia) { // Firefox.
  4473. result.browser = 'firefox';
  4474. result.version = extractVersion(navigator.userAgent,
  4475. /Firefox\/(\d+)\./, 1);
  4476. } else if (navigator.webkitGetUserMedia) {
  4477. // Chrome, Chromium, Webview, Opera.
  4478. // Version matches Chrome/WebRTC version.
  4479. result.browser = 'chrome';
  4480. result.version = extractVersion(navigator.userAgent,
  4481. /Chrom(e|ium)\/(\d+)\./, 2);
  4482. } else if (navigator.mediaDevices &&
  4483. navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge.
  4484. result.browser = 'edge';
  4485. result.version = extractVersion(navigator.userAgent,
  4486. /Edge\/(\d+).(\d+)$/, 2);
  4487. } else if (window.RTCPeerConnection &&
  4488. navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) { // Safari.
  4489. result.browser = 'safari';
  4490. result.version = extractVersion(navigator.userAgent,
  4491. /AppleWebKit\/(\d+)\./, 1);
  4492. } else { // Default fallthrough: not supported.
  4493. result.browser = 'Not a supported browser.';
  4494. return result;
  4495. }
  4496. return result;
  4497. }
  4498. };
  4499. },{}]},{},[4])(4)
  4500. });