pa_asio.cpp 159 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252
  1. /*
  2. * $Id: pa_asio.cpp 1890 2013-05-02 01:06:01Z rbencina $
  3. * Portable Audio I/O Library for ASIO Drivers
  4. *
  5. * Author: Stephane Letz
  6. * Based on the Open Source API proposed by Ross Bencina
  7. * Copyright (c) 2000-2002 Stephane Letz, Phil Burk, Ross Bencina
  8. * Blocking i/o implementation by Sven Fischer, Institute of Hearing
  9. * Technology and Audiology (www.hoertechnik-audiologie.de)
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining
  12. * a copy of this software and associated documentation files
  13. * (the "Software"), to deal in the Software without restriction,
  14. * including without limitation the rights to use, copy, modify, merge,
  15. * publish, distribute, sublicense, and/or sell copies of the Software,
  16. * and to permit persons to whom the Software is furnished to do so,
  17. * subject to the following conditions:
  18. *
  19. * The above copyright notice and this permission notice shall be
  20. * included in all copies or substantial portions of the Software.
  21. *
  22. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  25. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  26. * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  27. * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. */
  30. /*
  31. * The text above constitutes the entire PortAudio license; however,
  32. * the PortAudio community also makes the following non-binding requests:
  33. *
  34. * Any person wishing to distribute modifications to the Software is
  35. * requested to send the modifications to the original developer so that
  36. * they can be incorporated into the canonical version. It is also
  37. * requested that these non-binding requests be included along with the
  38. * license above.
  39. */
  40. /* Modification History
  41. 08-03-01 First version : Stephane Letz
  42. 08-06-01 Tweaks for PC, use C++, buffer allocation, Float32 to Int32 conversion : Phil Burk
  43. 08-20-01 More conversion, PA_StreamTime, Pa_GetHostError : Stephane Letz
  44. 08-21-01 PaUInt8 bug correction, implementation of ASIOSTFloat32LSB and ASIOSTFloat32MSB native formats : Stephane Letz
  45. 08-24-01 MAX_INT32_FP hack, another Uint8 fix : Stephane and Phil
  46. 08-27-01 Implementation of hostBufferSize < userBufferSize case, better management of the ouput buffer when
  47. the stream is stopped : Stephane Letz
  48. 08-28-01 Check the stream pointer for null in bufferSwitchTimeInfo, correct bug in bufferSwitchTimeInfo when
  49. the stream is stopped : Stephane Letz
  50. 10-12-01 Correct the PaHost_CalcNumHostBuffers function: computes FramesPerHostBuffer to be the lowest that
  51. respect requested FramesPerUserBuffer and userBuffersPerHostBuffer : Stephane Letz
  52. 10-26-01 Management of hostBufferSize and userBufferSize of any size : Stephane Letz
  53. 10-27-01 Improve calculus of hostBufferSize to be multiple or divisor of userBufferSize if possible : Stephane and Phil
  54. 10-29-01 Change MAX_INT32_FP to (2147483520.0f) to prevent roundup to 0x80000000 : Phil Burk
  55. 10-31-01 Clear the ouput buffer and user buffers in PaHost_StartOutput, correct bug in GetFirstMultiple : Stephane Letz
  56. 11-06-01 Rename functions : Stephane Letz
  57. 11-08-01 New Pa_ASIO_Adaptor_Init function to init Callback adpatation variables, cleanup of Pa_ASIO_Callback_Input: Stephane Letz
  58. 11-29-01 Break apart device loading to debug random failure in Pa_ASIO_QueryDeviceInfo ; Phil Burk
  59. 01-03-02 Desallocate all resources in PaHost_Term for cases where Pa_CloseStream is not called properly : Stephane Letz
  60. 02-01-02 Cleanup, test of multiple-stream opening : Stephane Letz
  61. 19-02-02 New Pa_ASIO_loadDriver that calls CoInitialize on each thread on Windows : Stephane Letz
  62. 09-04-02 Correct error code management in PaHost_Term, removes various compiler warning : Stephane Letz
  63. 12-04-02 Add Mac includes for <Devices.h> and <Timer.h> : Phil Burk
  64. 13-04-02 Removes another compiler warning : Stephane Letz
  65. 30-04-02 Pa_ASIO_QueryDeviceInfo bug correction, memory allocation checking, better error handling : D Viens, P Burk, S Letz
  66. 12-06-02 Rehashed into new multi-api infrastructure, added support for all ASIO sample formats : Ross Bencina
  67. 18-06-02 Added pa_asio.h, PaAsio_GetAvailableLatencyValues() : Ross B.
  68. 21-06-02 Added SelectHostBufferSize() which selects host buffer size based on user latency parameters : Ross Bencina
  69. ** NOTE maintanance history is now stored in CVS **
  70. */
  71. /** @file
  72. @ingroup hostapi_src
  73. Note that specific support for paInputUnderflow, paOutputOverflow and
  74. paNeverDropInput is not necessary or possible with this driver due to the
  75. synchronous full duplex double-buffered architecture of ASIO.
  76. */
  77. #include <stdio.h>
  78. #include <assert.h>
  79. #include <string.h>
  80. //#include <values.h>
  81. #include <new>
  82. #include <windows.h>
  83. #include <mmsystem.h>
  84. #include "portaudio.h"
  85. #include "pa_asio.h"
  86. #include "pa_util.h"
  87. #include "pa_allocation.h"
  88. #include "pa_hostapi.h"
  89. #include "pa_stream.h"
  90. #include "pa_cpuload.h"
  91. #include "pa_process.h"
  92. #include "pa_debugprint.h"
  93. #include "pa_ringbuffer.h"
  94. #include "pa_win_coinitialize.h"
  95. /* This version of pa_asio.cpp is currently only targetted at Win32,
  96. It would require a few tweaks to work with pre-OS X Macintosh.
  97. To make configuration easier, we define WIN32 here to make sure
  98. that the ASIO SDK knows this is Win32.
  99. */
  100. #ifndef WIN32
  101. #define WIN32
  102. #endif
  103. #include "asiosys.h"
  104. #include "asio.h"
  105. #include "asiodrivers.h"
  106. #include "iasiothiscallresolver.h"
  107. /*
  108. #if MAC
  109. #include <Devices.h>
  110. #include <Timer.h>
  111. #include <Math64.h>
  112. #else
  113. */
  114. /*
  115. #include <math.h>
  116. #include <windows.h>
  117. #include <mmsystem.h>
  118. */
  119. /*
  120. #endif
  121. */
  122. /* winmm.lib is needed for timeGetTime() (this is in winmm.a if you're using gcc) */
  123. #if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
  124. #pragma comment(lib, "winmm.lib")
  125. #endif
  126. /* external reference to ASIO SDK's asioDrivers.
  127. This is a bit messy because we want to explicitly manage
  128. allocation/deallocation of this structure, but some layers of the SDK
  129. which we currently use (eg the implementation in asio.cpp) still
  130. use this global version.
  131. For now we keep it in sync with our local instance in the host
  132. API representation structure, but later we should be able to remove
  133. all dependence on it.
  134. */
  135. extern AsioDrivers* asioDrivers;
  136. /* We are trying to be compatible with CARBON but this has not been thoroughly tested. */
  137. /* not tested at all since new V19 code was introduced. */
  138. #define CARBON_COMPATIBLE (0)
  139. /* prototypes for functions declared in this file */
  140. extern "C" PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex );
  141. static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
  142. static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
  143. PaStream** s,
  144. const PaStreamParameters *inputParameters,
  145. const PaStreamParameters *outputParameters,
  146. double sampleRate,
  147. unsigned long framesPerBuffer,
  148. PaStreamFlags streamFlags,
  149. PaStreamCallback *streamCallback,
  150. void *userData );
  151. static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
  152. const PaStreamParameters *inputParameters,
  153. const PaStreamParameters *outputParameters,
  154. double sampleRate );
  155. static PaError CloseStream( PaStream* stream );
  156. static PaError StartStream( PaStream *stream );
  157. static PaError StopStream( PaStream *stream );
  158. static PaError AbortStream( PaStream *stream );
  159. static PaError IsStreamStopped( PaStream *s );
  160. static PaError IsStreamActive( PaStream *stream );
  161. static PaTime GetStreamTime( PaStream *stream );
  162. static double GetStreamCpuLoad( PaStream* stream );
  163. static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
  164. static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
  165. static signed long GetStreamReadAvailable( PaStream* stream );
  166. static signed long GetStreamWriteAvailable( PaStream* stream );
  167. /* Blocking i/o callback function. */
  168. static int BlockingIoPaCallback(const void *inputBuffer ,
  169. void *outputBuffer ,
  170. unsigned long framesPerBuffer,
  171. const PaStreamCallbackTimeInfo *timeInfo ,
  172. PaStreamCallbackFlags statusFlags ,
  173. void *userData );
  174. /* our ASIO callback functions */
  175. static void bufferSwitch(long index, ASIOBool processNow);
  176. static ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow);
  177. static void sampleRateChanged(ASIOSampleRate sRate);
  178. static long asioMessages(long selector, long value, void* message, double* opt);
  179. static ASIOCallbacks asioCallbacks_ =
  180. { bufferSwitch, sampleRateChanged, asioMessages, bufferSwitchTimeInfo };
  181. #define PA_ASIO_SET_LAST_HOST_ERROR( errorCode, errorText ) \
  182. PaUtil_SetLastHostErrorInfo( paASIO, errorCode, errorText )
  183. static void PaAsio_SetLastSystemError( DWORD errorCode )
  184. {
  185. LPVOID lpMsgBuf;
  186. FormatMessage(
  187. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  188. NULL,
  189. errorCode,
  190. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  191. (LPTSTR) &lpMsgBuf,
  192. 0,
  193. NULL
  194. );
  195. PaUtil_SetLastHostErrorInfo( paASIO, errorCode, (const char*)lpMsgBuf );
  196. LocalFree( lpMsgBuf );
  197. }
  198. #define PA_ASIO_SET_LAST_SYSTEM_ERROR( errorCode ) \
  199. PaAsio_SetLastSystemError( errorCode )
  200. static const char* PaAsio_GetAsioErrorText( ASIOError asioError )
  201. {
  202. const char *result;
  203. switch( asioError ){
  204. case ASE_OK:
  205. case ASE_SUCCESS: result = "Success"; break;
  206. case ASE_NotPresent: result = "Hardware input or output is not present or available"; break;
  207. case ASE_HWMalfunction: result = "Hardware is malfunctioning"; break;
  208. case ASE_InvalidParameter: result = "Input parameter invalid"; break;
  209. case ASE_InvalidMode: result = "Hardware is in a bad mode or used in a bad mode"; break;
  210. case ASE_SPNotAdvancing: result = "Hardware is not running when sample position is inquired"; break;
  211. case ASE_NoClock: result = "Sample clock or rate cannot be determined or is not present"; break;
  212. case ASE_NoMemory: result = "Not enough memory for completing the request"; break;
  213. default: result = "Unknown ASIO error"; break;
  214. }
  215. return result;
  216. }
  217. #define PA_ASIO_SET_LAST_ASIO_ERROR( asioError ) \
  218. PaUtil_SetLastHostErrorInfo( paASIO, asioError, PaAsio_GetAsioErrorText( asioError ) )
  219. // Atomic increment and decrement operations
  220. #if MAC
  221. /* need to be implemented on Mac */
  222. inline long PaAsio_AtomicIncrement(volatile long* v) {return ++(*const_cast<long*>(v));}
  223. inline long PaAsio_AtomicDecrement(volatile long* v) {return --(*const_cast<long*>(v));}
  224. #elif WINDOWS
  225. inline long PaAsio_AtomicIncrement(volatile long* v) {return InterlockedIncrement(const_cast<long*>(v));}
  226. inline long PaAsio_AtomicDecrement(volatile long* v) {return InterlockedDecrement(const_cast<long*>(v));}
  227. #endif
  228. typedef struct PaAsioDriverInfo
  229. {
  230. ASIODriverInfo asioDriverInfo;
  231. long inputChannelCount, outputChannelCount;
  232. long bufferMinSize, bufferMaxSize, bufferPreferredSize, bufferGranularity;
  233. bool postOutput;
  234. }
  235. PaAsioDriverInfo;
  236. /* PaAsioHostApiRepresentation - host api datastructure specific to this implementation */
  237. typedef struct
  238. {
  239. PaUtilHostApiRepresentation inheritedHostApiRep;
  240. PaUtilStreamInterface callbackStreamInterface;
  241. PaUtilStreamInterface blockingStreamInterface;
  242. PaUtilAllocationGroup *allocations;
  243. PaWinUtilComInitializationResult comInitializationResult;
  244. AsioDrivers *asioDrivers;
  245. void *systemSpecific;
  246. /* the ASIO C API only allows one ASIO driver to be open at a time,
  247. so we keep track of whether we have the driver open here, and
  248. use this information to return errors from OpenStream if the
  249. driver is already open.
  250. openAsioDeviceIndex will be PaNoDevice if there is no device open
  251. and a valid pa_asio (not global) device index otherwise.
  252. openAsioDriverInfo is populated with the driver info for the
  253. currently open device (if any)
  254. */
  255. PaDeviceIndex openAsioDeviceIndex;
  256. PaAsioDriverInfo openAsioDriverInfo;
  257. }
  258. PaAsioHostApiRepresentation;
  259. /*
  260. Retrieve <driverCount> driver names from ASIO, returned in a char**
  261. allocated in <group>.
  262. */
  263. static char **GetAsioDriverNames( PaAsioHostApiRepresentation *asioHostApi, PaUtilAllocationGroup *group, long driverCount )
  264. {
  265. char **result = 0;
  266. int i;
  267. result =(char**)PaUtil_GroupAllocateMemory(
  268. group, sizeof(char*) * driverCount );
  269. if( !result )
  270. goto error;
  271. result[0] = (char*)PaUtil_GroupAllocateMemory(
  272. group, 32 * driverCount );
  273. if( !result[0] )
  274. goto error;
  275. for( i=0; i<driverCount; ++i )
  276. result[i] = result[0] + (32 * i);
  277. asioHostApi->asioDrivers->getDriverNames( result, driverCount );
  278. error:
  279. return result;
  280. }
  281. static PaSampleFormat AsioSampleTypeToPaNativeSampleFormat(ASIOSampleType type)
  282. {
  283. switch (type) {
  284. case ASIOSTInt16MSB:
  285. case ASIOSTInt16LSB:
  286. return paInt16;
  287. case ASIOSTFloat32MSB:
  288. case ASIOSTFloat32LSB:
  289. case ASIOSTFloat64MSB:
  290. case ASIOSTFloat64LSB:
  291. return paFloat32;
  292. case ASIOSTInt32MSB:
  293. case ASIOSTInt32LSB:
  294. case ASIOSTInt32MSB16:
  295. case ASIOSTInt32LSB16:
  296. case ASIOSTInt32MSB18:
  297. case ASIOSTInt32MSB20:
  298. case ASIOSTInt32MSB24:
  299. case ASIOSTInt32LSB18:
  300. case ASIOSTInt32LSB20:
  301. case ASIOSTInt32LSB24:
  302. return paInt32;
  303. case ASIOSTInt24MSB:
  304. case ASIOSTInt24LSB:
  305. return paInt24;
  306. default:
  307. return paCustomFormat;
  308. }
  309. }
  310. void AsioSampleTypeLOG(ASIOSampleType type)
  311. {
  312. switch (type) {
  313. case ASIOSTInt16MSB: PA_DEBUG(("ASIOSTInt16MSB\n")); break;
  314. case ASIOSTInt16LSB: PA_DEBUG(("ASIOSTInt16LSB\n")); break;
  315. case ASIOSTFloat32MSB:PA_DEBUG(("ASIOSTFloat32MSB\n"));break;
  316. case ASIOSTFloat32LSB:PA_DEBUG(("ASIOSTFloat32LSB\n"));break;
  317. case ASIOSTFloat64MSB:PA_DEBUG(("ASIOSTFloat64MSB\n"));break;
  318. case ASIOSTFloat64LSB:PA_DEBUG(("ASIOSTFloat64LSB\n"));break;
  319. case ASIOSTInt32MSB: PA_DEBUG(("ASIOSTInt32MSB\n")); break;
  320. case ASIOSTInt32LSB: PA_DEBUG(("ASIOSTInt32LSB\n")); break;
  321. case ASIOSTInt32MSB16:PA_DEBUG(("ASIOSTInt32MSB16\n"));break;
  322. case ASIOSTInt32LSB16:PA_DEBUG(("ASIOSTInt32LSB16\n"));break;
  323. case ASIOSTInt32MSB18:PA_DEBUG(("ASIOSTInt32MSB18\n"));break;
  324. case ASIOSTInt32MSB20:PA_DEBUG(("ASIOSTInt32MSB20\n"));break;
  325. case ASIOSTInt32MSB24:PA_DEBUG(("ASIOSTInt32MSB24\n"));break;
  326. case ASIOSTInt32LSB18:PA_DEBUG(("ASIOSTInt32LSB18\n"));break;
  327. case ASIOSTInt32LSB20:PA_DEBUG(("ASIOSTInt32LSB20\n"));break;
  328. case ASIOSTInt32LSB24:PA_DEBUG(("ASIOSTInt32LSB24\n"));break;
  329. case ASIOSTInt24MSB: PA_DEBUG(("ASIOSTInt24MSB\n")); break;
  330. case ASIOSTInt24LSB: PA_DEBUG(("ASIOSTInt24LSB\n")); break;
  331. default: PA_DEBUG(("Custom Format%d\n",type));break;
  332. }
  333. }
  334. static int BytesPerAsioSample( ASIOSampleType sampleType )
  335. {
  336. switch (sampleType) {
  337. case ASIOSTInt16MSB:
  338. case ASIOSTInt16LSB:
  339. return 2;
  340. case ASIOSTFloat64MSB:
  341. case ASIOSTFloat64LSB:
  342. return 8;
  343. case ASIOSTFloat32MSB:
  344. case ASIOSTFloat32LSB:
  345. case ASIOSTInt32MSB:
  346. case ASIOSTInt32LSB:
  347. case ASIOSTInt32MSB16:
  348. case ASIOSTInt32LSB16:
  349. case ASIOSTInt32MSB18:
  350. case ASIOSTInt32MSB20:
  351. case ASIOSTInt32MSB24:
  352. case ASIOSTInt32LSB18:
  353. case ASIOSTInt32LSB20:
  354. case ASIOSTInt32LSB24:
  355. return 4;
  356. case ASIOSTInt24MSB:
  357. case ASIOSTInt24LSB:
  358. return 3;
  359. default:
  360. return 0;
  361. }
  362. }
  363. static void Swap16( void *buffer, long shift, long count )
  364. {
  365. unsigned short *p = (unsigned short*)buffer;
  366. unsigned short temp;
  367. (void) shift; /* unused parameter */
  368. while( count-- )
  369. {
  370. temp = *p;
  371. *p++ = (unsigned short)((temp<<8) | (temp>>8));
  372. }
  373. }
  374. static void Swap24( void *buffer, long shift, long count )
  375. {
  376. unsigned char *p = (unsigned char*)buffer;
  377. unsigned char temp;
  378. (void) shift; /* unused parameter */
  379. while( count-- )
  380. {
  381. temp = *p;
  382. *p = *(p+2);
  383. *(p+2) = temp;
  384. p += 3;
  385. }
  386. }
  387. #define PA_SWAP32_( x ) ((x>>24) | ((x>>8)&0xFF00) | ((x<<8)&0xFF0000) | (x<<24));
  388. static void Swap32( void *buffer, long shift, long count )
  389. {
  390. unsigned long *p = (unsigned long*)buffer;
  391. unsigned long temp;
  392. (void) shift; /* unused parameter */
  393. while( count-- )
  394. {
  395. temp = *p;
  396. *p++ = PA_SWAP32_( temp);
  397. }
  398. }
  399. static void SwapShiftLeft32( void *buffer, long shift, long count )
  400. {
  401. unsigned long *p = (unsigned long*)buffer;
  402. unsigned long temp;
  403. while( count-- )
  404. {
  405. temp = *p;
  406. temp = PA_SWAP32_( temp);
  407. *p++ = temp << shift;
  408. }
  409. }
  410. static void ShiftRightSwap32( void *buffer, long shift, long count )
  411. {
  412. unsigned long *p = (unsigned long*)buffer;
  413. unsigned long temp;
  414. while( count-- )
  415. {
  416. temp = *p >> shift;
  417. *p++ = PA_SWAP32_( temp);
  418. }
  419. }
  420. static void ShiftLeft32( void *buffer, long shift, long count )
  421. {
  422. unsigned long *p = (unsigned long*)buffer;
  423. unsigned long temp;
  424. while( count-- )
  425. {
  426. temp = *p;
  427. *p++ = temp << shift;
  428. }
  429. }
  430. static void ShiftRight32( void *buffer, long shift, long count )
  431. {
  432. unsigned long *p = (unsigned long*)buffer;
  433. unsigned long temp;
  434. while( count-- )
  435. {
  436. temp = *p;
  437. *p++ = temp >> shift;
  438. }
  439. }
  440. #define PA_SWAP_( x, y ) temp=x; x = y; y = temp;
  441. static void Swap64ConvertFloat64ToFloat32( void *buffer, long shift, long count )
  442. {
  443. double *in = (double*)buffer;
  444. float *out = (float*)buffer;
  445. unsigned char *p;
  446. unsigned char temp;
  447. (void) shift; /* unused parameter */
  448. while( count-- )
  449. {
  450. p = (unsigned char*)in;
  451. PA_SWAP_( p[0], p[7] );
  452. PA_SWAP_( p[1], p[6] );
  453. PA_SWAP_( p[2], p[5] );
  454. PA_SWAP_( p[3], p[4] );
  455. *out++ = (float) (*in++);
  456. }
  457. }
  458. static void ConvertFloat64ToFloat32( void *buffer, long shift, long count )
  459. {
  460. double *in = (double*)buffer;
  461. float *out = (float*)buffer;
  462. (void) shift; /* unused parameter */
  463. while( count-- )
  464. *out++ = (float) (*in++);
  465. }
  466. static void ConvertFloat32ToFloat64Swap64( void *buffer, long shift, long count )
  467. {
  468. float *in = ((float*)buffer) + (count-1);
  469. double *out = ((double*)buffer) + (count-1);
  470. unsigned char *p;
  471. unsigned char temp;
  472. (void) shift; /* unused parameter */
  473. while( count-- )
  474. {
  475. *out = *in--;
  476. p = (unsigned char*)out;
  477. PA_SWAP_( p[0], p[7] );
  478. PA_SWAP_( p[1], p[6] );
  479. PA_SWAP_( p[2], p[5] );
  480. PA_SWAP_( p[3], p[4] );
  481. out--;
  482. }
  483. }
  484. static void ConvertFloat32ToFloat64( void *buffer, long shift, long count )
  485. {
  486. float *in = ((float*)buffer) + (count-1);
  487. double *out = ((double*)buffer) + (count-1);
  488. (void) shift; /* unused parameter */
  489. while( count-- )
  490. *out-- = *in--;
  491. }
  492. #ifdef MAC
  493. #define PA_MSB_IS_NATIVE_
  494. #undef PA_LSB_IS_NATIVE_
  495. #endif
  496. #ifdef WINDOWS
  497. #undef PA_MSB_IS_NATIVE_
  498. #define PA_LSB_IS_NATIVE_
  499. #endif
  500. typedef void PaAsioBufferConverter( void *, long, long );
  501. static void SelectAsioToPaConverter( ASIOSampleType type, PaAsioBufferConverter **converter, long *shift )
  502. {
  503. *shift = 0;
  504. *converter = 0;
  505. switch (type) {
  506. case ASIOSTInt16MSB:
  507. /* dest: paInt16, no conversion necessary, possible byte swap*/
  508. #ifdef PA_LSB_IS_NATIVE_
  509. *converter = Swap16;
  510. #endif
  511. break;
  512. case ASIOSTInt16LSB:
  513. /* dest: paInt16, no conversion necessary, possible byte swap*/
  514. #ifdef PA_MSB_IS_NATIVE_
  515. *converter = Swap16;
  516. #endif
  517. break;
  518. case ASIOSTFloat32MSB:
  519. /* dest: paFloat32, no conversion necessary, possible byte swap*/
  520. #ifdef PA_LSB_IS_NATIVE_
  521. *converter = Swap32;
  522. #endif
  523. break;
  524. case ASIOSTFloat32LSB:
  525. /* dest: paFloat32, no conversion necessary, possible byte swap*/
  526. #ifdef PA_MSB_IS_NATIVE_
  527. *converter = Swap32;
  528. #endif
  529. break;
  530. case ASIOSTFloat64MSB:
  531. /* dest: paFloat32, in-place conversion to/from float32, possible byte swap*/
  532. #ifdef PA_LSB_IS_NATIVE_
  533. *converter = Swap64ConvertFloat64ToFloat32;
  534. #else
  535. *converter = ConvertFloat64ToFloat32;
  536. #endif
  537. break;
  538. case ASIOSTFloat64LSB:
  539. /* dest: paFloat32, in-place conversion to/from float32, possible byte swap*/
  540. #ifdef PA_MSB_IS_NATIVE_
  541. *converter = Swap64ConvertFloat64ToFloat32;
  542. #else
  543. *converter = ConvertFloat64ToFloat32;
  544. #endif
  545. break;
  546. case ASIOSTInt32MSB:
  547. /* dest: paInt32, no conversion necessary, possible byte swap */
  548. #ifdef PA_LSB_IS_NATIVE_
  549. *converter = Swap32;
  550. #endif
  551. break;
  552. case ASIOSTInt32LSB:
  553. /* dest: paInt32, no conversion necessary, possible byte swap */
  554. #ifdef PA_MSB_IS_NATIVE_
  555. *converter = Swap32;
  556. #endif
  557. break;
  558. case ASIOSTInt32MSB16:
  559. /* dest: paInt32, 16 bit shift, possible byte swap */
  560. #ifdef PA_LSB_IS_NATIVE_
  561. *converter = SwapShiftLeft32;
  562. #else
  563. *converter = ShiftLeft32;
  564. #endif
  565. *shift = 16;
  566. break;
  567. case ASIOSTInt32MSB18:
  568. /* dest: paInt32, 14 bit shift, possible byte swap */
  569. #ifdef PA_LSB_IS_NATIVE_
  570. *converter = SwapShiftLeft32;
  571. #else
  572. *converter = ShiftLeft32;
  573. #endif
  574. *shift = 14;
  575. break;
  576. case ASIOSTInt32MSB20:
  577. /* dest: paInt32, 12 bit shift, possible byte swap */
  578. #ifdef PA_LSB_IS_NATIVE_
  579. *converter = SwapShiftLeft32;
  580. #else
  581. *converter = ShiftLeft32;
  582. #endif
  583. *shift = 12;
  584. break;
  585. case ASIOSTInt32MSB24:
  586. /* dest: paInt32, 8 bit shift, possible byte swap */
  587. #ifdef PA_LSB_IS_NATIVE_
  588. *converter = SwapShiftLeft32;
  589. #else
  590. *converter = ShiftLeft32;
  591. #endif
  592. *shift = 8;
  593. break;
  594. case ASIOSTInt32LSB16:
  595. /* dest: paInt32, 16 bit shift, possible byte swap */
  596. #ifdef PA_MSB_IS_NATIVE_
  597. *converter = SwapShiftLeft32;
  598. #else
  599. *converter = ShiftLeft32;
  600. #endif
  601. *shift = 16;
  602. break;
  603. case ASIOSTInt32LSB18:
  604. /* dest: paInt32, 14 bit shift, possible byte swap */
  605. #ifdef PA_MSB_IS_NATIVE_
  606. *converter = SwapShiftLeft32;
  607. #else
  608. *converter = ShiftLeft32;
  609. #endif
  610. *shift = 14;
  611. break;
  612. case ASIOSTInt32LSB20:
  613. /* dest: paInt32, 12 bit shift, possible byte swap */
  614. #ifdef PA_MSB_IS_NATIVE_
  615. *converter = SwapShiftLeft32;
  616. #else
  617. *converter = ShiftLeft32;
  618. #endif
  619. *shift = 12;
  620. break;
  621. case ASIOSTInt32LSB24:
  622. /* dest: paInt32, 8 bit shift, possible byte swap */
  623. #ifdef PA_MSB_IS_NATIVE_
  624. *converter = SwapShiftLeft32;
  625. #else
  626. *converter = ShiftLeft32;
  627. #endif
  628. *shift = 8;
  629. break;
  630. case ASIOSTInt24MSB:
  631. /* dest: paInt24, no conversion necessary, possible byte swap */
  632. #ifdef PA_LSB_IS_NATIVE_
  633. *converter = Swap24;
  634. #endif
  635. break;
  636. case ASIOSTInt24LSB:
  637. /* dest: paInt24, no conversion necessary, possible byte swap */
  638. #ifdef PA_MSB_IS_NATIVE_
  639. *converter = Swap24;
  640. #endif
  641. break;
  642. }
  643. }
  644. static void SelectPaToAsioConverter( ASIOSampleType type, PaAsioBufferConverter **converter, long *shift )
  645. {
  646. *shift = 0;
  647. *converter = 0;
  648. switch (type) {
  649. case ASIOSTInt16MSB:
  650. /* src: paInt16, no conversion necessary, possible byte swap*/
  651. #ifdef PA_LSB_IS_NATIVE_
  652. *converter = Swap16;
  653. #endif
  654. break;
  655. case ASIOSTInt16LSB:
  656. /* src: paInt16, no conversion necessary, possible byte swap*/
  657. #ifdef PA_MSB_IS_NATIVE_
  658. *converter = Swap16;
  659. #endif
  660. break;
  661. case ASIOSTFloat32MSB:
  662. /* src: paFloat32, no conversion necessary, possible byte swap*/
  663. #ifdef PA_LSB_IS_NATIVE_
  664. *converter = Swap32;
  665. #endif
  666. break;
  667. case ASIOSTFloat32LSB:
  668. /* src: paFloat32, no conversion necessary, possible byte swap*/
  669. #ifdef PA_MSB_IS_NATIVE_
  670. *converter = Swap32;
  671. #endif
  672. break;
  673. case ASIOSTFloat64MSB:
  674. /* src: paFloat32, in-place conversion to/from float32, possible byte swap*/
  675. #ifdef PA_LSB_IS_NATIVE_
  676. *converter = ConvertFloat32ToFloat64Swap64;
  677. #else
  678. *converter = ConvertFloat32ToFloat64;
  679. #endif
  680. break;
  681. case ASIOSTFloat64LSB:
  682. /* src: paFloat32, in-place conversion to/from float32, possible byte swap*/
  683. #ifdef PA_MSB_IS_NATIVE_
  684. *converter = ConvertFloat32ToFloat64Swap64;
  685. #else
  686. *converter = ConvertFloat32ToFloat64;
  687. #endif
  688. break;
  689. case ASIOSTInt32MSB:
  690. /* src: paInt32, no conversion necessary, possible byte swap */
  691. #ifdef PA_LSB_IS_NATIVE_
  692. *converter = Swap32;
  693. #endif
  694. break;
  695. case ASIOSTInt32LSB:
  696. /* src: paInt32, no conversion necessary, possible byte swap */
  697. #ifdef PA_MSB_IS_NATIVE_
  698. *converter = Swap32;
  699. #endif
  700. break;
  701. case ASIOSTInt32MSB16:
  702. /* src: paInt32, 16 bit shift, possible byte swap */
  703. #ifdef PA_LSB_IS_NATIVE_
  704. *converter = ShiftRightSwap32;
  705. #else
  706. *converter = ShiftRight32;
  707. #endif
  708. *shift = 16;
  709. break;
  710. case ASIOSTInt32MSB18:
  711. /* src: paInt32, 14 bit shift, possible byte swap */
  712. #ifdef PA_LSB_IS_NATIVE_
  713. *converter = ShiftRightSwap32;
  714. #else
  715. *converter = ShiftRight32;
  716. #endif
  717. *shift = 14;
  718. break;
  719. case ASIOSTInt32MSB20:
  720. /* src: paInt32, 12 bit shift, possible byte swap */
  721. #ifdef PA_LSB_IS_NATIVE_
  722. *converter = ShiftRightSwap32;
  723. #else
  724. *converter = ShiftRight32;
  725. #endif
  726. *shift = 12;
  727. break;
  728. case ASIOSTInt32MSB24:
  729. /* src: paInt32, 8 bit shift, possible byte swap */
  730. #ifdef PA_LSB_IS_NATIVE_
  731. *converter = ShiftRightSwap32;
  732. #else
  733. *converter = ShiftRight32;
  734. #endif
  735. *shift = 8;
  736. break;
  737. case ASIOSTInt32LSB16:
  738. /* src: paInt32, 16 bit shift, possible byte swap */
  739. #ifdef PA_MSB_IS_NATIVE_
  740. *converter = ShiftRightSwap32;
  741. #else
  742. *converter = ShiftRight32;
  743. #endif
  744. *shift = 16;
  745. break;
  746. case ASIOSTInt32LSB18:
  747. /* src: paInt32, 14 bit shift, possible byte swap */
  748. #ifdef PA_MSB_IS_NATIVE_
  749. *converter = ShiftRightSwap32;
  750. #else
  751. *converter = ShiftRight32;
  752. #endif
  753. *shift = 14;
  754. break;
  755. case ASIOSTInt32LSB20:
  756. /* src: paInt32, 12 bit shift, possible byte swap */
  757. #ifdef PA_MSB_IS_NATIVE_
  758. *converter = ShiftRightSwap32;
  759. #else
  760. *converter = ShiftRight32;
  761. #endif
  762. *shift = 12;
  763. break;
  764. case ASIOSTInt32LSB24:
  765. /* src: paInt32, 8 bit shift, possible byte swap */
  766. #ifdef PA_MSB_IS_NATIVE_
  767. *converter = ShiftRightSwap32;
  768. #else
  769. *converter = ShiftRight32;
  770. #endif
  771. *shift = 8;
  772. break;
  773. case ASIOSTInt24MSB:
  774. /* src: paInt24, no conversion necessary, possible byte swap */
  775. #ifdef PA_LSB_IS_NATIVE_
  776. *converter = Swap24;
  777. #endif
  778. break;
  779. case ASIOSTInt24LSB:
  780. /* src: paInt24, no conversion necessary, possible byte swap */
  781. #ifdef PA_MSB_IS_NATIVE_
  782. *converter = Swap24;
  783. #endif
  784. break;
  785. }
  786. }
  787. typedef struct PaAsioDeviceInfo
  788. {
  789. PaDeviceInfo commonDeviceInfo;
  790. long minBufferSize;
  791. long maxBufferSize;
  792. long preferredBufferSize;
  793. long bufferGranularity;
  794. ASIOChannelInfo *asioChannelInfos;
  795. }
  796. PaAsioDeviceInfo;
  797. PaError PaAsio_GetAvailableBufferSizes( PaDeviceIndex device,
  798. long *minBufferSizeFrames, long *maxBufferSizeFrames, long *preferredBufferSizeFrames, long *granularity )
  799. {
  800. PaError result;
  801. PaUtilHostApiRepresentation *hostApi;
  802. PaDeviceIndex hostApiDevice;
  803. result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
  804. if( result == paNoError )
  805. {
  806. result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
  807. if( result == paNoError )
  808. {
  809. PaAsioDeviceInfo *asioDeviceInfo =
  810. (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
  811. *minBufferSizeFrames = asioDeviceInfo->minBufferSize;
  812. *maxBufferSizeFrames = asioDeviceInfo->maxBufferSize;
  813. *preferredBufferSizeFrames = asioDeviceInfo->preferredBufferSize;
  814. *granularity = asioDeviceInfo->bufferGranularity;
  815. }
  816. }
  817. return result;
  818. }
  819. /* Unload whatever we loaded in LoadAsioDriver().
  820. */
  821. static void UnloadAsioDriver( void )
  822. {
  823. ASIOExit();
  824. }
  825. /*
  826. load the asio driver named by <driverName> and return statistics about
  827. the driver in info. If no error occurred, the driver will remain open
  828. and must be closed by the called by calling UnloadAsioDriver() - if an error
  829. is returned the driver will already be unloaded.
  830. */
  831. static PaError LoadAsioDriver( PaAsioHostApiRepresentation *asioHostApi, const char *driverName,
  832. PaAsioDriverInfo *driverInfo, void *systemSpecific )
  833. {
  834. PaError result = paNoError;
  835. ASIOError asioError;
  836. int asioIsInitialized = 0;
  837. if( !asioHostApi->asioDrivers->loadDriver( const_cast<char*>(driverName) ) )
  838. {
  839. result = paUnanticipatedHostError;
  840. PA_ASIO_SET_LAST_HOST_ERROR( 0, "Failed to load ASIO driver" );
  841. goto error;
  842. }
  843. memset( &driverInfo->asioDriverInfo, 0, sizeof(ASIODriverInfo) );
  844. driverInfo->asioDriverInfo.asioVersion = 2;
  845. driverInfo->asioDriverInfo.sysRef = systemSpecific;
  846. if( (asioError = ASIOInit( &driverInfo->asioDriverInfo )) != ASE_OK )
  847. {
  848. result = paUnanticipatedHostError;
  849. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  850. goto error;
  851. }
  852. else
  853. {
  854. asioIsInitialized = 1;
  855. }
  856. if( (asioError = ASIOGetChannels(&driverInfo->inputChannelCount,
  857. &driverInfo->outputChannelCount)) != ASE_OK )
  858. {
  859. result = paUnanticipatedHostError;
  860. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  861. goto error;
  862. }
  863. if( (asioError = ASIOGetBufferSize(&driverInfo->bufferMinSize,
  864. &driverInfo->bufferMaxSize, &driverInfo->bufferPreferredSize,
  865. &driverInfo->bufferGranularity)) != ASE_OK )
  866. {
  867. result = paUnanticipatedHostError;
  868. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  869. goto error;
  870. }
  871. if( ASIOOutputReady() == ASE_OK )
  872. driverInfo->postOutput = true;
  873. else
  874. driverInfo->postOutput = false;
  875. return result;
  876. error:
  877. if( asioIsInitialized )
  878. {
  879. ASIOExit();
  880. }
  881. return result;
  882. }
  883. #define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_ 13 /* must be the same number of elements as in the array below */
  884. static ASIOSampleRate defaultSampleRateSearchOrder_[]
  885. = {44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0,
  886. 192000.0, 16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };
  887. static PaError InitPaDeviceInfoFromAsioDriver( PaAsioHostApiRepresentation *asioHostApi,
  888. const char *driverName, int driverIndex,
  889. PaDeviceInfo *deviceInfo, PaAsioDeviceInfo *asioDeviceInfo )
  890. {
  891. PaError result = paNoError;
  892. /* Due to the headless design of the ASIO API, drivers are free to write over data given to them (like M-Audio
  893. drivers f.i.). This is an attempt to overcome that. */
  894. union _tag_local {
  895. PaAsioDriverInfo info;
  896. char _padding[4096];
  897. } paAsioDriver;
  898. asioDeviceInfo->asioChannelInfos = 0; /* we check this below to handle error cleanup */
  899. result = LoadAsioDriver( asioHostApi, driverName, &paAsioDriver.info, asioHostApi->systemSpecific );
  900. if( result == paNoError )
  901. {
  902. PA_DEBUG(("PaAsio_Initialize: drv:%d name = %s\n", driverIndex,deviceInfo->name));
  903. PA_DEBUG(("PaAsio_Initialize: drv:%d inputChannels = %d\n", driverIndex, paAsioDriver.info.inputChannelCount));
  904. PA_DEBUG(("PaAsio_Initialize: drv:%d outputChannels = %d\n", driverIndex, paAsioDriver.info.outputChannelCount));
  905. PA_DEBUG(("PaAsio_Initialize: drv:%d bufferMinSize = %d\n", driverIndex, paAsioDriver.info.bufferMinSize));
  906. PA_DEBUG(("PaAsio_Initialize: drv:%d bufferMaxSize = %d\n", driverIndex, paAsioDriver.info.bufferMaxSize));
  907. PA_DEBUG(("PaAsio_Initialize: drv:%d bufferPreferredSize = %d\n", driverIndex, paAsioDriver.info.bufferPreferredSize));
  908. PA_DEBUG(("PaAsio_Initialize: drv:%d bufferGranularity = %d\n", driverIndex, paAsioDriver.info.bufferGranularity));
  909. deviceInfo->maxInputChannels = paAsioDriver.info.inputChannelCount;
  910. deviceInfo->maxOutputChannels = paAsioDriver.info.outputChannelCount;
  911. deviceInfo->defaultSampleRate = 0.;
  912. bool foundDefaultSampleRate = false;
  913. for( int j=0; j < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++j )
  914. {
  915. ASIOError asioError = ASIOCanSampleRate( defaultSampleRateSearchOrder_[j] );
  916. if( asioError != ASE_NoClock && asioError != ASE_NotPresent )
  917. {
  918. deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[j];
  919. foundDefaultSampleRate = true;
  920. break;
  921. }
  922. }
  923. PA_DEBUG(("PaAsio_Initialize: drv:%d defaultSampleRate = %f\n", driverIndex, deviceInfo->defaultSampleRate));
  924. if( foundDefaultSampleRate ){
  925. /* calculate default latency values from bufferPreferredSize
  926. for default low latency, and bufferMaxSize
  927. for default high latency.
  928. use the default sample rate to convert from samples to
  929. seconds. Without knowing what sample rate the user will
  930. use this is the best we can do.
  931. */
  932. double defaultLowLatency =
  933. paAsioDriver.info.bufferPreferredSize / deviceInfo->defaultSampleRate;
  934. deviceInfo->defaultLowInputLatency = defaultLowLatency;
  935. deviceInfo->defaultLowOutputLatency = defaultLowLatency;
  936. double defaultHighLatency =
  937. paAsioDriver.info.bufferMaxSize / deviceInfo->defaultSampleRate;
  938. if( defaultHighLatency < defaultLowLatency )
  939. defaultHighLatency = defaultLowLatency; /* just in case the driver returns something strange */
  940. deviceInfo->defaultHighInputLatency = defaultHighLatency;
  941. deviceInfo->defaultHighOutputLatency = defaultHighLatency;
  942. }else{
  943. deviceInfo->defaultLowInputLatency = 0.;
  944. deviceInfo->defaultLowOutputLatency = 0.;
  945. deviceInfo->defaultHighInputLatency = 0.;
  946. deviceInfo->defaultHighOutputLatency = 0.;
  947. }
  948. PA_DEBUG(("PaAsio_Initialize: drv:%d defaultLowInputLatency = %f\n", driverIndex, deviceInfo->defaultLowInputLatency));
  949. PA_DEBUG(("PaAsio_Initialize: drv:%d defaultLowOutputLatency = %f\n", driverIndex, deviceInfo->defaultLowOutputLatency));
  950. PA_DEBUG(("PaAsio_Initialize: drv:%d defaultHighInputLatency = %f\n", driverIndex, deviceInfo->defaultHighInputLatency));
  951. PA_DEBUG(("PaAsio_Initialize: drv:%d defaultHighOutputLatency = %f\n", driverIndex, deviceInfo->defaultHighOutputLatency));
  952. asioDeviceInfo->minBufferSize = paAsioDriver.info.bufferMinSize;
  953. asioDeviceInfo->maxBufferSize = paAsioDriver.info.bufferMaxSize;
  954. asioDeviceInfo->preferredBufferSize = paAsioDriver.info.bufferPreferredSize;
  955. asioDeviceInfo->bufferGranularity = paAsioDriver.info.bufferGranularity;
  956. asioDeviceInfo->asioChannelInfos = (ASIOChannelInfo*)PaUtil_GroupAllocateMemory(
  957. asioHostApi->allocations,
  958. sizeof(ASIOChannelInfo) * (deviceInfo->maxInputChannels
  959. + deviceInfo->maxOutputChannels) );
  960. if( !asioDeviceInfo->asioChannelInfos )
  961. {
  962. result = paInsufficientMemory;
  963. goto error_unload;
  964. }
  965. int a;
  966. for( a=0; a < deviceInfo->maxInputChannels; ++a ){
  967. asioDeviceInfo->asioChannelInfos[a].channel = a;
  968. asioDeviceInfo->asioChannelInfos[a].isInput = ASIOTrue;
  969. ASIOError asioError = ASIOGetChannelInfo( &asioDeviceInfo->asioChannelInfos[a] );
  970. if( asioError != ASE_OK )
  971. {
  972. result = paUnanticipatedHostError;
  973. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  974. goto error_unload;
  975. }
  976. }
  977. for( a=0; a < deviceInfo->maxOutputChannels; ++a ){
  978. int b = deviceInfo->maxInputChannels + a;
  979. asioDeviceInfo->asioChannelInfos[b].channel = a;
  980. asioDeviceInfo->asioChannelInfos[b].isInput = ASIOFalse;
  981. ASIOError asioError = ASIOGetChannelInfo( &asioDeviceInfo->asioChannelInfos[b] );
  982. if( asioError != ASE_OK )
  983. {
  984. result = paUnanticipatedHostError;
  985. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  986. goto error_unload;
  987. }
  988. }
  989. /* unload the driver */
  990. UnloadAsioDriver();
  991. }
  992. return result;
  993. error_unload:
  994. UnloadAsioDriver();
  995. if( asioDeviceInfo->asioChannelInfos ){
  996. PaUtil_GroupFreeMemory( asioHostApi->allocations, asioDeviceInfo->asioChannelInfos );
  997. asioDeviceInfo->asioChannelInfos = 0;
  998. }
  999. return result;
  1000. }
  1001. /* we look up IsDebuggerPresent at runtime incase it isn't present (on Win95 for example) */
  1002. typedef BOOL (WINAPI *IsDebuggerPresentPtr)(VOID);
  1003. IsDebuggerPresentPtr IsDebuggerPresent_ = 0;
  1004. //FARPROC IsDebuggerPresent_ = 0; // this is the current way to do it apparently according to davidv
  1005. PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
  1006. {
  1007. PaError result = paNoError;
  1008. int i, driverCount;
  1009. PaAsioHostApiRepresentation *asioHostApi;
  1010. PaAsioDeviceInfo *deviceInfoArray;
  1011. char **names;
  1012. asioHostApi = (PaAsioHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaAsioHostApiRepresentation) );
  1013. if( !asioHostApi )
  1014. {
  1015. result = paInsufficientMemory;
  1016. goto error;
  1017. }
  1018. memset( asioHostApi, 0, sizeof(PaAsioHostApiRepresentation) ); /* ensure all fields are zeroed. especially asioHostApi->allocations */
  1019. /*
  1020. We initialize COM ourselves here and uninitialize it in Terminate().
  1021. This should be the only COM initialization needed in this module.
  1022. The ASIO SDK may also initialize COM but since we want to reduce dependency
  1023. on the ASIO SDK we manage COM initialization ourselves.
  1024. There used to be code that initialized COM in other situations
  1025. such as when creating a Stream. This made PA work when calling Pa_CreateStream
  1026. from a non-main thread. However we currently consider initialization
  1027. of COM in non-main threads to be the caller's responsibility.
  1028. */
  1029. result = PaWinUtil_CoInitialize( paASIO, &asioHostApi->comInitializationResult );
  1030. if( result != paNoError )
  1031. {
  1032. goto error;
  1033. }
  1034. asioHostApi->asioDrivers = 0; /* avoid surprises in our error handler below */
  1035. asioHostApi->allocations = PaUtil_CreateAllocationGroup();
  1036. if( !asioHostApi->allocations )
  1037. {
  1038. result = paInsufficientMemory;
  1039. goto error;
  1040. }
  1041. /* Allocate the AsioDrivers() driver list (class from ASIO SDK) */
  1042. try
  1043. {
  1044. asioHostApi->asioDrivers = new AsioDrivers(); /* invokes CoInitialize(0) in AsioDriverList::AsioDriverList */
  1045. }
  1046. catch (std::bad_alloc)
  1047. {
  1048. asioHostApi->asioDrivers = 0;
  1049. }
  1050. /* some implementations of new (ie MSVC, see http://support.microsoft.com/?kbid=167733)
  1051. don't throw std::bad_alloc, so we also explicitly test for a null return. */
  1052. if( asioHostApi->asioDrivers == 0 )
  1053. {
  1054. result = paInsufficientMemory;
  1055. goto error;
  1056. }
  1057. asioDrivers = asioHostApi->asioDrivers; /* keep SDK global in sync until we stop depending on it */
  1058. asioHostApi->systemSpecific = 0;
  1059. asioHostApi->openAsioDeviceIndex = paNoDevice;
  1060. *hostApi = &asioHostApi->inheritedHostApiRep;
  1061. (*hostApi)->info.structVersion = 1;
  1062. (*hostApi)->info.type = paASIO;
  1063. (*hostApi)->info.name = "ASIO";
  1064. (*hostApi)->info.deviceCount = 0;
  1065. #ifdef WINDOWS
  1066. /* use desktop window as system specific ptr */
  1067. asioHostApi->systemSpecific = GetDesktopWindow();
  1068. #endif
  1069. /* driverCount is the number of installed drivers - not necessarily
  1070. the number of installed physical devices. */
  1071. #if MAC
  1072. driverCount = asioHostApi->asioDrivers->getNumFragments();
  1073. #elif WINDOWS
  1074. driverCount = asioHostApi->asioDrivers->asioGetNumDev();
  1075. #endif
  1076. if( driverCount > 0 )
  1077. {
  1078. names = GetAsioDriverNames( asioHostApi, asioHostApi->allocations, driverCount );
  1079. if( !names )
  1080. {
  1081. result = paInsufficientMemory;
  1082. goto error;
  1083. }
  1084. /* allocate enough space for all drivers, even if some aren't installed */
  1085. (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
  1086. asioHostApi->allocations, sizeof(PaDeviceInfo*) * driverCount );
  1087. if( !(*hostApi)->deviceInfos )
  1088. {
  1089. result = paInsufficientMemory;
  1090. goto error;
  1091. }
  1092. /* allocate all device info structs in a contiguous block */
  1093. deviceInfoArray = (PaAsioDeviceInfo*)PaUtil_GroupAllocateMemory(
  1094. asioHostApi->allocations, sizeof(PaAsioDeviceInfo) * driverCount );
  1095. if( !deviceInfoArray )
  1096. {
  1097. result = paInsufficientMemory;
  1098. goto error;
  1099. }
  1100. IsDebuggerPresent_ = (IsDebuggerPresentPtr)GetProcAddress( LoadLibraryA( "Kernel32.dll" ), "IsDebuggerPresent" );
  1101. for( i=0; i < driverCount; ++i )
  1102. {
  1103. PA_DEBUG(("ASIO names[%d]:%s\n",i,names[i]));
  1104. // Since portaudio opens ALL ASIO drivers, and no one else does that,
  1105. // we face fact that some drivers were not meant for it, drivers which act
  1106. // like shells on top of REAL drivers, for instance.
  1107. // so we get duplicate handles, locks and other problems.
  1108. // so lets NOT try to load any such wrappers.
  1109. // The ones i [davidv] know of so far are:
  1110. if ( strcmp (names[i],"ASIO DirectX Full Duplex Driver") == 0
  1111. || strcmp (names[i],"ASIO Multimedia Driver") == 0
  1112. || strncmp(names[i],"Premiere",8) == 0 //"Premiere Elements Windows Sound 1.0"
  1113. || strncmp(names[i],"Adobe",5) == 0 //"Adobe Default Windows Sound 1.5"
  1114. )
  1115. {
  1116. PA_DEBUG(("BLACKLISTED!!!\n"));
  1117. continue;
  1118. }
  1119. if( IsDebuggerPresent_ && IsDebuggerPresent_() )
  1120. {
  1121. /* ASIO Digidesign Driver uses PACE copy protection which quits out
  1122. if a debugger is running. So we don't load it if a debugger is running. */
  1123. if( strcmp(names[i], "ASIO Digidesign Driver") == 0 )
  1124. {
  1125. PA_DEBUG(("BLACKLISTED!!! ASIO Digidesign Driver would quit the debugger\n"));
  1126. continue;
  1127. }
  1128. }
  1129. /* Attempt to init device info from the asio driver... */
  1130. {
  1131. PaAsioDeviceInfo *asioDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
  1132. PaDeviceInfo *deviceInfo = &asioDeviceInfo->commonDeviceInfo;
  1133. deviceInfo->structVersion = 2;
  1134. deviceInfo->hostApi = hostApiIndex;
  1135. deviceInfo->name = names[i];
  1136. if( InitPaDeviceInfoFromAsioDriver( asioHostApi, names[i], i, deviceInfo, asioDeviceInfo ) == paNoError )
  1137. {
  1138. (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
  1139. ++(*hostApi)->info.deviceCount;
  1140. }
  1141. else
  1142. {
  1143. PA_DEBUG(("Skipping ASIO device:%s\n",names[i]));
  1144. continue;
  1145. }
  1146. }
  1147. }
  1148. }
  1149. if( (*hostApi)->info.deviceCount > 0 )
  1150. {
  1151. (*hostApi)->info.defaultInputDevice = 0;
  1152. (*hostApi)->info.defaultOutputDevice = 0;
  1153. }
  1154. else
  1155. {
  1156. (*hostApi)->info.defaultInputDevice = paNoDevice;
  1157. (*hostApi)->info.defaultOutputDevice = paNoDevice;
  1158. }
  1159. (*hostApi)->Terminate = Terminate;
  1160. (*hostApi)->OpenStream = OpenStream;
  1161. (*hostApi)->IsFormatSupported = IsFormatSupported;
  1162. PaUtil_InitializeStreamInterface( &asioHostApi->callbackStreamInterface, CloseStream, StartStream,
  1163. StopStream, AbortStream, IsStreamStopped, IsStreamActive,
  1164. GetStreamTime, GetStreamCpuLoad,
  1165. PaUtil_DummyRead, PaUtil_DummyWrite,
  1166. PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
  1167. PaUtil_InitializeStreamInterface( &asioHostApi->blockingStreamInterface, CloseStream, StartStream,
  1168. StopStream, AbortStream, IsStreamStopped, IsStreamActive,
  1169. GetStreamTime, PaUtil_DummyGetCpuLoad,
  1170. ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
  1171. return result;
  1172. error:
  1173. if( asioHostApi )
  1174. {
  1175. if( asioHostApi->allocations )
  1176. {
  1177. PaUtil_FreeAllAllocations( asioHostApi->allocations );
  1178. PaUtil_DestroyAllocationGroup( asioHostApi->allocations );
  1179. }
  1180. delete asioHostApi->asioDrivers;
  1181. asioDrivers = 0; /* keep SDK global in sync until we stop depending on it */
  1182. PaWinUtil_CoUninitialize( paASIO, &asioHostApi->comInitializationResult );
  1183. PaUtil_FreeMemory( asioHostApi );
  1184. }
  1185. return result;
  1186. }
  1187. static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
  1188. {
  1189. PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
  1190. /*
  1191. IMPLEMENT ME:
  1192. - clean up any resources not handled by the allocation group (need to review if there are any)
  1193. */
  1194. if( asioHostApi->allocations )
  1195. {
  1196. PaUtil_FreeAllAllocations( asioHostApi->allocations );
  1197. PaUtil_DestroyAllocationGroup( asioHostApi->allocations );
  1198. }
  1199. delete asioHostApi->asioDrivers;
  1200. asioDrivers = 0; /* keep SDK global in sync until we stop depending on it */
  1201. PaWinUtil_CoUninitialize( paASIO, &asioHostApi->comInitializationResult );
  1202. PaUtil_FreeMemory( asioHostApi );
  1203. }
  1204. static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
  1205. const PaStreamParameters *inputParameters,
  1206. const PaStreamParameters *outputParameters,
  1207. double sampleRate )
  1208. {
  1209. PaError result = paNoError;
  1210. PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
  1211. PaAsioDriverInfo *driverInfo = &asioHostApi->openAsioDriverInfo;
  1212. int inputChannelCount, outputChannelCount;
  1213. PaSampleFormat inputSampleFormat, outputSampleFormat;
  1214. PaDeviceIndex asioDeviceIndex;
  1215. ASIOError asioError;
  1216. if( inputParameters && outputParameters )
  1217. {
  1218. /* full duplex ASIO stream must use the same device for input and output */
  1219. if( inputParameters->device != outputParameters->device )
  1220. return paBadIODeviceCombination;
  1221. }
  1222. if( inputParameters )
  1223. {
  1224. inputChannelCount = inputParameters->channelCount;
  1225. inputSampleFormat = inputParameters->sampleFormat;
  1226. /* all standard sample formats are supported by the buffer adapter,
  1227. this implementation doesn't support any custom sample formats */
  1228. if( inputSampleFormat & paCustomFormat )
  1229. return paSampleFormatNotSupported;
  1230. /* unless alternate device specification is supported, reject the use of
  1231. paUseHostApiSpecificDeviceSpecification */
  1232. if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
  1233. return paInvalidDevice;
  1234. asioDeviceIndex = inputParameters->device;
  1235. /* validate inputStreamInfo */
  1236. /** @todo do more validation here */
  1237. // if( inputParameters->hostApiSpecificStreamInfo )
  1238. // return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
  1239. }
  1240. else
  1241. {
  1242. inputChannelCount = 0;
  1243. }
  1244. if( outputParameters )
  1245. {
  1246. outputChannelCount = outputParameters->channelCount;
  1247. outputSampleFormat = outputParameters->sampleFormat;
  1248. /* all standard sample formats are supported by the buffer adapter,
  1249. this implementation doesn't support any custom sample formats */
  1250. if( outputSampleFormat & paCustomFormat )
  1251. return paSampleFormatNotSupported;
  1252. /* unless alternate device specification is supported, reject the use of
  1253. paUseHostApiSpecificDeviceSpecification */
  1254. if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
  1255. return paInvalidDevice;
  1256. asioDeviceIndex = outputParameters->device;
  1257. /* validate outputStreamInfo */
  1258. /** @todo do more validation here */
  1259. // if( outputParameters->hostApiSpecificStreamInfo )
  1260. // return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
  1261. }
  1262. else
  1263. {
  1264. outputChannelCount = 0;
  1265. }
  1266. /* if an ASIO device is open we can only get format information for the currently open device */
  1267. if( asioHostApi->openAsioDeviceIndex != paNoDevice
  1268. && asioHostApi->openAsioDeviceIndex != asioDeviceIndex )
  1269. {
  1270. return paDeviceUnavailable;
  1271. }
  1272. /* NOTE: we load the driver and use its current settings
  1273. rather than the ones in our device info structure which may be stale */
  1274. /* open the device if it's not already open */
  1275. if( asioHostApi->openAsioDeviceIndex == paNoDevice )
  1276. {
  1277. result = LoadAsioDriver( asioHostApi, asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name,
  1278. driverInfo, asioHostApi->systemSpecific );
  1279. if( result != paNoError )
  1280. return result;
  1281. }
  1282. /* check that input device can support inputChannelCount */
  1283. if( inputChannelCount > 0 )
  1284. {
  1285. if( inputChannelCount > driverInfo->inputChannelCount )
  1286. {
  1287. result = paInvalidChannelCount;
  1288. goto done;
  1289. }
  1290. }
  1291. /* check that output device can support outputChannelCount */
  1292. if( outputChannelCount )
  1293. {
  1294. if( outputChannelCount > driverInfo->outputChannelCount )
  1295. {
  1296. result = paInvalidChannelCount;
  1297. goto done;
  1298. }
  1299. }
  1300. /* query for sample rate support */
  1301. asioError = ASIOCanSampleRate( sampleRate );
  1302. if( asioError == ASE_NoClock || asioError == ASE_NotPresent )
  1303. {
  1304. result = paInvalidSampleRate;
  1305. goto done;
  1306. }
  1307. done:
  1308. /* close the device if it wasn't already open */
  1309. if( asioHostApi->openAsioDeviceIndex == paNoDevice )
  1310. {
  1311. UnloadAsioDriver(); /* not sure if we should check for errors here */
  1312. }
  1313. if( result == paNoError )
  1314. return paFormatIsSupported;
  1315. else
  1316. return result;
  1317. }
  1318. /** A data structure specifically for storing blocking i/o related data. */
  1319. typedef struct PaAsioStreamBlockingState
  1320. {
  1321. int stopFlag; /**< Flag indicating that block processing is to be stopped. */
  1322. unsigned long writeBuffersRequested; /**< The number of available output buffers, requested by the #WriteStream() function. */
  1323. unsigned long readFramesRequested; /**< The number of available input frames, requested by the #ReadStream() function. */
  1324. int writeBuffersRequestedFlag; /**< Flag to indicate that #WriteStream() has requested more output buffers to be available. */
  1325. int readFramesRequestedFlag; /**< Flag to indicate that #ReadStream() requires more input frames to be available. */
  1326. HANDLE writeBuffersReadyEvent; /**< Event to signal that requested output buffers are available. */
  1327. HANDLE readFramesReadyEvent; /**< Event to signal that requested input frames are available. */
  1328. void *writeRingBufferData; /**< The actual ring buffer memory, used by the output ring buffer. */
  1329. void *readRingBufferData; /**< The actual ring buffer memory, used by the input ring buffer. */
  1330. PaUtilRingBuffer writeRingBuffer; /**< Frame-aligned blocking i/o ring buffer to store output data (interleaved user format). */
  1331. PaUtilRingBuffer readRingBuffer; /**< Frame-aligned blocking i/o ring buffer to store input data (interleaved user format). */
  1332. long writeRingBufferInitialFrames; /**< The initial number of silent frames within the output ring buffer. */
  1333. const void **writeStreamBuffer; /**< Temp buffer, used by #WriteStream() for handling non-interleaved data. */
  1334. void **readStreamBuffer; /**< Temp buffer, used by #ReadStream() for handling non-interleaved data. */
  1335. PaUtilBufferProcessor bufferProcessor; /**< Buffer processor, used to handle the blocking i/o ring buffers. */
  1336. int outputUnderflowFlag; /**< Flag to signal an output underflow from within the callback function. */
  1337. int inputOverflowFlag; /**< Flag to signal an input overflow from within the callback function. */
  1338. }
  1339. PaAsioStreamBlockingState;
  1340. /* PaAsioStream - a stream data structure specifically for this implementation */
  1341. typedef struct PaAsioStream
  1342. {
  1343. PaUtilStreamRepresentation streamRepresentation;
  1344. PaUtilCpuLoadMeasurer cpuLoadMeasurer;
  1345. PaUtilBufferProcessor bufferProcessor;
  1346. PaAsioHostApiRepresentation *asioHostApi;
  1347. unsigned long framesPerHostCallback;
  1348. /* ASIO driver info - these may not be needed for the life of the stream,
  1349. but store them here until we work out how format conversion is going
  1350. to work. */
  1351. ASIOBufferInfo *asioBufferInfos;
  1352. ASIOChannelInfo *asioChannelInfos;
  1353. long asioInputLatencyFrames, asioOutputLatencyFrames; // actual latencies returned by asio
  1354. long inputChannelCount, outputChannelCount;
  1355. bool postOutput;
  1356. void **bufferPtrs; /* this is carved up for inputBufferPtrs and outputBufferPtrs */
  1357. void **inputBufferPtrs[2];
  1358. void **outputBufferPtrs[2];
  1359. PaAsioBufferConverter *inputBufferConverter;
  1360. long inputShift;
  1361. PaAsioBufferConverter *outputBufferConverter;
  1362. long outputShift;
  1363. volatile bool stopProcessing;
  1364. int stopPlayoutCount;
  1365. HANDLE completedBuffersPlayedEvent;
  1366. bool streamFinishedCallbackCalled;
  1367. int isStopped;
  1368. volatile int isActive;
  1369. volatile bool zeroOutput; /* all future calls to the callback will output silence */
  1370. volatile long reenterCount;
  1371. volatile long reenterError;
  1372. PaStreamCallbackFlags callbackFlags;
  1373. PaAsioStreamBlockingState *blockingState; /**< Blocking i/o data struct, or NULL when using callback interface. */
  1374. }
  1375. PaAsioStream;
  1376. static PaAsioStream *theAsioStream = 0; /* due to ASIO sdk limitations there can be only one stream */
  1377. static void ZeroOutputBuffers( PaAsioStream *stream, long index )
  1378. {
  1379. int i;
  1380. for( i=0; i < stream->outputChannelCount; ++i )
  1381. {
  1382. void *buffer = stream->asioBufferInfos[ i + stream->inputChannelCount ].buffers[index];
  1383. int bytesPerSample = BytesPerAsioSample( stream->asioChannelInfos[ i + stream->inputChannelCount ].type );
  1384. memset( buffer, 0, stream->framesPerHostCallback * bytesPerSample );
  1385. }
  1386. }
  1387. /* return the next power of two >= x.
  1388. Returns the input parameter if it is already a power of two.
  1389. http://stackoverflow.com/questions/364985/algorithm-for-finding-the-smallest-power-of-two-thats-greater-or-equal-to-a-giv
  1390. */
  1391. static unsigned long NextPowerOfTwo( unsigned long x )
  1392. {
  1393. --x;
  1394. x |= x >> 1;
  1395. x |= x >> 2;
  1396. x |= x >> 4;
  1397. x |= x >> 8;
  1398. x |= x >> 16;
  1399. /* If you needed to deal with numbers > 2^32 the following would be needed.
  1400. For latencies, we don't deal with values this large.
  1401. x |= x >> 16;
  1402. */
  1403. return x + 1;
  1404. }
  1405. static unsigned long SelectHostBufferSizeForUnspecifiedUserFramesPerBuffer(
  1406. unsigned long targetBufferingLatencyFrames, PaAsioDriverInfo *driverInfo )
  1407. {
  1408. /* Choose a host buffer size based only on targetBufferingLatencyFrames and the
  1409. device's supported buffer sizes. Always returns a valid value.
  1410. */
  1411. unsigned long result;
  1412. if( targetBufferingLatencyFrames <= (unsigned long)driverInfo->bufferMinSize )
  1413. {
  1414. result = driverInfo->bufferMinSize;
  1415. }
  1416. else if( targetBufferingLatencyFrames >= (unsigned long)driverInfo->bufferMaxSize )
  1417. {
  1418. result = driverInfo->bufferMaxSize;
  1419. }
  1420. else
  1421. {
  1422. if( driverInfo->bufferGranularity == 0 ) /* single fixed host buffer size */
  1423. {
  1424. /* The documentation states that bufferGranularity should be zero
  1425. when bufferMinSize, bufferMaxSize and bufferPreferredSize are the
  1426. same. We assume that is the case.
  1427. */
  1428. result = driverInfo->bufferPreferredSize;
  1429. }
  1430. else if( driverInfo->bufferGranularity == -1 ) /* power-of-two */
  1431. {
  1432. /* We assume bufferMinSize and bufferMaxSize are powers of two. */
  1433. result = NextPowerOfTwo( targetBufferingLatencyFrames );
  1434. if( result < (unsigned long)driverInfo->bufferMinSize )
  1435. result = driverInfo->bufferMinSize;
  1436. if( result > (unsigned long)driverInfo->bufferMaxSize )
  1437. result = driverInfo->bufferMaxSize;
  1438. }
  1439. else /* modulo bufferGranularity */
  1440. {
  1441. /* round up to the next multiple of granularity */
  1442. unsigned long n = (targetBufferingLatencyFrames + driverInfo->bufferGranularity - 1)
  1443. / driverInfo->bufferGranularity;
  1444. result = n * driverInfo->bufferGranularity;
  1445. if( result < (unsigned long)driverInfo->bufferMinSize )
  1446. result = driverInfo->bufferMinSize;
  1447. if( result > (unsigned long)driverInfo->bufferMaxSize )
  1448. result = driverInfo->bufferMaxSize;
  1449. }
  1450. }
  1451. return result;
  1452. }
  1453. static unsigned long SelectHostBufferSizeForSpecifiedUserFramesPerBuffer(
  1454. unsigned long targetBufferingLatencyFrames, unsigned long userFramesPerBuffer,
  1455. PaAsioDriverInfo *driverInfo )
  1456. {
  1457. /* Select a host buffer size conforming to targetBufferingLatencyFrames
  1458. and the device's supported buffer sizes.
  1459. The return value will always be a multiple of userFramesPerBuffer.
  1460. If a valid buffer size can not be found the function returns 0.
  1461. The current implementation uses a simple iterative search for clarity.
  1462. Feel free to suggest a closed form solution.
  1463. */
  1464. unsigned long result = 0;
  1465. assert( userFramesPerBuffer != 0 );
  1466. if( driverInfo->bufferGranularity == 0 ) /* single fixed host buffer size */
  1467. {
  1468. /* The documentation states that bufferGranularity should be zero
  1469. when bufferMinSize, bufferMaxSize and bufferPreferredSize are the
  1470. same. We assume that is the case.
  1471. */
  1472. if( (driverInfo->bufferPreferredSize % userFramesPerBuffer) == 0 )
  1473. result = driverInfo->bufferPreferredSize;
  1474. }
  1475. else if( driverInfo->bufferGranularity == -1 ) /* power-of-two */
  1476. {
  1477. /* We assume bufferMinSize and bufferMaxSize are powers of two. */
  1478. /* Search all powers of two in the range [bufferMinSize,bufferMaxSize]
  1479. for multiples of userFramesPerBuffer. We prefer the first multiple
  1480. that is equal or greater than targetBufferingLatencyFrames, or
  1481. failing that, the largest multiple less than
  1482. targetBufferingLatencyFrames.
  1483. */
  1484. unsigned long x = (unsigned long)driverInfo->bufferMinSize;
  1485. do {
  1486. if( (x % userFramesPerBuffer) == 0 )
  1487. {
  1488. /* any multiple of userFramesPerBuffer is acceptable */
  1489. result = x;
  1490. if( result >= targetBufferingLatencyFrames )
  1491. break; /* stop. a value >= to targetBufferingLatencyFrames is ideal. */
  1492. }
  1493. x *= 2;
  1494. } while( x <= (unsigned long)driverInfo->bufferMaxSize );
  1495. }
  1496. else /* modulo granularity */
  1497. {
  1498. /* We assume bufferMinSize is a multiple of bufferGranularity. */
  1499. /* Search all multiples of bufferGranularity in the range
  1500. [bufferMinSize,bufferMaxSize] for multiples of userFramesPerBuffer.
  1501. We prefer the first multiple that is equal or greater than
  1502. targetBufferingLatencyFrames, or failing that, the largest multiple
  1503. less than targetBufferingLatencyFrames.
  1504. */
  1505. unsigned long x = (unsigned long)driverInfo->bufferMinSize;
  1506. do {
  1507. if( (x % userFramesPerBuffer) == 0 )
  1508. {
  1509. /* any multiple of userFramesPerBuffer is acceptable */
  1510. result = x;
  1511. if( result >= targetBufferingLatencyFrames )
  1512. break; /* stop. a value >= to targetBufferingLatencyFrames is ideal. */
  1513. }
  1514. x += driverInfo->bufferGranularity;
  1515. } while( x <= (unsigned long)driverInfo->bufferMaxSize );
  1516. }
  1517. return result;
  1518. }
  1519. static unsigned long SelectHostBufferSize(
  1520. unsigned long targetBufferingLatencyFrames,
  1521. unsigned long userFramesPerBuffer, PaAsioDriverInfo *driverInfo )
  1522. {
  1523. unsigned long result = 0;
  1524. /* We select a host buffer size based on the following requirements
  1525. (in priority order):
  1526. 1. The host buffer size must be permissible according to the ASIO
  1527. driverInfo buffer size constraints (min, max, granularity or
  1528. powers-of-two).
  1529. 2. If the user specifies a non-zero framesPerBuffer parameter
  1530. (userFramesPerBuffer here) the host buffer should be a multiple of
  1531. this (subject to the constraints in (1) above).
  1532. [NOTE: Where no permissible host buffer size is a multiple of
  1533. userFramesPerBuffer, we choose a value as if userFramesPerBuffer were
  1534. zero (i.e. we ignore it). This strategy is open for review ~ perhaps
  1535. there are still "more optimal" buffer sizes related to
  1536. userFramesPerBuffer that we could use.]
  1537. 3. The host buffer size should be greater than or equal to
  1538. targetBufferingLatencyFrames, subject to (1) and (2) above. Where it
  1539. is not possible to select a host buffer size equal or greater than
  1540. targetBufferingLatencyFrames, the highest buffer size conforming to
  1541. (1) and (2) should be chosen.
  1542. */
  1543. if( userFramesPerBuffer != 0 )
  1544. {
  1545. /* userFramesPerBuffer is specified, try to find a buffer size that's
  1546. a multiple of it */
  1547. result = SelectHostBufferSizeForSpecifiedUserFramesPerBuffer(
  1548. targetBufferingLatencyFrames, userFramesPerBuffer, driverInfo );
  1549. }
  1550. if( result == 0 )
  1551. {
  1552. /* either userFramesPerBuffer was not specified, or we couldn't find a
  1553. host buffer size that is a multiple of it. Select a host buffer size
  1554. according to targetBufferingLatencyFrames and the ASIO driverInfo
  1555. buffer size constraints.
  1556. */
  1557. result = SelectHostBufferSizeForUnspecifiedUserFramesPerBuffer(
  1558. targetBufferingLatencyFrames, driverInfo );
  1559. }
  1560. return result;
  1561. }
  1562. /* returns channelSelectors if present */
  1563. static PaError ValidateAsioSpecificStreamInfo(
  1564. const PaStreamParameters *streamParameters,
  1565. const PaAsioStreamInfo *streamInfo,
  1566. int deviceChannelCount,
  1567. int **channelSelectors )
  1568. {
  1569. if( streamInfo )
  1570. {
  1571. if( streamInfo->size != sizeof( PaAsioStreamInfo )
  1572. || streamInfo->version != 1 )
  1573. {
  1574. return paIncompatibleHostApiSpecificStreamInfo;
  1575. }
  1576. if( streamInfo->flags & paAsioUseChannelSelectors )
  1577. *channelSelectors = streamInfo->channelSelectors;
  1578. if( !(*channelSelectors) )
  1579. return paIncompatibleHostApiSpecificStreamInfo;
  1580. for( int i=0; i < streamParameters->channelCount; ++i ){
  1581. if( (*channelSelectors)[i] < 0
  1582. || (*channelSelectors)[i] >= deviceChannelCount ){
  1583. return paInvalidChannelCount;
  1584. }
  1585. }
  1586. }
  1587. return paNoError;
  1588. }
  1589. static bool IsUsingExternalClockSource()
  1590. {
  1591. bool result = false;
  1592. ASIOError asioError;
  1593. ASIOClockSource clocks[32];
  1594. long numSources=32;
  1595. /* davidv: listing ASIO Clock sources. there is an ongoing investigation by
  1596. me about whether or not to call ASIOSetSampleRate if an external Clock is
  1597. used. A few drivers expected different things here */
  1598. asioError = ASIOGetClockSources(clocks, &numSources);
  1599. if( asioError != ASE_OK ){
  1600. PA_DEBUG(("ERROR: ASIOGetClockSources: %s\n", PaAsio_GetAsioErrorText(asioError) ));
  1601. }else{
  1602. PA_DEBUG(("INFO ASIOGetClockSources listing %d clocks\n", numSources ));
  1603. for (int i=0;i<numSources;++i){
  1604. PA_DEBUG(("ASIOClockSource%d %s current:%d\n", i, clocks[i].name, clocks[i].isCurrentSource ));
  1605. if (clocks[i].isCurrentSource)
  1606. result = true;
  1607. }
  1608. }
  1609. return result;
  1610. }
  1611. static PaError ValidateAndSetSampleRate( double sampleRate )
  1612. {
  1613. PaError result = paNoError;
  1614. ASIOError asioError;
  1615. // check that the device supports the requested sample rate
  1616. asioError = ASIOCanSampleRate( sampleRate );
  1617. PA_DEBUG(("ASIOCanSampleRate(%f):%d\n", sampleRate, asioError ));
  1618. if( asioError != ASE_OK )
  1619. {
  1620. result = paInvalidSampleRate;
  1621. PA_DEBUG(("ERROR: ASIOCanSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
  1622. goto error;
  1623. }
  1624. // retrieve the current sample rate, we only change to the requested
  1625. // sample rate if the device is not already in that rate.
  1626. ASIOSampleRate oldRate;
  1627. asioError = ASIOGetSampleRate(&oldRate);
  1628. if( asioError != ASE_OK )
  1629. {
  1630. result = paInvalidSampleRate;
  1631. PA_DEBUG(("ERROR: ASIOGetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
  1632. goto error;
  1633. }
  1634. PA_DEBUG(("ASIOGetSampleRate:%f\n",oldRate));
  1635. if (oldRate != sampleRate){
  1636. /* Set sample rate */
  1637. PA_DEBUG(("before ASIOSetSampleRate(%f)\n",sampleRate));
  1638. /*
  1639. If you have problems with some drivers when externally clocked,
  1640. try switching on the following line and commenting out the one after it.
  1641. See IsUsingExternalClockSource() for more info.
  1642. */
  1643. //if( IsUsingExternalClockSource() ){
  1644. if( false ){
  1645. asioError = ASIOSetSampleRate( 0 );
  1646. }else{
  1647. asioError = ASIOSetSampleRate( sampleRate );
  1648. }
  1649. if( asioError != ASE_OK )
  1650. {
  1651. result = paInvalidSampleRate;
  1652. PA_DEBUG(("ERROR: ASIOSetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
  1653. goto error;
  1654. }
  1655. PA_DEBUG(("after ASIOSetSampleRate(%f)\n",sampleRate));
  1656. }
  1657. else
  1658. {
  1659. PA_DEBUG(("No Need to change SR\n"));
  1660. }
  1661. error:
  1662. return result;
  1663. }
  1664. /* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
  1665. static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
  1666. PaStream** s,
  1667. const PaStreamParameters *inputParameters,
  1668. const PaStreamParameters *outputParameters,
  1669. double sampleRate,
  1670. unsigned long framesPerBuffer,
  1671. PaStreamFlags streamFlags,
  1672. PaStreamCallback *streamCallback,
  1673. void *userData )
  1674. {
  1675. PaError result = paNoError;
  1676. PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
  1677. PaAsioStream *stream = 0;
  1678. PaAsioStreamInfo *inputStreamInfo, *outputStreamInfo;
  1679. unsigned long framesPerHostBuffer;
  1680. int inputChannelCount, outputChannelCount;
  1681. PaSampleFormat inputSampleFormat, outputSampleFormat;
  1682. PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
  1683. unsigned long suggestedInputLatencyFrames;
  1684. unsigned long suggestedOutputLatencyFrames;
  1685. PaDeviceIndex asioDeviceIndex;
  1686. ASIOError asioError;
  1687. int asioIsInitialized = 0;
  1688. int asioBuffersCreated = 0;
  1689. int completedBuffersPlayedEventInited = 0;
  1690. int i;
  1691. PaAsioDriverInfo *driverInfo;
  1692. int *inputChannelSelectors = 0;
  1693. int *outputChannelSelectors = 0;
  1694. /* Are we using blocking i/o interface? */
  1695. int usingBlockingIo = ( !streamCallback ) ? TRUE : FALSE;
  1696. /* Blocking i/o stuff */
  1697. long lBlockingBufferSize = 0; /* Desired ring buffer size in samples. */
  1698. long lBlockingBufferSizePow2 = 0; /* Power-of-2 rounded ring buffer size. */
  1699. long lBytesPerFrame = 0; /* Number of bytes per input/output frame. */
  1700. int blockingWriteBuffersReadyEventInitialized = 0; /* Event init flag. */
  1701. int blockingReadFramesReadyEventInitialized = 0; /* Event init flag. */
  1702. int callbackBufferProcessorInited = FALSE;
  1703. int blockingBufferProcessorInited = FALSE;
  1704. /* unless we move to using lower level ASIO calls, we can only have
  1705. one device open at a time */
  1706. if( asioHostApi->openAsioDeviceIndex != paNoDevice )
  1707. {
  1708. PA_DEBUG(("OpenStream paDeviceUnavailable\n"));
  1709. return paDeviceUnavailable;
  1710. }
  1711. assert( theAsioStream == 0 );
  1712. if( inputParameters && outputParameters )
  1713. {
  1714. /* full duplex ASIO stream must use the same device for input and output */
  1715. if( inputParameters->device != outputParameters->device )
  1716. {
  1717. PA_DEBUG(("OpenStream paBadIODeviceCombination\n"));
  1718. return paBadIODeviceCombination;
  1719. }
  1720. }
  1721. if( inputParameters )
  1722. {
  1723. inputChannelCount = inputParameters->channelCount;
  1724. inputSampleFormat = inputParameters->sampleFormat;
  1725. suggestedInputLatencyFrames = (unsigned long)((inputParameters->suggestedLatency * sampleRate)+0.5f);
  1726. /* unless alternate device specification is supported, reject the use of
  1727. paUseHostApiSpecificDeviceSpecification */
  1728. if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
  1729. return paInvalidDevice;
  1730. asioDeviceIndex = inputParameters->device;
  1731. PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[asioDeviceIndex];
  1732. /* validate hostApiSpecificStreamInfo */
  1733. inputStreamInfo = (PaAsioStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
  1734. result = ValidateAsioSpecificStreamInfo( inputParameters, inputStreamInfo,
  1735. asioDeviceInfo->commonDeviceInfo.maxInputChannels,
  1736. &inputChannelSelectors
  1737. );
  1738. if( result != paNoError ) return result;
  1739. }
  1740. else
  1741. {
  1742. inputChannelCount = 0;
  1743. inputSampleFormat = 0;
  1744. suggestedInputLatencyFrames = 0;
  1745. }
  1746. if( outputParameters )
  1747. {
  1748. outputChannelCount = outputParameters->channelCount;
  1749. outputSampleFormat = outputParameters->sampleFormat;
  1750. suggestedOutputLatencyFrames = (unsigned long)((outputParameters->suggestedLatency * sampleRate)+0.5f);
  1751. /* unless alternate device specification is supported, reject the use of
  1752. paUseHostApiSpecificDeviceSpecification */
  1753. if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
  1754. return paInvalidDevice;
  1755. asioDeviceIndex = outputParameters->device;
  1756. PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[asioDeviceIndex];
  1757. /* validate hostApiSpecificStreamInfo */
  1758. outputStreamInfo = (PaAsioStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
  1759. result = ValidateAsioSpecificStreamInfo( outputParameters, outputStreamInfo,
  1760. asioDeviceInfo->commonDeviceInfo.maxOutputChannels,
  1761. &outputChannelSelectors
  1762. );
  1763. if( result != paNoError ) return result;
  1764. }
  1765. else
  1766. {
  1767. outputChannelCount = 0;
  1768. outputSampleFormat = 0;
  1769. suggestedOutputLatencyFrames = 0;
  1770. }
  1771. driverInfo = &asioHostApi->openAsioDriverInfo;
  1772. /* NOTE: we load the driver and use its current settings
  1773. rather than the ones in our device info structure which may be stale */
  1774. result = LoadAsioDriver( asioHostApi, asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name,
  1775. driverInfo, asioHostApi->systemSpecific );
  1776. if( result == paNoError )
  1777. asioIsInitialized = 1;
  1778. else{
  1779. PA_DEBUG(("OpenStream ERROR1 - LoadAsioDriver returned %d\n", result));
  1780. goto error;
  1781. }
  1782. /* check that input device can support inputChannelCount */
  1783. if( inputChannelCount > 0 )
  1784. {
  1785. if( inputChannelCount > driverInfo->inputChannelCount )
  1786. {
  1787. result = paInvalidChannelCount;
  1788. PA_DEBUG(("OpenStream ERROR2\n"));
  1789. goto error;
  1790. }
  1791. }
  1792. /* check that output device can support outputChannelCount */
  1793. if( outputChannelCount )
  1794. {
  1795. if( outputChannelCount > driverInfo->outputChannelCount )
  1796. {
  1797. result = paInvalidChannelCount;
  1798. PA_DEBUG(("OpenStream ERROR3\n"));
  1799. goto error;
  1800. }
  1801. }
  1802. result = ValidateAndSetSampleRate( sampleRate );
  1803. if( result != paNoError )
  1804. goto error;
  1805. /*
  1806. IMPLEMENT ME:
  1807. - if a full duplex stream is requested, check that the combination
  1808. of input and output parameters is supported
  1809. */
  1810. /* validate platform specific flags */
  1811. if( (streamFlags & paPlatformSpecificFlags) != 0 ){
  1812. PA_DEBUG(("OpenStream invalid flags!!\n"));
  1813. return paInvalidFlag; /* unexpected platform specific flag */
  1814. }
  1815. stream = (PaAsioStream*)PaUtil_AllocateMemory( sizeof(PaAsioStream) );
  1816. if( !stream )
  1817. {
  1818. result = paInsufficientMemory;
  1819. PA_DEBUG(("OpenStream ERROR5\n"));
  1820. goto error;
  1821. }
  1822. stream->blockingState = NULL; /* Blocking i/o not initialized, yet. */
  1823. stream->completedBuffersPlayedEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
  1824. if( stream->completedBuffersPlayedEvent == NULL )
  1825. {
  1826. result = paUnanticipatedHostError;
  1827. PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
  1828. PA_DEBUG(("OpenStream ERROR6\n"));
  1829. goto error;
  1830. }
  1831. completedBuffersPlayedEventInited = 1;
  1832. stream->asioBufferInfos = 0; /* for deallocation in error */
  1833. stream->asioChannelInfos = 0; /* for deallocation in error */
  1834. stream->bufferPtrs = 0; /* for deallocation in error */
  1835. /* Using blocking i/o interface... */
  1836. if( usingBlockingIo )
  1837. {
  1838. /* Blocking i/o is implemented by running callback mode, using a special blocking i/o callback. */
  1839. streamCallback = BlockingIoPaCallback; /* Setup PA to use the ASIO blocking i/o callback. */
  1840. userData = &theAsioStream; /* The callback user data will be the PA ASIO stream. */
  1841. PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
  1842. &asioHostApi->blockingStreamInterface, streamCallback, userData );
  1843. }
  1844. else /* Using callback interface... */
  1845. {
  1846. PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
  1847. &asioHostApi->callbackStreamInterface, streamCallback, userData );
  1848. }
  1849. PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
  1850. stream->asioBufferInfos = (ASIOBufferInfo*)PaUtil_AllocateMemory(
  1851. sizeof(ASIOBufferInfo) * (inputChannelCount + outputChannelCount) );
  1852. if( !stream->asioBufferInfos )
  1853. {
  1854. result = paInsufficientMemory;
  1855. PA_DEBUG(("OpenStream ERROR7\n"));
  1856. goto error;
  1857. }
  1858. for( i=0; i < inputChannelCount; ++i )
  1859. {
  1860. ASIOBufferInfo *info = &stream->asioBufferInfos[i];
  1861. info->isInput = ASIOTrue;
  1862. if( inputChannelSelectors ){
  1863. // inputChannelSelectors values have already been validated in
  1864. // ValidateAsioSpecificStreamInfo() above
  1865. info->channelNum = inputChannelSelectors[i];
  1866. }else{
  1867. info->channelNum = i;
  1868. }
  1869. info->buffers[0] = info->buffers[1] = 0;
  1870. }
  1871. for( i=0; i < outputChannelCount; ++i ){
  1872. ASIOBufferInfo *info = &stream->asioBufferInfos[inputChannelCount+i];
  1873. info->isInput = ASIOFalse;
  1874. if( outputChannelSelectors ){
  1875. // outputChannelSelectors values have already been validated in
  1876. // ValidateAsioSpecificStreamInfo() above
  1877. info->channelNum = outputChannelSelectors[i];
  1878. }else{
  1879. info->channelNum = i;
  1880. }
  1881. info->buffers[0] = info->buffers[1] = 0;
  1882. }
  1883. /* Using blocking i/o interface... */
  1884. if( usingBlockingIo )
  1885. {
  1886. /** @todo REVIEW selection of host buffer size for blocking i/o */
  1887. framesPerHostBuffer = SelectHostBufferSize( 0, framesPerBuffer, driverInfo );
  1888. }
  1889. else /* Using callback interface... */
  1890. {
  1891. /* Select the host buffer size based on user framesPerBuffer and the
  1892. maximum of suggestedInputLatencyFrames and
  1893. suggestedOutputLatencyFrames.
  1894. We should subtract any fixed known driver latency from
  1895. suggestedLatencyFrames before computing the host buffer size.
  1896. However, the ASIO API doesn't provide a method for determining fixed
  1897. latencies independent of the host buffer size. ASIOGetLatencies()
  1898. only returns latencies after the buffer size has been configured, so
  1899. we can't reliably use it to determine fixed latencies here.
  1900. We could set the preferred buffer size and then subtract it from
  1901. the values returned from ASIOGetLatencies, but this would not be 100%
  1902. reliable, so we don't do it.
  1903. */
  1904. unsigned long targetBufferingLatencyFrames =
  1905. (( suggestedInputLatencyFrames > suggestedOutputLatencyFrames )
  1906. ? suggestedInputLatencyFrames
  1907. : suggestedOutputLatencyFrames);
  1908. framesPerHostBuffer = SelectHostBufferSize( targetBufferingLatencyFrames,
  1909. framesPerBuffer, driverInfo );
  1910. }
  1911. PA_DEBUG(("PaAsioOpenStream: framesPerHostBuffer :%d\n", framesPerHostBuffer));
  1912. asioError = ASIOCreateBuffers( stream->asioBufferInfos,
  1913. inputChannelCount+outputChannelCount,
  1914. framesPerHostBuffer, &asioCallbacks_ );
  1915. if( asioError != ASE_OK
  1916. && framesPerHostBuffer != (unsigned long)driverInfo->bufferPreferredSize )
  1917. {
  1918. PA_DEBUG(("ERROR: ASIOCreateBuffers: %s\n", PaAsio_GetAsioErrorText(asioError) ));
  1919. /*
  1920. Some buggy drivers (like the Hoontech DSP24) give incorrect
  1921. [min, preferred, max] values They should work with the preferred size
  1922. value, thus if Pa_ASIO_CreateBuffers fails with the hostBufferSize
  1923. computed in SelectHostBufferSize, we try again with the preferred size.
  1924. */
  1925. framesPerHostBuffer = driverInfo->bufferPreferredSize;
  1926. PA_DEBUG(("PaAsioOpenStream: CORRECTED framesPerHostBuffer :%d\n", framesPerHostBuffer));
  1927. ASIOError asioError2 = ASIOCreateBuffers( stream->asioBufferInfos,
  1928. inputChannelCount+outputChannelCount,
  1929. framesPerHostBuffer, &asioCallbacks_ );
  1930. if( asioError2 == ASE_OK )
  1931. asioError = ASE_OK;
  1932. }
  1933. if( asioError != ASE_OK )
  1934. {
  1935. result = paUnanticipatedHostError;
  1936. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  1937. PA_DEBUG(("OpenStream ERROR9\n"));
  1938. goto error;
  1939. }
  1940. asioBuffersCreated = 1;
  1941. stream->asioChannelInfos = (ASIOChannelInfo*)PaUtil_AllocateMemory(
  1942. sizeof(ASIOChannelInfo) * (inputChannelCount + outputChannelCount) );
  1943. if( !stream->asioChannelInfos )
  1944. {
  1945. result = paInsufficientMemory;
  1946. PA_DEBUG(("OpenStream ERROR10\n"));
  1947. goto error;
  1948. }
  1949. for( i=0; i < inputChannelCount + outputChannelCount; ++i )
  1950. {
  1951. stream->asioChannelInfos[i].channel = stream->asioBufferInfos[i].channelNum;
  1952. stream->asioChannelInfos[i].isInput = stream->asioBufferInfos[i].isInput;
  1953. asioError = ASIOGetChannelInfo( &stream->asioChannelInfos[i] );
  1954. if( asioError != ASE_OK )
  1955. {
  1956. result = paUnanticipatedHostError;
  1957. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  1958. PA_DEBUG(("OpenStream ERROR11\n"));
  1959. goto error;
  1960. }
  1961. }
  1962. stream->bufferPtrs = (void**)PaUtil_AllocateMemory(
  1963. 2 * sizeof(void*) * (inputChannelCount + outputChannelCount) );
  1964. if( !stream->bufferPtrs )
  1965. {
  1966. result = paInsufficientMemory;
  1967. PA_DEBUG(("OpenStream ERROR12\n"));
  1968. goto error;
  1969. }
  1970. if( inputChannelCount > 0 )
  1971. {
  1972. stream->inputBufferPtrs[0] = stream-> bufferPtrs;
  1973. stream->inputBufferPtrs[1] = &stream->bufferPtrs[inputChannelCount];
  1974. for( i=0; i<inputChannelCount; ++i )
  1975. {
  1976. stream->inputBufferPtrs[0][i] = stream->asioBufferInfos[i].buffers[0];
  1977. stream->inputBufferPtrs[1][i] = stream->asioBufferInfos[i].buffers[1];
  1978. }
  1979. }
  1980. else
  1981. {
  1982. stream->inputBufferPtrs[0] = 0;
  1983. stream->inputBufferPtrs[1] = 0;
  1984. }
  1985. if( outputChannelCount > 0 )
  1986. {
  1987. stream->outputBufferPtrs[0] = &stream->bufferPtrs[inputChannelCount*2];
  1988. stream->outputBufferPtrs[1] = &stream->bufferPtrs[inputChannelCount*2 + outputChannelCount];
  1989. for( i=0; i<outputChannelCount; ++i )
  1990. {
  1991. stream->outputBufferPtrs[0][i] = stream->asioBufferInfos[inputChannelCount+i].buffers[0];
  1992. stream->outputBufferPtrs[1][i] = stream->asioBufferInfos[inputChannelCount+i].buffers[1];
  1993. }
  1994. }
  1995. else
  1996. {
  1997. stream->outputBufferPtrs[0] = 0;
  1998. stream->outputBufferPtrs[1] = 0;
  1999. }
  2000. if( inputChannelCount > 0 )
  2001. {
  2002. /* FIXME: assume all channels use the same type for now
  2003. see: "ASIO devices with multiple sample formats are unsupported"
  2004. http://www.portaudio.com/trac/ticket/106
  2005. */
  2006. ASIOSampleType inputType = stream->asioChannelInfos[0].type;
  2007. PA_DEBUG(("ASIO Input type:%d",inputType));
  2008. AsioSampleTypeLOG(inputType);
  2009. hostInputSampleFormat = AsioSampleTypeToPaNativeSampleFormat( inputType );
  2010. SelectAsioToPaConverter( inputType, &stream->inputBufferConverter, &stream->inputShift );
  2011. }
  2012. else
  2013. {
  2014. hostInputSampleFormat = 0;
  2015. stream->inputBufferConverter = 0;
  2016. }
  2017. if( outputChannelCount > 0 )
  2018. {
  2019. /* FIXME: assume all channels use the same type for now
  2020. see: "ASIO devices with multiple sample formats are unsupported"
  2021. http://www.portaudio.com/trac/ticket/106
  2022. */
  2023. ASIOSampleType outputType = stream->asioChannelInfos[inputChannelCount].type;
  2024. PA_DEBUG(("ASIO Output type:%d",outputType));
  2025. AsioSampleTypeLOG(outputType);
  2026. hostOutputSampleFormat = AsioSampleTypeToPaNativeSampleFormat( outputType );
  2027. SelectPaToAsioConverter( outputType, &stream->outputBufferConverter, &stream->outputShift );
  2028. }
  2029. else
  2030. {
  2031. hostOutputSampleFormat = 0;
  2032. stream->outputBufferConverter = 0;
  2033. }
  2034. /* Values returned by ASIOGetLatencies() include the latency introduced by
  2035. the ASIO double buffer. */
  2036. ASIOGetLatencies( &stream->asioInputLatencyFrames, &stream->asioOutputLatencyFrames );
  2037. /* Using blocking i/o interface... */
  2038. if( usingBlockingIo )
  2039. {
  2040. /* Allocate the blocking i/o input ring buffer memory. */
  2041. stream->blockingState = (PaAsioStreamBlockingState*)PaUtil_AllocateMemory( sizeof(PaAsioStreamBlockingState) );
  2042. if( !stream->blockingState )
  2043. {
  2044. result = paInsufficientMemory;
  2045. PA_DEBUG(("ERROR! Blocking i/o interface struct allocation failed in OpenStream()\n"));
  2046. goto error;
  2047. }
  2048. /* Initialize blocking i/o interface struct. */
  2049. stream->blockingState->readFramesReadyEvent = NULL; /* Uninitialized, yet. */
  2050. stream->blockingState->writeBuffersReadyEvent = NULL; /* Uninitialized, yet. */
  2051. stream->blockingState->readRingBufferData = NULL; /* Uninitialized, yet. */
  2052. stream->blockingState->writeRingBufferData = NULL; /* Uninitialized, yet. */
  2053. stream->blockingState->readStreamBuffer = NULL; /* Uninitialized, yet. */
  2054. stream->blockingState->writeStreamBuffer = NULL; /* Uninitialized, yet. */
  2055. stream->blockingState->stopFlag = TRUE; /* Not started, yet. */
  2056. /* If the user buffer is unspecified */
  2057. if( framesPerBuffer == paFramesPerBufferUnspecified )
  2058. {
  2059. /* Make the user buffer the same size as the host buffer. */
  2060. framesPerBuffer = framesPerHostBuffer;
  2061. }
  2062. /* Initialize callback buffer processor. */
  2063. result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor ,
  2064. inputChannelCount ,
  2065. inputSampleFormat & ~paNonInterleaved , /* Ring buffer. */
  2066. (hostInputSampleFormat | paNonInterleaved), /* Host format. */
  2067. outputChannelCount ,
  2068. outputSampleFormat & ~paNonInterleaved, /* Ring buffer. */
  2069. (hostOutputSampleFormat | paNonInterleaved), /* Host format. */
  2070. sampleRate ,
  2071. streamFlags ,
  2072. framesPerBuffer , /* Frames per ring buffer block. */
  2073. framesPerHostBuffer , /* Frames per asio buffer. */
  2074. paUtilFixedHostBufferSize ,
  2075. streamCallback ,
  2076. userData );
  2077. if( result != paNoError ){
  2078. PA_DEBUG(("OpenStream ERROR13\n"));
  2079. goto error;
  2080. }
  2081. callbackBufferProcessorInited = TRUE;
  2082. /* Initialize the blocking i/o buffer processor. */
  2083. result = PaUtil_InitializeBufferProcessor(&stream->blockingState->bufferProcessor,
  2084. inputChannelCount ,
  2085. inputSampleFormat , /* User format. */
  2086. inputSampleFormat & ~paNonInterleaved , /* Ring buffer. */
  2087. outputChannelCount ,
  2088. outputSampleFormat , /* User format. */
  2089. outputSampleFormat & ~paNonInterleaved, /* Ring buffer. */
  2090. sampleRate ,
  2091. paClipOff | paDitherOff , /* Don't use dither nor clipping. */
  2092. framesPerBuffer , /* Frames per user buffer. */
  2093. framesPerBuffer , /* Frames per ring buffer block. */
  2094. paUtilBoundedHostBufferSize ,
  2095. NULL, NULL );/* No callback! */
  2096. if( result != paNoError ){
  2097. PA_DEBUG(("ERROR! Blocking i/o buffer processor initialization failed in OpenStream()\n"));
  2098. goto error;
  2099. }
  2100. blockingBufferProcessorInited = TRUE;
  2101. /* If input is requested. */
  2102. if( inputChannelCount )
  2103. {
  2104. /* Create the callback sync-event. */
  2105. stream->blockingState->readFramesReadyEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  2106. if( stream->blockingState->readFramesReadyEvent == NULL )
  2107. {
  2108. result = paUnanticipatedHostError;
  2109. PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
  2110. PA_DEBUG(("ERROR! Blocking i/o \"read frames ready\" event creation failed in OpenStream()\n"));
  2111. goto error;
  2112. }
  2113. blockingReadFramesReadyEventInitialized = 1;
  2114. /* Create pointer buffer to access non-interleaved data in ReadStream() */
  2115. stream->blockingState->readStreamBuffer = (void**)PaUtil_AllocateMemory( sizeof(void*) * inputChannelCount );
  2116. if( !stream->blockingState->readStreamBuffer )
  2117. {
  2118. result = paInsufficientMemory;
  2119. PA_DEBUG(("ERROR! Blocking i/o read stream buffer allocation failed in OpenStream()\n"));
  2120. goto error;
  2121. }
  2122. /* The ring buffer should store as many data blocks as needed
  2123. to achieve the requested latency. Whereas it must be large
  2124. enough to store at least two complete data blocks.
  2125. 1) Determine the amount of latency to be added to the
  2126. prefered ASIO latency.
  2127. 2) Make sure we have at lest one additional latency frame.
  2128. 3) Divide the number of frames by the desired block size to
  2129. get the number (rounded up to pure integer) of blocks to
  2130. be stored in the buffer.
  2131. 4) Add one additional block for block processing and convert
  2132. to samples frames.
  2133. 5) Get the next larger (or equal) power-of-two buffer size.
  2134. */
  2135. lBlockingBufferSize = suggestedInputLatencyFrames - stream->asioInputLatencyFrames;
  2136. lBlockingBufferSize = (lBlockingBufferSize > 0) ? lBlockingBufferSize : 1;
  2137. lBlockingBufferSize = (lBlockingBufferSize + framesPerBuffer - 1) / framesPerBuffer;
  2138. lBlockingBufferSize = (lBlockingBufferSize + 1) * framesPerBuffer;
  2139. /* Get the next larger or equal power-of-two buffersize. */
  2140. lBlockingBufferSizePow2 = 1;
  2141. while( lBlockingBufferSize > (lBlockingBufferSizePow2<<=1) );
  2142. lBlockingBufferSize = lBlockingBufferSizePow2;
  2143. /* Compute total intput latency in seconds */
  2144. stream->streamRepresentation.streamInfo.inputLatency =
  2145. (double)( PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor )
  2146. + PaUtil_GetBufferProcessorInputLatencyFrames(&stream->blockingState->bufferProcessor)
  2147. + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer
  2148. + stream->asioInputLatencyFrames )
  2149. / sampleRate;
  2150. /* The code below prints the ASIO latency which doesn't include
  2151. the buffer processor latency nor the blocking i/o latency. It
  2152. reports the added latency separately.
  2153. */
  2154. PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms),\n added buffProc:%ld (%ld ms),\n added blocking:%ld (%ld ms)\n",
  2155. stream->asioInputLatencyFrames,
  2156. (long)( stream->asioInputLatencyFrames * (1000.0 / sampleRate) ),
  2157. PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor),
  2158. (long)( PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor) * (1000.0 / sampleRate) ),
  2159. PaUtil_GetBufferProcessorInputLatencyFrames(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer,
  2160. (long)( (PaUtil_GetBufferProcessorInputLatencyFrames(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer) * (1000.0 / sampleRate) )
  2161. ));
  2162. /* Determine the size of ring buffer in bytes. */
  2163. lBytesPerFrame = inputChannelCount * Pa_GetSampleSize(inputSampleFormat );
  2164. /* Allocate the blocking i/o input ring buffer memory. */
  2165. stream->blockingState->readRingBufferData = (void*)PaUtil_AllocateMemory( lBlockingBufferSize * lBytesPerFrame );
  2166. if( !stream->blockingState->readRingBufferData )
  2167. {
  2168. result = paInsufficientMemory;
  2169. PA_DEBUG(("ERROR! Blocking i/o input ring buffer allocation failed in OpenStream()\n"));
  2170. goto error;
  2171. }
  2172. /* Initialize the input ring buffer struct. */
  2173. PaUtil_InitializeRingBuffer( &stream->blockingState->readRingBuffer ,
  2174. lBytesPerFrame ,
  2175. lBlockingBufferSize ,
  2176. stream->blockingState->readRingBufferData );
  2177. }
  2178. /* If output is requested. */
  2179. if( outputChannelCount )
  2180. {
  2181. stream->blockingState->writeBuffersReadyEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  2182. if( stream->blockingState->writeBuffersReadyEvent == NULL )
  2183. {
  2184. result = paUnanticipatedHostError;
  2185. PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
  2186. PA_DEBUG(("ERROR! Blocking i/o \"write buffers ready\" event creation failed in OpenStream()\n"));
  2187. goto error;
  2188. }
  2189. blockingWriteBuffersReadyEventInitialized = 1;
  2190. /* Create pointer buffer to access non-interleaved data in WriteStream() */
  2191. stream->blockingState->writeStreamBuffer = (const void**)PaUtil_AllocateMemory( sizeof(const void*) * outputChannelCount );
  2192. if( !stream->blockingState->writeStreamBuffer )
  2193. {
  2194. result = paInsufficientMemory;
  2195. PA_DEBUG(("ERROR! Blocking i/o write stream buffer allocation failed in OpenStream()\n"));
  2196. goto error;
  2197. }
  2198. /* The ring buffer should store as many data blocks as needed
  2199. to achieve the requested latency. Whereas it must be large
  2200. enough to store at least two complete data blocks.
  2201. 1) Determine the amount of latency to be added to the
  2202. prefered ASIO latency.
  2203. 2) Make sure we have at lest one additional latency frame.
  2204. 3) Divide the number of frames by the desired block size to
  2205. get the number (rounded up to pure integer) of blocks to
  2206. be stored in the buffer.
  2207. 4) Add one additional block for block processing and convert
  2208. to samples frames.
  2209. 5) Get the next larger (or equal) power-of-two buffer size.
  2210. */
  2211. lBlockingBufferSize = suggestedOutputLatencyFrames - stream->asioOutputLatencyFrames;
  2212. lBlockingBufferSize = (lBlockingBufferSize > 0) ? lBlockingBufferSize : 1;
  2213. lBlockingBufferSize = (lBlockingBufferSize + framesPerBuffer - 1) / framesPerBuffer;
  2214. lBlockingBufferSize = (lBlockingBufferSize + 1) * framesPerBuffer;
  2215. /* The buffer size (without the additional block) corresponds
  2216. to the initial number of silent samples in the output ring
  2217. buffer. */
  2218. stream->blockingState->writeRingBufferInitialFrames = lBlockingBufferSize - framesPerBuffer;
  2219. /* Get the next larger or equal power-of-two buffersize. */
  2220. lBlockingBufferSizePow2 = 1;
  2221. while( lBlockingBufferSize > (lBlockingBufferSizePow2<<=1) );
  2222. lBlockingBufferSize = lBlockingBufferSizePow2;
  2223. /* Compute total output latency in seconds */
  2224. stream->streamRepresentation.streamInfo.outputLatency =
  2225. (double)( PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)
  2226. + PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->blockingState->bufferProcessor)
  2227. + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer
  2228. + stream->asioOutputLatencyFrames )
  2229. / sampleRate;
  2230. /* The code below prints the ASIO latency which doesn't include
  2231. the buffer processor latency nor the blocking i/o latency. It
  2232. reports the added latency separately.
  2233. */
  2234. PA_DEBUG(("PaAsio : ASIO OutputLatency = %ld (%ld ms),\n added buffProc:%ld (%ld ms),\n added blocking:%ld (%ld ms)\n",
  2235. stream->asioOutputLatencyFrames,
  2236. (long)( stream->asioOutputLatencyFrames * (1000.0 / sampleRate) ),
  2237. PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor),
  2238. (long)( PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor) * (1000.0 / sampleRate) ),
  2239. PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer,
  2240. (long)( (PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer) * (1000.0 / sampleRate) )
  2241. ));
  2242. /* Determine the size of ring buffer in bytes. */
  2243. lBytesPerFrame = outputChannelCount * Pa_GetSampleSize(outputSampleFormat);
  2244. /* Allocate the blocking i/o output ring buffer memory. */
  2245. stream->blockingState->writeRingBufferData = (void*)PaUtil_AllocateMemory( lBlockingBufferSize * lBytesPerFrame );
  2246. if( !stream->blockingState->writeRingBufferData )
  2247. {
  2248. result = paInsufficientMemory;
  2249. PA_DEBUG(("ERROR! Blocking i/o output ring buffer allocation failed in OpenStream()\n"));
  2250. goto error;
  2251. }
  2252. /* Initialize the output ring buffer struct. */
  2253. PaUtil_InitializeRingBuffer( &stream->blockingState->writeRingBuffer ,
  2254. lBytesPerFrame ,
  2255. lBlockingBufferSize ,
  2256. stream->blockingState->writeRingBufferData );
  2257. }
  2258. stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
  2259. }
  2260. else /* Using callback interface... */
  2261. {
  2262. result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
  2263. inputChannelCount, inputSampleFormat, (hostInputSampleFormat | paNonInterleaved),
  2264. outputChannelCount, outputSampleFormat, (hostOutputSampleFormat | paNonInterleaved),
  2265. sampleRate, streamFlags, framesPerBuffer,
  2266. framesPerHostBuffer, paUtilFixedHostBufferSize,
  2267. streamCallback, userData );
  2268. if( result != paNoError ){
  2269. PA_DEBUG(("OpenStream ERROR13\n"));
  2270. goto error;
  2271. }
  2272. callbackBufferProcessorInited = TRUE;
  2273. stream->streamRepresentation.streamInfo.inputLatency =
  2274. (double)( PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor)
  2275. + stream->asioInputLatencyFrames) / sampleRate; // seconds
  2276. stream->streamRepresentation.streamInfo.outputLatency =
  2277. (double)( PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)
  2278. + stream->asioOutputLatencyFrames) / sampleRate; // seconds
  2279. stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
  2280. // the code below prints the ASIO latency which doesn't include the
  2281. // buffer processor latency. it reports the added latency separately
  2282. PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n",
  2283. stream->asioInputLatencyFrames,
  2284. (long)((stream->asioInputLatencyFrames*1000)/ sampleRate),
  2285. PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor),
  2286. (long)((PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor)*1000)/ sampleRate)
  2287. ));
  2288. PA_DEBUG(("PaAsio : ASIO OuputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n",
  2289. stream->asioOutputLatencyFrames,
  2290. (long)((stream->asioOutputLatencyFrames*1000)/ sampleRate),
  2291. PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor),
  2292. (long)((PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)*1000)/ sampleRate)
  2293. ));
  2294. }
  2295. stream->asioHostApi = asioHostApi;
  2296. stream->framesPerHostCallback = framesPerHostBuffer;
  2297. stream->inputChannelCount = inputChannelCount;
  2298. stream->outputChannelCount = outputChannelCount;
  2299. stream->postOutput = driverInfo->postOutput;
  2300. stream->isStopped = 1;
  2301. stream->isActive = 0;
  2302. asioHostApi->openAsioDeviceIndex = asioDeviceIndex;
  2303. theAsioStream = stream;
  2304. *s = (PaStream*)stream;
  2305. return result;
  2306. error:
  2307. PA_DEBUG(("goto errored\n"));
  2308. if( stream )
  2309. {
  2310. if( stream->blockingState )
  2311. {
  2312. if( blockingBufferProcessorInited )
  2313. PaUtil_TerminateBufferProcessor( &stream->blockingState->bufferProcessor );
  2314. if( stream->blockingState->writeRingBufferData )
  2315. PaUtil_FreeMemory( stream->blockingState->writeRingBufferData );
  2316. if( stream->blockingState->writeStreamBuffer )
  2317. PaUtil_FreeMemory( stream->blockingState->writeStreamBuffer );
  2318. if( blockingWriteBuffersReadyEventInitialized )
  2319. CloseHandle( stream->blockingState->writeBuffersReadyEvent );
  2320. if( stream->blockingState->readRingBufferData )
  2321. PaUtil_FreeMemory( stream->blockingState->readRingBufferData );
  2322. if( stream->blockingState->readStreamBuffer )
  2323. PaUtil_FreeMemory( stream->blockingState->readStreamBuffer );
  2324. if( blockingReadFramesReadyEventInitialized )
  2325. CloseHandle( stream->blockingState->readFramesReadyEvent );
  2326. PaUtil_FreeMemory( stream->blockingState );
  2327. }
  2328. if( callbackBufferProcessorInited )
  2329. PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
  2330. if( completedBuffersPlayedEventInited )
  2331. CloseHandle( stream->completedBuffersPlayedEvent );
  2332. if( stream->asioBufferInfos )
  2333. PaUtil_FreeMemory( stream->asioBufferInfos );
  2334. if( stream->asioChannelInfos )
  2335. PaUtil_FreeMemory( stream->asioChannelInfos );
  2336. if( stream->bufferPtrs )
  2337. PaUtil_FreeMemory( stream->bufferPtrs );
  2338. PaUtil_FreeMemory( stream );
  2339. }
  2340. if( asioBuffersCreated )
  2341. ASIODisposeBuffers();
  2342. if( asioIsInitialized )
  2343. {
  2344. UnloadAsioDriver();
  2345. }
  2346. return result;
  2347. }
  2348. /*
  2349. When CloseStream() is called, the multi-api layer ensures that
  2350. the stream has already been stopped or aborted.
  2351. */
  2352. static PaError CloseStream( PaStream* s )
  2353. {
  2354. PaError result = paNoError;
  2355. PaAsioStream *stream = (PaAsioStream*)s;
  2356. /*
  2357. IMPLEMENT ME:
  2358. - additional stream closing + cleanup
  2359. */
  2360. PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
  2361. PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
  2362. stream->asioHostApi->openAsioDeviceIndex = paNoDevice;
  2363. CloseHandle( stream->completedBuffersPlayedEvent );
  2364. /* Using blocking i/o interface... */
  2365. if( stream->blockingState )
  2366. {
  2367. PaUtil_TerminateBufferProcessor( &stream->blockingState->bufferProcessor );
  2368. if( stream->inputChannelCount ) {
  2369. PaUtil_FreeMemory( stream->blockingState->readRingBufferData );
  2370. PaUtil_FreeMemory( stream->blockingState->readStreamBuffer );
  2371. CloseHandle( stream->blockingState->readFramesReadyEvent );
  2372. }
  2373. if( stream->outputChannelCount ) {
  2374. PaUtil_FreeMemory( stream->blockingState->writeRingBufferData );
  2375. PaUtil_FreeMemory( stream->blockingState->writeStreamBuffer );
  2376. CloseHandle( stream->blockingState->writeBuffersReadyEvent );
  2377. }
  2378. PaUtil_FreeMemory( stream->blockingState );
  2379. }
  2380. PaUtil_FreeMemory( stream->asioBufferInfos );
  2381. PaUtil_FreeMemory( stream->asioChannelInfos );
  2382. PaUtil_FreeMemory( stream->bufferPtrs );
  2383. PaUtil_FreeMemory( stream );
  2384. ASIODisposeBuffers();
  2385. UnloadAsioDriver();
  2386. theAsioStream = 0;
  2387. return result;
  2388. }
  2389. static void bufferSwitch(long index, ASIOBool directProcess)
  2390. {
  2391. //TAKEN FROM THE ASIO SDK
  2392. // the actual processing callback.
  2393. // Beware that this is normally in a seperate thread, hence be sure that
  2394. // you take care about thread synchronization. This is omitted here for
  2395. // simplicity.
  2396. // as this is a "back door" into the bufferSwitchTimeInfo a timeInfo needs
  2397. // to be created though it will only set the timeInfo.samplePosition and
  2398. // timeInfo.systemTime fields and the according flags
  2399. ASIOTime timeInfo;
  2400. memset( &timeInfo, 0, sizeof (timeInfo) );
  2401. // get the time stamp of the buffer, not necessary if no
  2402. // synchronization to other media is required
  2403. if( ASIOGetSamplePosition(&timeInfo.timeInfo.samplePosition, &timeInfo.timeInfo.systemTime) == ASE_OK)
  2404. timeInfo.timeInfo.flags = kSystemTimeValid | kSamplePositionValid;
  2405. // Call the real callback
  2406. bufferSwitchTimeInfo( &timeInfo, index, directProcess );
  2407. }
  2408. // conversion from 64 bit ASIOSample/ASIOTimeStamp to double float
  2409. #if NATIVE_INT64
  2410. #define ASIO64toDouble(a) (a)
  2411. #else
  2412. const double twoRaisedTo32 = 4294967296.;
  2413. #define ASIO64toDouble(a) ((a).lo + (a).hi * twoRaisedTo32)
  2414. #endif
  2415. static ASIOTime *bufferSwitchTimeInfo( ASIOTime *timeInfo, long index, ASIOBool directProcess )
  2416. {
  2417. // the actual processing callback.
  2418. // Beware that this is normally in a seperate thread, hence be sure that
  2419. // you take care about thread synchronization.
  2420. /* The SDK says the following about the directProcess flag:
  2421. suggests to the host whether it should immediately start processing
  2422. (directProcess == ASIOTrue), or whether its process should be deferred
  2423. because the call comes from a very low level (for instance, a high level
  2424. priority interrupt), and direct processing would cause timing instabilities for
  2425. the rest of the system. If in doubt, directProcess should be set to ASIOFalse.
  2426. We just ignore directProcess. This could cause incompatibilities with
  2427. drivers which really don't want the audio processing to occur in this
  2428. callback, but none have been identified yet.
  2429. */
  2430. (void) directProcess; /* suppress unused parameter warning */
  2431. #if 0
  2432. // store the timeInfo for later use
  2433. asioDriverInfo.tInfo = *timeInfo;
  2434. // get the time stamp of the buffer, not necessary if no
  2435. // synchronization to other media is required
  2436. if (timeInfo->timeInfo.flags & kSystemTimeValid)
  2437. asioDriverInfo.nanoSeconds = ASIO64toDouble(timeInfo->timeInfo.systemTime);
  2438. else
  2439. asioDriverInfo.nanoSeconds = 0;
  2440. if (timeInfo->timeInfo.flags & kSamplePositionValid)
  2441. asioDriverInfo.samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition);
  2442. else
  2443. asioDriverInfo.samples = 0;
  2444. if (timeInfo->timeCode.flags & kTcValid)
  2445. asioDriverInfo.tcSamples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples);
  2446. else
  2447. asioDriverInfo.tcSamples = 0;
  2448. // get the system reference time
  2449. asioDriverInfo.sysRefTime = get_sys_reference_time();
  2450. #endif
  2451. #if 0
  2452. // a few debug messages for the Windows device driver developer
  2453. // tells you the time when driver got its interrupt and the delay until the app receives
  2454. // the event notification.
  2455. static double last_samples = 0;
  2456. char tmp[128];
  2457. sprintf (tmp, "diff: %d / %d ms / %d ms / %d samples \n", asioDriverInfo.sysRefTime - (long)(asioDriverInfo.nanoSeconds / 1000000.0), asioDriverInfo.sysRefTime, (long)(asioDriverInfo.nanoSeconds / 1000000.0), (long)(asioDriverInfo.samples - last_samples));
  2458. OutputDebugString (tmp);
  2459. last_samples = asioDriverInfo.samples;
  2460. #endif
  2461. if( !theAsioStream )
  2462. return 0L;
  2463. // protect against reentrancy
  2464. if( PaAsio_AtomicIncrement(&theAsioStream->reenterCount) )
  2465. {
  2466. theAsioStream->reenterError++;
  2467. //DBUG(("bufferSwitchTimeInfo : reentrancy detection = %d\n", asioDriverInfo.reenterError));
  2468. return 0L;
  2469. }
  2470. int buffersDone = 0;
  2471. do
  2472. {
  2473. if( buffersDone > 0 )
  2474. {
  2475. // this is a reentered buffer, we missed processing it on time
  2476. // set the input overflow and output underflow flags as appropriate
  2477. if( theAsioStream->inputChannelCount > 0 )
  2478. theAsioStream->callbackFlags |= paInputOverflow;
  2479. if( theAsioStream->outputChannelCount > 0 )
  2480. theAsioStream->callbackFlags |= paOutputUnderflow;
  2481. }
  2482. else
  2483. {
  2484. if( theAsioStream->zeroOutput )
  2485. {
  2486. ZeroOutputBuffers( theAsioStream, index );
  2487. // Finally if the driver supports the ASIOOutputReady() optimization,
  2488. // do it here, all data are in place
  2489. if( theAsioStream->postOutput )
  2490. ASIOOutputReady();
  2491. if( theAsioStream->stopProcessing )
  2492. {
  2493. if( theAsioStream->stopPlayoutCount < 2 )
  2494. {
  2495. ++theAsioStream->stopPlayoutCount;
  2496. if( theAsioStream->stopPlayoutCount == 2 )
  2497. {
  2498. theAsioStream->isActive = 0;
  2499. if( theAsioStream->streamRepresentation.streamFinishedCallback != 0 )
  2500. theAsioStream->streamRepresentation.streamFinishedCallback( theAsioStream->streamRepresentation.userData );
  2501. theAsioStream->streamFinishedCallbackCalled = true;
  2502. SetEvent( theAsioStream->completedBuffersPlayedEvent );
  2503. }
  2504. }
  2505. }
  2506. }
  2507. else
  2508. {
  2509. #if 0
  2510. /*
  2511. see: "ASIO callback underflow/overflow buffer slip detection doesn't work"
  2512. http://www.portaudio.com/trac/ticket/110
  2513. */
  2514. // test code to try to detect slip conditions... these may work on some systems
  2515. // but neither of them work on the RME Digi96
  2516. // check that sample delta matches buffer size (otherwise we must have skipped
  2517. // a buffer.
  2518. static double last_samples = -512;
  2519. double samples;
  2520. //if( timeInfo->timeCode.flags & kTcValid )
  2521. // samples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples);
  2522. //else
  2523. samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition);
  2524. int delta = samples - last_samples;
  2525. //printf( "%d\n", delta);
  2526. last_samples = samples;
  2527. if( delta > theAsioStream->framesPerHostCallback )
  2528. {
  2529. if( theAsioStream->inputChannelCount > 0 )
  2530. theAsioStream->callbackFlags |= paInputOverflow;
  2531. if( theAsioStream->outputChannelCount > 0 )
  2532. theAsioStream->callbackFlags |= paOutputUnderflow;
  2533. }
  2534. // check that the buffer index is not the previous index (which would indicate
  2535. // that a buffer was skipped.
  2536. static int previousIndex = 1;
  2537. if( index == previousIndex )
  2538. {
  2539. if( theAsioStream->inputChannelCount > 0 )
  2540. theAsioStream->callbackFlags |= paInputOverflow;
  2541. if( theAsioStream->outputChannelCount > 0 )
  2542. theAsioStream->callbackFlags |= paOutputUnderflow;
  2543. }
  2544. previousIndex = index;
  2545. #endif
  2546. int i;
  2547. PaUtil_BeginCpuLoadMeasurement( &theAsioStream->cpuLoadMeasurer );
  2548. PaStreamCallbackTimeInfo paTimeInfo;
  2549. // asio systemTime is supposed to be measured according to the same
  2550. // clock as timeGetTime
  2551. paTimeInfo.currentTime = (ASIO64toDouble( timeInfo->timeInfo.systemTime ) * .000000001);
  2552. /* patch from Paul Boege */
  2553. paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime -
  2554. ((double)theAsioStream->asioInputLatencyFrames/theAsioStream->streamRepresentation.streamInfo.sampleRate);
  2555. paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime +
  2556. ((double)theAsioStream->asioOutputLatencyFrames/theAsioStream->streamRepresentation.streamInfo.sampleRate);
  2557. /* old version is buggy because the buffer processor also adds in its latency to the time parameters
  2558. paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime - theAsioStream->streamRepresentation.streamInfo.inputLatency;
  2559. paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime + theAsioStream->streamRepresentation.streamInfo.outputLatency;
  2560. */
  2561. /* Disabled! Stopping and re-starting the stream causes an input overflow / output underflow. S.Fischer */
  2562. #if 0
  2563. // detect underflows by checking inter-callback time > 2 buffer period
  2564. static double previousTime = -1;
  2565. if( previousTime > 0 ){
  2566. double delta = paTimeInfo.currentTime - previousTime;
  2567. if( delta >= 2. * (theAsioStream->framesPerHostCallback / theAsioStream->streamRepresentation.streamInfo.sampleRate) ){
  2568. if( theAsioStream->inputChannelCount > 0 )
  2569. theAsioStream->callbackFlags |= paInputOverflow;
  2570. if( theAsioStream->outputChannelCount > 0 )
  2571. theAsioStream->callbackFlags |= paOutputUnderflow;
  2572. }
  2573. }
  2574. previousTime = paTimeInfo.currentTime;
  2575. #endif
  2576. // note that the above input and output times do not need to be
  2577. // adjusted for the latency of the buffer processor -- the buffer
  2578. // processor handles that.
  2579. if( theAsioStream->inputBufferConverter )
  2580. {
  2581. for( i=0; i<theAsioStream->inputChannelCount; i++ )
  2582. {
  2583. theAsioStream->inputBufferConverter( theAsioStream->inputBufferPtrs[index][i],
  2584. theAsioStream->inputShift, theAsioStream->framesPerHostCallback );
  2585. }
  2586. }
  2587. PaUtil_BeginBufferProcessing( &theAsioStream->bufferProcessor, &paTimeInfo, theAsioStream->callbackFlags );
  2588. /* reset status flags once they've been passed to the callback */
  2589. theAsioStream->callbackFlags = 0;
  2590. PaUtil_SetInputFrameCount( &theAsioStream->bufferProcessor, 0 /* default to host buffer size */ );
  2591. for( i=0; i<theAsioStream->inputChannelCount; ++i )
  2592. PaUtil_SetNonInterleavedInputChannel( &theAsioStream->bufferProcessor, i, theAsioStream->inputBufferPtrs[index][i] );
  2593. PaUtil_SetOutputFrameCount( &theAsioStream->bufferProcessor, 0 /* default to host buffer size */ );
  2594. for( i=0; i<theAsioStream->outputChannelCount; ++i )
  2595. PaUtil_SetNonInterleavedOutputChannel( &theAsioStream->bufferProcessor, i, theAsioStream->outputBufferPtrs[index][i] );
  2596. int callbackResult;
  2597. if( theAsioStream->stopProcessing )
  2598. callbackResult = paComplete;
  2599. else
  2600. callbackResult = paContinue;
  2601. unsigned long framesProcessed = PaUtil_EndBufferProcessing( &theAsioStream->bufferProcessor, &callbackResult );
  2602. if( theAsioStream->outputBufferConverter )
  2603. {
  2604. for( i=0; i<theAsioStream->outputChannelCount; i++ )
  2605. {
  2606. theAsioStream->outputBufferConverter( theAsioStream->outputBufferPtrs[index][i],
  2607. theAsioStream->outputShift, theAsioStream->framesPerHostCallback );
  2608. }
  2609. }
  2610. PaUtil_EndCpuLoadMeasurement( &theAsioStream->cpuLoadMeasurer, framesProcessed );
  2611. // Finally if the driver supports the ASIOOutputReady() optimization,
  2612. // do it here, all data are in place
  2613. if( theAsioStream->postOutput )
  2614. ASIOOutputReady();
  2615. if( callbackResult == paContinue )
  2616. {
  2617. /* nothing special to do */
  2618. }
  2619. else if( callbackResult == paAbort )
  2620. {
  2621. /* finish playback immediately */
  2622. theAsioStream->isActive = 0;
  2623. if( theAsioStream->streamRepresentation.streamFinishedCallback != 0 )
  2624. theAsioStream->streamRepresentation.streamFinishedCallback( theAsioStream->streamRepresentation.userData );
  2625. theAsioStream->streamFinishedCallbackCalled = true;
  2626. SetEvent( theAsioStream->completedBuffersPlayedEvent );
  2627. theAsioStream->zeroOutput = true;
  2628. }
  2629. else /* paComplete or other non-zero value indicating complete */
  2630. {
  2631. /* Finish playback once currently queued audio has completed. */
  2632. theAsioStream->stopProcessing = true;
  2633. if( PaUtil_IsBufferProcessorOutputEmpty( &theAsioStream->bufferProcessor ) )
  2634. {
  2635. theAsioStream->zeroOutput = true;
  2636. theAsioStream->stopPlayoutCount = 0;
  2637. }
  2638. }
  2639. }
  2640. }
  2641. ++buffersDone;
  2642. }while( PaAsio_AtomicDecrement(&theAsioStream->reenterCount) >= 0 );
  2643. return 0L;
  2644. }
  2645. static void sampleRateChanged(ASIOSampleRate sRate)
  2646. {
  2647. // TAKEN FROM THE ASIO SDK
  2648. // do whatever you need to do if the sample rate changed
  2649. // usually this only happens during external sync.
  2650. // Audio processing is not stopped by the driver, actual sample rate
  2651. // might not have even changed, maybe only the sample rate status of an
  2652. // AES/EBU or S/PDIF digital input at the audio device.
  2653. // You might have to update time/sample related conversion routines, etc.
  2654. (void) sRate; /* unused parameter */
  2655. PA_DEBUG( ("sampleRateChanged : %d \n", sRate));
  2656. }
  2657. static long asioMessages(long selector, long value, void* message, double* opt)
  2658. {
  2659. // TAKEN FROM THE ASIO SDK
  2660. // currently the parameters "value", "message" and "opt" are not used.
  2661. long ret = 0;
  2662. (void) message; /* unused parameters */
  2663. (void) opt;
  2664. PA_DEBUG( ("asioMessages : %d , %d \n", selector, value));
  2665. switch(selector)
  2666. {
  2667. case kAsioSelectorSupported:
  2668. if(value == kAsioResetRequest
  2669. || value == kAsioEngineVersion
  2670. || value == kAsioResyncRequest
  2671. || value == kAsioLatenciesChanged
  2672. // the following three were added for ASIO 2.0, you don't necessarily have to support them
  2673. || value == kAsioSupportsTimeInfo
  2674. || value == kAsioSupportsTimeCode
  2675. || value == kAsioSupportsInputMonitor)
  2676. ret = 1L;
  2677. break;
  2678. case kAsioBufferSizeChange:
  2679. //printf("kAsioBufferSizeChange \n");
  2680. break;
  2681. case kAsioResetRequest:
  2682. // defer the task and perform the reset of the driver during the next "safe" situation
  2683. // You cannot reset the driver right now, as this code is called from the driver.
  2684. // Reset the driver is done by completely destruct is. I.e. ASIOStop(), ASIODisposeBuffers(), Destruction
  2685. // Afterwards you initialize the driver again.
  2686. /*FIXME: commented the next line out
  2687. see: "PA/ASIO ignores some driver notifications it probably shouldn't"
  2688. http://www.portaudio.com/trac/ticket/108
  2689. */
  2690. //asioDriverInfo.stopped; // In this sample the processing will just stop
  2691. ret = 1L;
  2692. break;
  2693. case kAsioResyncRequest:
  2694. // This informs the application, that the driver encountered some non fatal data loss.
  2695. // It is used for synchronization purposes of different media.
  2696. // Added mainly to work around the Win16Mutex problems in Windows 95/98 with the
  2697. // Windows Multimedia system, which could loose data because the Mutex was hold too long
  2698. // by another thread.
  2699. // However a driver can issue it in other situations, too.
  2700. ret = 1L;
  2701. break;
  2702. case kAsioLatenciesChanged:
  2703. // This will inform the host application that the drivers were latencies changed.
  2704. // Beware, it this does not mean that the buffer sizes have changed!
  2705. // You might need to update internal delay data.
  2706. ret = 1L;
  2707. //printf("kAsioLatenciesChanged \n");
  2708. break;
  2709. case kAsioEngineVersion:
  2710. // return the supported ASIO version of the host application
  2711. // If a host applications does not implement this selector, ASIO 1.0 is assumed
  2712. // by the driver
  2713. ret = 2L;
  2714. break;
  2715. case kAsioSupportsTimeInfo:
  2716. // informs the driver wether the asioCallbacks.bufferSwitchTimeInfo() callback
  2717. // is supported.
  2718. // For compatibility with ASIO 1.0 drivers the host application should always support
  2719. // the "old" bufferSwitch method, too.
  2720. ret = 1;
  2721. break;
  2722. case kAsioSupportsTimeCode:
  2723. // informs the driver wether application is interested in time code info.
  2724. // If an application does not need to know about time code, the driver has less work
  2725. // to do.
  2726. ret = 0;
  2727. break;
  2728. }
  2729. return ret;
  2730. }
  2731. static PaError StartStream( PaStream *s )
  2732. {
  2733. PaError result = paNoError;
  2734. PaAsioStream *stream = (PaAsioStream*)s;
  2735. PaAsioStreamBlockingState *blockingState = stream->blockingState;
  2736. ASIOError asioError;
  2737. if( stream->outputChannelCount > 0 )
  2738. {
  2739. ZeroOutputBuffers( stream, 0 );
  2740. ZeroOutputBuffers( stream, 1 );
  2741. }
  2742. PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
  2743. stream->stopProcessing = false;
  2744. stream->zeroOutput = false;
  2745. /* Reentrancy counter initialisation */
  2746. stream->reenterCount = -1;
  2747. stream->reenterError = 0;
  2748. stream->callbackFlags = 0;
  2749. if( ResetEvent( stream->completedBuffersPlayedEvent ) == 0 )
  2750. {
  2751. result = paUnanticipatedHostError;
  2752. PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
  2753. }
  2754. /* Using blocking i/o interface... */
  2755. if( blockingState )
  2756. {
  2757. /* Reset blocking i/o buffer processor. */
  2758. PaUtil_ResetBufferProcessor( &blockingState->bufferProcessor );
  2759. /* If we're about to process some input data. */
  2760. if( stream->inputChannelCount )
  2761. {
  2762. /* Reset callback-ReadStream sync event. */
  2763. if( ResetEvent( blockingState->readFramesReadyEvent ) == 0 )
  2764. {
  2765. result = paUnanticipatedHostError;
  2766. PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
  2767. }
  2768. /* Flush blocking i/o ring buffer. */
  2769. PaUtil_FlushRingBuffer( &blockingState->readRingBuffer );
  2770. (*blockingState->bufferProcessor.inputZeroer)( blockingState->readRingBuffer.buffer, 1, blockingState->bufferProcessor.inputChannelCount * blockingState->readRingBuffer.bufferSize );
  2771. }
  2772. /* If we're about to process some output data. */
  2773. if( stream->outputChannelCount )
  2774. {
  2775. /* Reset callback-WriteStream sync event. */
  2776. if( ResetEvent( blockingState->writeBuffersReadyEvent ) == 0 )
  2777. {
  2778. result = paUnanticipatedHostError;
  2779. PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
  2780. }
  2781. /* Flush blocking i/o ring buffer. */
  2782. PaUtil_FlushRingBuffer( &blockingState->writeRingBuffer );
  2783. (*blockingState->bufferProcessor.outputZeroer)( blockingState->writeRingBuffer.buffer, 1, blockingState->bufferProcessor.outputChannelCount * blockingState->writeRingBuffer.bufferSize );
  2784. /* Initialize the output ring buffer to "silence". */
  2785. PaUtil_AdvanceRingBufferWriteIndex( &blockingState->writeRingBuffer, blockingState->writeRingBufferInitialFrames );
  2786. }
  2787. /* Clear requested frames / buffers count. */
  2788. blockingState->writeBuffersRequested = 0;
  2789. blockingState->readFramesRequested = 0;
  2790. blockingState->writeBuffersRequestedFlag = FALSE;
  2791. blockingState->readFramesRequestedFlag = FALSE;
  2792. blockingState->outputUnderflowFlag = FALSE;
  2793. blockingState->inputOverflowFlag = FALSE;
  2794. blockingState->stopFlag = FALSE;
  2795. }
  2796. if( result == paNoError )
  2797. {
  2798. assert( theAsioStream == stream ); /* theAsioStream should be set correctly in OpenStream */
  2799. /* initialize these variables before the callback has a chance to be invoked */
  2800. stream->isStopped = 0;
  2801. stream->isActive = 1;
  2802. stream->streamFinishedCallbackCalled = false;
  2803. asioError = ASIOStart();
  2804. if( asioError != ASE_OK )
  2805. {
  2806. stream->isStopped = 1;
  2807. stream->isActive = 0;
  2808. result = paUnanticipatedHostError;
  2809. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  2810. }
  2811. }
  2812. return result;
  2813. }
  2814. static void EnsureCallbackHasCompleted( PaAsioStream *stream )
  2815. {
  2816. // make sure that the callback is not still in-flight after ASIOStop()
  2817. // returns. This has been observed to happen on the Hoontech DSP24 for
  2818. // example.
  2819. int count = 2000; // only wait for 2 seconds, rather than hanging.
  2820. while( stream->reenterCount != -1 && count > 0 )
  2821. {
  2822. Sleep(1);
  2823. --count;
  2824. }
  2825. }
  2826. static PaError StopStream( PaStream *s )
  2827. {
  2828. PaError result = paNoError;
  2829. PaAsioStream *stream = (PaAsioStream*)s;
  2830. PaAsioStreamBlockingState *blockingState = stream->blockingState;
  2831. ASIOError asioError;
  2832. if( stream->isActive )
  2833. {
  2834. /* If blocking i/o output is in use */
  2835. if( blockingState && stream->outputChannelCount )
  2836. {
  2837. /* Request the whole output buffer to be available. */
  2838. blockingState->writeBuffersRequested = blockingState->writeRingBuffer.bufferSize;
  2839. /* Signalize that additional buffers are need. */
  2840. blockingState->writeBuffersRequestedFlag = TRUE;
  2841. /* Set flag to indicate the playback is to be stopped. */
  2842. blockingState->stopFlag = TRUE;
  2843. /* Wait until requested number of buffers has been freed. Time
  2844. out after twice the blocking i/o ouput buffer could have
  2845. been consumed. */
  2846. DWORD timeout = (DWORD)( 2 * blockingState->writeRingBuffer.bufferSize * 1000
  2847. / stream->streamRepresentation.streamInfo.sampleRate );
  2848. DWORD waitResult = WaitForSingleObject( blockingState->writeBuffersReadyEvent, timeout );
  2849. /* If something seriously went wrong... */
  2850. if( waitResult == WAIT_FAILED )
  2851. {
  2852. PA_DEBUG(("WaitForSingleObject() failed in StopStream()\n"));
  2853. result = paUnanticipatedHostError;
  2854. PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
  2855. }
  2856. else if( waitResult == WAIT_TIMEOUT )
  2857. {
  2858. PA_DEBUG(("WaitForSingleObject() timed out in StopStream()\n"));
  2859. result = paTimedOut;
  2860. }
  2861. }
  2862. stream->stopProcessing = true;
  2863. /* wait for the stream to finish playing out enqueued buffers.
  2864. timeout after four times the stream latency.
  2865. @todo should use a better time out value - if the user buffer
  2866. length is longer than the asio buffer size then that should
  2867. be taken into account.
  2868. */
  2869. if( WaitForSingleObject( stream->completedBuffersPlayedEvent,
  2870. (DWORD)(stream->streamRepresentation.streamInfo.outputLatency * 1000. * 4.) )
  2871. == WAIT_TIMEOUT )
  2872. {
  2873. PA_DEBUG(("WaitForSingleObject() timed out in StopStream()\n" ));
  2874. }
  2875. }
  2876. asioError = ASIOStop();
  2877. if( asioError == ASE_OK )
  2878. {
  2879. EnsureCallbackHasCompleted( stream );
  2880. }
  2881. else
  2882. {
  2883. result = paUnanticipatedHostError;
  2884. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  2885. }
  2886. stream->isStopped = 1;
  2887. stream->isActive = 0;
  2888. if( !stream->streamFinishedCallbackCalled )
  2889. {
  2890. if( stream->streamRepresentation.streamFinishedCallback != 0 )
  2891. stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
  2892. }
  2893. return result;
  2894. }
  2895. static PaError AbortStream( PaStream *s )
  2896. {
  2897. PaError result = paNoError;
  2898. PaAsioStream *stream = (PaAsioStream*)s;
  2899. ASIOError asioError;
  2900. stream->zeroOutput = true;
  2901. asioError = ASIOStop();
  2902. if( asioError == ASE_OK )
  2903. {
  2904. EnsureCallbackHasCompleted( stream );
  2905. }
  2906. else
  2907. {
  2908. result = paUnanticipatedHostError;
  2909. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  2910. }
  2911. stream->isStopped = 1;
  2912. stream->isActive = 0;
  2913. if( !stream->streamFinishedCallbackCalled )
  2914. {
  2915. if( stream->streamRepresentation.streamFinishedCallback != 0 )
  2916. stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
  2917. }
  2918. return result;
  2919. }
  2920. static PaError IsStreamStopped( PaStream *s )
  2921. {
  2922. PaAsioStream *stream = (PaAsioStream*)s;
  2923. return stream->isStopped;
  2924. }
  2925. static PaError IsStreamActive( PaStream *s )
  2926. {
  2927. PaAsioStream *stream = (PaAsioStream*)s;
  2928. return stream->isActive;
  2929. }
  2930. static PaTime GetStreamTime( PaStream *s )
  2931. {
  2932. (void) s; /* unused parameter */
  2933. return (double)timeGetTime() * .001;
  2934. }
  2935. static double GetStreamCpuLoad( PaStream* s )
  2936. {
  2937. PaAsioStream *stream = (PaAsioStream*)s;
  2938. return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
  2939. }
  2940. /*
  2941. As separate stream interfaces are used for blocking and callback
  2942. streams, the following functions can be guaranteed to only be called
  2943. for blocking streams.
  2944. */
  2945. static PaError ReadStream( PaStream *s ,
  2946. void *buffer,
  2947. unsigned long frames )
  2948. {
  2949. PaError result = paNoError; /* Initial return value. */
  2950. PaAsioStream *stream = (PaAsioStream*)s; /* The PA ASIO stream. */
  2951. /* Pointer to the blocking i/o data struct. */
  2952. PaAsioStreamBlockingState *blockingState = stream->blockingState;
  2953. /* Get blocking i/o buffer processor and ring buffer pointers. */
  2954. PaUtilBufferProcessor *pBp = &blockingState->bufferProcessor;
  2955. PaUtilRingBuffer *pRb = &blockingState->readRingBuffer;
  2956. /* Ring buffer segment(s) used for writing. */
  2957. void *pRingBufferData1st = NULL; /* First segment. (Mandatory) */
  2958. void *pRingBufferData2nd = NULL; /* Second segment. (Optional) */
  2959. /* Number of frames per ring buffer segment. */
  2960. long lRingBufferSize1st = 0; /* First segment. (Mandatory) */
  2961. long lRingBufferSize2nd = 0; /* Second segment. (Optional) */
  2962. /* Get number of frames to be processed per data block. */
  2963. unsigned long lFramesPerBlock = stream->bufferProcessor.framesPerUserBuffer;
  2964. /* Actual number of frames that has been copied into the ring buffer. */
  2965. unsigned long lFramesCopied = 0;
  2966. /* The number of remaining unprocessed dtat frames. */
  2967. unsigned long lFramesRemaining = frames;
  2968. /* Copy the input argument to avoid pointer increment! */
  2969. const void *userBuffer;
  2970. unsigned int i; /* Just a counter. */
  2971. /* About the time, needed to process 8 data blocks. */
  2972. DWORD timeout = (DWORD)( 8 * lFramesPerBlock * 1000 / stream->streamRepresentation.streamInfo.sampleRate );
  2973. DWORD waitResult = 0;
  2974. /* Check if the stream is still available ready to gather new data. */
  2975. if( blockingState->stopFlag || !stream->isActive )
  2976. {
  2977. PA_DEBUG(("Warning! Stream no longer available for reading in ReadStream()\n"));
  2978. result = paStreamIsStopped;
  2979. return result;
  2980. }
  2981. /* If the stream is a input stream. */
  2982. if( stream->inputChannelCount )
  2983. {
  2984. /* Prepare buffer access. */
  2985. if( !pBp->userOutputIsInterleaved )
  2986. {
  2987. userBuffer = blockingState->readStreamBuffer;
  2988. for( i = 0; i<pBp->inputChannelCount; ++i )
  2989. {
  2990. ((void**)userBuffer)[i] = ((void**)buffer)[i];
  2991. }
  2992. } /* Use the unchanged buffer. */
  2993. else { userBuffer = buffer; }
  2994. do /* Internal block processing for too large user data buffers. */
  2995. {
  2996. /* Get the size of the current data block to be processed. */
  2997. lFramesPerBlock =(lFramesPerBlock < lFramesRemaining)
  2998. ? lFramesPerBlock : lFramesRemaining;
  2999. /* Use predefined block size for as long there are enough
  3000. buffers available, thereafter reduce the processing block
  3001. size to match the number of remaining buffers. So the final
  3002. data block is processed although it may be incomplete. */
  3003. /* If the available amount of data frames is insufficient. */
  3004. if( PaUtil_GetRingBufferReadAvailable(pRb) < (long) lFramesPerBlock )
  3005. {
  3006. /* Make sure, the event isn't already set! */
  3007. /* ResetEvent( blockingState->readFramesReadyEvent ); */
  3008. /* Set the number of requested buffers. */
  3009. blockingState->readFramesRequested = lFramesPerBlock;
  3010. /* Signalize that additional buffers are need. */
  3011. blockingState->readFramesRequestedFlag = TRUE;
  3012. /* Wait until requested number of buffers has been freed. */
  3013. waitResult = WaitForSingleObject( blockingState->readFramesReadyEvent, timeout );
  3014. /* If something seriously went wrong... */
  3015. if( waitResult == WAIT_FAILED )
  3016. {
  3017. PA_DEBUG(("WaitForSingleObject() failed in ReadStream()\n"));
  3018. result = paUnanticipatedHostError;
  3019. PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
  3020. return result;
  3021. }
  3022. else if( waitResult == WAIT_TIMEOUT )
  3023. {
  3024. PA_DEBUG(("WaitForSingleObject() timed out in ReadStream()\n"));
  3025. /* If block processing has stopped, abort! */
  3026. if( blockingState->stopFlag ) { return result = paStreamIsStopped; }
  3027. /* If a timeout is encountered, give up eventually. */
  3028. return result = paTimedOut;
  3029. }
  3030. }
  3031. /* Now, the ring buffer contains the required amount of data
  3032. frames.
  3033. (Therefor we don't need to check the return argument of
  3034. PaUtil_GetRingBufferReadRegions(). ;-) )
  3035. */
  3036. /* Retrieve pointer(s) to the ring buffer's current write
  3037. position(s). If the first buffer segment is too small to
  3038. store the requested number of bytes, an additional second
  3039. segment is returned. Otherwise, i.e. if the first segment
  3040. is large enough, the second segment's pointer will be NULL.
  3041. */
  3042. PaUtil_GetRingBufferReadRegions(pRb ,
  3043. lFramesPerBlock ,
  3044. &pRingBufferData1st,
  3045. &lRingBufferSize1st,
  3046. &pRingBufferData2nd,
  3047. &lRingBufferSize2nd);
  3048. /* Set number of frames to be copied from the ring buffer. */
  3049. PaUtil_SetInputFrameCount( pBp, lRingBufferSize1st );
  3050. /* Setup ring buffer access. */
  3051. PaUtil_SetInterleavedInputChannels(pBp , /* Buffer processor. */
  3052. 0 , /* The first channel's index. */
  3053. pRingBufferData1st, /* First ring buffer segment. */
  3054. 0 ); /* Use all available channels. */
  3055. /* If a second ring buffer segment is required. */
  3056. if( lRingBufferSize2nd ) {
  3057. /* Set number of frames to be copied from the ring buffer. */
  3058. PaUtil_Set2ndInputFrameCount( pBp, lRingBufferSize2nd );
  3059. /* Setup ring buffer access. */
  3060. PaUtil_Set2ndInterleavedInputChannels(pBp , /* Buffer processor. */
  3061. 0 , /* The first channel's index. */
  3062. pRingBufferData2nd, /* Second ring buffer segment. */
  3063. 0 ); /* Use all available channels. */
  3064. }
  3065. /* Let the buffer processor handle "copy and conversion" and
  3066. update the ring buffer indices manually. */
  3067. lFramesCopied = PaUtil_CopyInput( pBp, &buffer, lFramesPerBlock );
  3068. PaUtil_AdvanceRingBufferReadIndex( pRb, lFramesCopied );
  3069. /* Decrease number of unprocessed frames. */
  3070. lFramesRemaining -= lFramesCopied;
  3071. } /* Continue with the next data chunk. */
  3072. while( lFramesRemaining );
  3073. /* If there has been an input overflow within the callback */
  3074. if( blockingState->inputOverflowFlag )
  3075. {
  3076. blockingState->inputOverflowFlag = FALSE;
  3077. /* Return the corresponding error code. */
  3078. result = paInputOverflowed;
  3079. }
  3080. } /* If this is not an input stream. */
  3081. else {
  3082. result = paCanNotReadFromAnOutputOnlyStream;
  3083. }
  3084. return result;
  3085. }
  3086. static PaError WriteStream( PaStream *s ,
  3087. const void *buffer,
  3088. unsigned long frames )
  3089. {
  3090. PaError result = paNoError; /* Initial return value. */
  3091. PaAsioStream *stream = (PaAsioStream*)s; /* The PA ASIO stream. */
  3092. /* Pointer to the blocking i/o data struct. */
  3093. PaAsioStreamBlockingState *blockingState = stream->blockingState;
  3094. /* Get blocking i/o buffer processor and ring buffer pointers. */
  3095. PaUtilBufferProcessor *pBp = &blockingState->bufferProcessor;
  3096. PaUtilRingBuffer *pRb = &blockingState->writeRingBuffer;
  3097. /* Ring buffer segment(s) used for writing. */
  3098. void *pRingBufferData1st = NULL; /* First segment. (Mandatory) */
  3099. void *pRingBufferData2nd = NULL; /* Second segment. (Optional) */
  3100. /* Number of frames per ring buffer segment. */
  3101. long lRingBufferSize1st = 0; /* First segment. (Mandatory) */
  3102. long lRingBufferSize2nd = 0; /* Second segment. (Optional) */
  3103. /* Get number of frames to be processed per data block. */
  3104. unsigned long lFramesPerBlock = stream->bufferProcessor.framesPerUserBuffer;
  3105. /* Actual number of frames that has been copied into the ring buffer. */
  3106. unsigned long lFramesCopied = 0;
  3107. /* The number of remaining unprocessed dtat frames. */
  3108. unsigned long lFramesRemaining = frames;
  3109. /* About the time, needed to process 8 data blocks. */
  3110. DWORD timeout = (DWORD)( 8 * lFramesPerBlock * 1000 / stream->streamRepresentation.streamInfo.sampleRate );
  3111. DWORD waitResult = 0;
  3112. /* Copy the input argument to avoid pointer increment! */
  3113. const void *userBuffer;
  3114. unsigned int i; /* Just a counter. */
  3115. /* Check if the stream ist still available ready to recieve new data. */
  3116. if( blockingState->stopFlag || !stream->isActive )
  3117. {
  3118. PA_DEBUG(("Warning! Stream no longer available for writing in WriteStream()\n"));
  3119. result = paStreamIsStopped;
  3120. return result;
  3121. }
  3122. /* If the stream is a output stream. */
  3123. if( stream->outputChannelCount )
  3124. {
  3125. /* Prepare buffer access. */
  3126. if( !pBp->userOutputIsInterleaved )
  3127. {
  3128. userBuffer = blockingState->writeStreamBuffer;
  3129. for( i = 0; i<pBp->outputChannelCount; ++i )
  3130. {
  3131. ((const void**)userBuffer)[i] = ((const void**)buffer)[i];
  3132. }
  3133. } /* Use the unchanged buffer. */
  3134. else { userBuffer = buffer; }
  3135. do /* Internal block processing for too large user data buffers. */
  3136. {
  3137. /* Get the size of the current data block to be processed. */
  3138. lFramesPerBlock =(lFramesPerBlock < lFramesRemaining)
  3139. ? lFramesPerBlock : lFramesRemaining;
  3140. /* Use predefined block size for as long there are enough
  3141. frames available, thereafter reduce the processing block
  3142. size to match the number of remaining frames. So the final
  3143. data block is processed although it may be incomplete. */
  3144. /* If the available amount of buffers is insufficient. */
  3145. if( PaUtil_GetRingBufferWriteAvailable(pRb) < (long) lFramesPerBlock )
  3146. {
  3147. /* Make sure, the event isn't already set! */
  3148. /* ResetEvent( blockingState->writeBuffersReadyEvent ); */
  3149. /* Set the number of requested buffers. */
  3150. blockingState->writeBuffersRequested = lFramesPerBlock;
  3151. /* Signalize that additional buffers are need. */
  3152. blockingState->writeBuffersRequestedFlag = TRUE;
  3153. /* Wait until requested number of buffers has been freed. */
  3154. waitResult = WaitForSingleObject( blockingState->writeBuffersReadyEvent, timeout );
  3155. /* If something seriously went wrong... */
  3156. if( waitResult == WAIT_FAILED )
  3157. {
  3158. PA_DEBUG(("WaitForSingleObject() failed in WriteStream()\n"));
  3159. result = paUnanticipatedHostError;
  3160. PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
  3161. return result;
  3162. }
  3163. else if( waitResult == WAIT_TIMEOUT )
  3164. {
  3165. PA_DEBUG(("WaitForSingleObject() timed out in WriteStream()\n"));
  3166. /* If block processing has stopped, abort! */
  3167. if( blockingState->stopFlag ) { return result = paStreamIsStopped; }
  3168. /* If a timeout is encountered, give up eventually. */
  3169. return result = paTimedOut;
  3170. }
  3171. }
  3172. /* Now, the ring buffer contains the required amount of free
  3173. space to store the provided number of data frames.
  3174. (Therefor we don't need to check the return argument of
  3175. PaUtil_GetRingBufferWriteRegions(). ;-) )
  3176. */
  3177. /* Retrieve pointer(s) to the ring buffer's current write
  3178. position(s). If the first buffer segment is too small to
  3179. store the requested number of bytes, an additional second
  3180. segment is returned. Otherwise, i.e. if the first segment
  3181. is large enough, the second segment's pointer will be NULL.
  3182. */
  3183. PaUtil_GetRingBufferWriteRegions(pRb ,
  3184. lFramesPerBlock ,
  3185. &pRingBufferData1st,
  3186. &lRingBufferSize1st,
  3187. &pRingBufferData2nd,
  3188. &lRingBufferSize2nd);
  3189. /* Set number of frames to be copied to the ring buffer. */
  3190. PaUtil_SetOutputFrameCount( pBp, lRingBufferSize1st );
  3191. /* Setup ring buffer access. */
  3192. PaUtil_SetInterleavedOutputChannels(pBp , /* Buffer processor. */
  3193. 0 , /* The first channel's index. */
  3194. pRingBufferData1st, /* First ring buffer segment. */
  3195. 0 ); /* Use all available channels. */
  3196. /* If a second ring buffer segment is required. */
  3197. if( lRingBufferSize2nd ) {
  3198. /* Set number of frames to be copied to the ring buffer. */
  3199. PaUtil_Set2ndOutputFrameCount( pBp, lRingBufferSize2nd );
  3200. /* Setup ring buffer access. */
  3201. PaUtil_Set2ndInterleavedOutputChannels(pBp , /* Buffer processor. */
  3202. 0 , /* The first channel's index. */
  3203. pRingBufferData2nd, /* Second ring buffer segment. */
  3204. 0 ); /* Use all available channels. */
  3205. }
  3206. /* Let the buffer processor handle "copy and conversion" and
  3207. update the ring buffer indices manually. */
  3208. lFramesCopied = PaUtil_CopyOutput( pBp, &userBuffer, lFramesPerBlock );
  3209. PaUtil_AdvanceRingBufferWriteIndex( pRb, lFramesCopied );
  3210. /* Decrease number of unprocessed frames. */
  3211. lFramesRemaining -= lFramesCopied;
  3212. } /* Continue with the next data chunk. */
  3213. while( lFramesRemaining );
  3214. /* If there has been an output underflow within the callback */
  3215. if( blockingState->outputUnderflowFlag )
  3216. {
  3217. blockingState->outputUnderflowFlag = FALSE;
  3218. /* Return the corresponding error code. */
  3219. result = paOutputUnderflowed;
  3220. }
  3221. } /* If this is not an output stream. */
  3222. else
  3223. {
  3224. result = paCanNotWriteToAnInputOnlyStream;
  3225. }
  3226. return result;
  3227. }
  3228. static signed long GetStreamReadAvailable( PaStream* s )
  3229. {
  3230. PaAsioStream *stream = (PaAsioStream*)s;
  3231. /* Call buffer utility routine to get the number of available frames. */
  3232. return PaUtil_GetRingBufferReadAvailable( &stream->blockingState->readRingBuffer );
  3233. }
  3234. static signed long GetStreamWriteAvailable( PaStream* s )
  3235. {
  3236. PaAsioStream *stream = (PaAsioStream*)s;
  3237. /* Call buffer utility routine to get the number of empty buffers. */
  3238. return PaUtil_GetRingBufferWriteAvailable( &stream->blockingState->writeRingBuffer );
  3239. }
  3240. /* This routine will be called by the PortAudio engine when audio is needed.
  3241. ** It may called at interrupt level on some machines so don't do anything
  3242. ** that could mess up the system like calling malloc() or free().
  3243. */
  3244. static int BlockingIoPaCallback(const void *inputBuffer ,
  3245. void *outputBuffer ,
  3246. unsigned long framesPerBuffer,
  3247. const PaStreamCallbackTimeInfo *timeInfo ,
  3248. PaStreamCallbackFlags statusFlags ,
  3249. void *userData )
  3250. {
  3251. PaError result = paNoError; /* Initial return value. */
  3252. PaAsioStream *stream = *(PaAsioStream**)userData; /* The PA ASIO stream. */
  3253. PaAsioStreamBlockingState *blockingState = stream->blockingState; /* Persume blockingState is valid, otherwise the callback wouldn't be running. */
  3254. /* Get a pointer to the stream's blocking i/o buffer processor. */
  3255. PaUtilBufferProcessor *pBp = &blockingState->bufferProcessor;
  3256. PaUtilRingBuffer *pRb = NULL;
  3257. /* If output data has been requested. */
  3258. if( stream->outputChannelCount )
  3259. {
  3260. /* If the callback input argument signalizes a output underflow,
  3261. make sure the WriteStream() function knows about it, too! */
  3262. if( statusFlags & paOutputUnderflowed ) {
  3263. blockingState->outputUnderflowFlag = TRUE;
  3264. }
  3265. /* Access the corresponding ring buffer. */
  3266. pRb = &blockingState->writeRingBuffer;
  3267. /* If the blocking i/o buffer contains enough output data, */
  3268. if( PaUtil_GetRingBufferReadAvailable(pRb) >= (long) framesPerBuffer )
  3269. {
  3270. /* Extract the requested data from the ring buffer. */
  3271. PaUtil_ReadRingBuffer( pRb, outputBuffer, framesPerBuffer );
  3272. }
  3273. else /* If no output data is available :-( */
  3274. {
  3275. /* Signalize a write-buffer underflow. */
  3276. blockingState->outputUnderflowFlag = TRUE;
  3277. /* Fill the output buffer with silence. */
  3278. (*pBp->outputZeroer)( outputBuffer, 1, pBp->outputChannelCount * framesPerBuffer );
  3279. /* If playback is to be stopped */
  3280. if( blockingState->stopFlag && PaUtil_GetRingBufferReadAvailable(pRb) < (long) framesPerBuffer )
  3281. {
  3282. /* Extract all the remaining data from the ring buffer,
  3283. whether it is a complete data block or not. */
  3284. PaUtil_ReadRingBuffer( pRb, outputBuffer, PaUtil_GetRingBufferReadAvailable(pRb) );
  3285. }
  3286. }
  3287. /* Set blocking i/o event? */
  3288. if( blockingState->writeBuffersRequestedFlag && PaUtil_GetRingBufferWriteAvailable(pRb) >= (long) blockingState->writeBuffersRequested )
  3289. {
  3290. /* Reset buffer request. */
  3291. blockingState->writeBuffersRequestedFlag = FALSE;
  3292. blockingState->writeBuffersRequested = 0;
  3293. /* Signalize that requested buffers are ready. */
  3294. SetEvent( blockingState->writeBuffersReadyEvent );
  3295. /* What do we do if SetEvent() returns zero, i.e. the event
  3296. could not be set? How to return errors from within the
  3297. callback? - S.Fischer */
  3298. }
  3299. }
  3300. /* If input data has been supplied. */
  3301. if( stream->inputChannelCount )
  3302. {
  3303. /* If the callback input argument signalizes a input overflow,
  3304. make sure the ReadStream() function knows about it, too! */
  3305. if( statusFlags & paInputOverflowed ) {
  3306. blockingState->inputOverflowFlag = TRUE;
  3307. }
  3308. /* Access the corresponding ring buffer. */
  3309. pRb = &blockingState->readRingBuffer;
  3310. /* If the blocking i/o buffer contains not enough input buffers */
  3311. if( PaUtil_GetRingBufferWriteAvailable(pRb) < (long) framesPerBuffer )
  3312. {
  3313. /* Signalize a read-buffer overflow. */
  3314. blockingState->inputOverflowFlag = TRUE;
  3315. /* Remove some old data frames from the buffer. */
  3316. PaUtil_AdvanceRingBufferReadIndex( pRb, framesPerBuffer );
  3317. }
  3318. /* Insert the current input data into the ring buffer. */
  3319. PaUtil_WriteRingBuffer( pRb, inputBuffer, framesPerBuffer );
  3320. /* Set blocking i/o event? */
  3321. if( blockingState->readFramesRequestedFlag && PaUtil_GetRingBufferReadAvailable(pRb) >= (long) blockingState->readFramesRequested )
  3322. {
  3323. /* Reset buffer request. */
  3324. blockingState->readFramesRequestedFlag = FALSE;
  3325. blockingState->readFramesRequested = 0;
  3326. /* Signalize that requested buffers are ready. */
  3327. SetEvent( blockingState->readFramesReadyEvent );
  3328. /* What do we do if SetEvent() returns zero, i.e. the event
  3329. could not be set? How to return errors from within the
  3330. callback? - S.Fischer */
  3331. /** @todo report an error with PA_DEBUG */
  3332. }
  3333. }
  3334. return paContinue;
  3335. }
  3336. PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific )
  3337. {
  3338. PaError result = paNoError;
  3339. PaUtilHostApiRepresentation *hostApi;
  3340. PaDeviceIndex hostApiDevice;
  3341. ASIODriverInfo asioDriverInfo;
  3342. ASIOError asioError;
  3343. int asioIsInitialized = 0;
  3344. PaAsioHostApiRepresentation *asioHostApi;
  3345. PaAsioDeviceInfo *asioDeviceInfo;
  3346. PaWinUtilComInitializationResult comInitializationResult;
  3347. /* initialize COM again here, we might be in another thread */
  3348. result = PaWinUtil_CoInitialize( paASIO, &comInitializationResult );
  3349. if( result != paNoError )
  3350. return result;
  3351. result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
  3352. if( result != paNoError )
  3353. goto error;
  3354. result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
  3355. if( result != paNoError )
  3356. goto error;
  3357. /*
  3358. In theory we could proceed if the currently open device was the same
  3359. one for which the control panel was requested, however because the
  3360. window pointer is not available until this function is called we
  3361. currently need to call ASIOInit() again here, which of course can't be
  3362. done safely while a stream is open.
  3363. */
  3364. asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
  3365. if( asioHostApi->openAsioDeviceIndex != paNoDevice )
  3366. {
  3367. result = paDeviceUnavailable;
  3368. goto error;
  3369. }
  3370. asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
  3371. if( !asioHostApi->asioDrivers->loadDriver( const_cast<char*>(asioDeviceInfo->commonDeviceInfo.name) ) )
  3372. {
  3373. result = paUnanticipatedHostError;
  3374. goto error;
  3375. }
  3376. /* CRUCIAL!!! */
  3377. memset( &asioDriverInfo, 0, sizeof(ASIODriverInfo) );
  3378. asioDriverInfo.asioVersion = 2;
  3379. asioDriverInfo.sysRef = systemSpecific;
  3380. asioError = ASIOInit( &asioDriverInfo );
  3381. if( asioError != ASE_OK )
  3382. {
  3383. result = paUnanticipatedHostError;
  3384. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  3385. goto error;
  3386. }
  3387. else
  3388. {
  3389. asioIsInitialized = 1;
  3390. }
  3391. PA_DEBUG(("PaAsio_ShowControlPanel: ASIOInit(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
  3392. PA_DEBUG(("asioVersion: ASIOInit(): %ld\n", asioDriverInfo.asioVersion ));
  3393. PA_DEBUG(("driverVersion: ASIOInit(): %ld\n", asioDriverInfo.driverVersion ));
  3394. PA_DEBUG(("Name: ASIOInit(): %s\n", asioDriverInfo.name ));
  3395. PA_DEBUG(("ErrorMessage: ASIOInit(): %s\n", asioDriverInfo.errorMessage ));
  3396. asioError = ASIOControlPanel();
  3397. if( asioError != ASE_OK )
  3398. {
  3399. PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
  3400. result = paUnanticipatedHostError;
  3401. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  3402. goto error;
  3403. }
  3404. PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
  3405. asioError = ASIOExit();
  3406. if( asioError != ASE_OK )
  3407. {
  3408. result = paUnanticipatedHostError;
  3409. PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
  3410. asioIsInitialized = 0;
  3411. goto error;
  3412. }
  3413. PA_DEBUG(("PaAsio_ShowControlPanel: ASIOExit(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
  3414. return result;
  3415. error:
  3416. if( asioIsInitialized )
  3417. {
  3418. ASIOExit();
  3419. }
  3420. PaWinUtil_CoUninitialize( paASIO, &comInitializationResult );
  3421. return result;
  3422. }
  3423. PaError PaAsio_GetInputChannelName( PaDeviceIndex device, int channelIndex,
  3424. const char** channelName )
  3425. {
  3426. PaError result = paNoError;
  3427. PaUtilHostApiRepresentation *hostApi;
  3428. PaDeviceIndex hostApiDevice;
  3429. PaAsioDeviceInfo *asioDeviceInfo;
  3430. result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
  3431. if( result != paNoError )
  3432. goto error;
  3433. result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
  3434. if( result != paNoError )
  3435. goto error;
  3436. asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
  3437. if( channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxInputChannels ){
  3438. result = paInvalidChannelCount;
  3439. goto error;
  3440. }
  3441. *channelName = asioDeviceInfo->asioChannelInfos[channelIndex].name;
  3442. return paNoError;
  3443. error:
  3444. return result;
  3445. }
  3446. PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex,
  3447. const char** channelName )
  3448. {
  3449. PaError result = paNoError;
  3450. PaUtilHostApiRepresentation *hostApi;
  3451. PaDeviceIndex hostApiDevice;
  3452. PaAsioDeviceInfo *asioDeviceInfo;
  3453. result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
  3454. if( result != paNoError )
  3455. goto error;
  3456. result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
  3457. if( result != paNoError )
  3458. goto error;
  3459. asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
  3460. if( channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxOutputChannels ){
  3461. result = paInvalidChannelCount;
  3462. goto error;
  3463. }
  3464. *channelName = asioDeviceInfo->asioChannelInfos[
  3465. asioDeviceInfo->commonDeviceInfo.maxInputChannels + channelIndex].name;
  3466. return paNoError;
  3467. error:
  3468. return result;
  3469. }
  3470. /* NOTE: the following functions are ASIO-stream specific, and are called directly
  3471. by client code. We need to check for many more error conditions here because
  3472. we don't have the benefit of pa_front.c's parameter checking.
  3473. */
  3474. static PaError GetAsioStreamPointer( PaAsioStream **stream, PaStream *s )
  3475. {
  3476. PaError result;
  3477. PaUtilHostApiRepresentation *hostApi;
  3478. PaAsioHostApiRepresentation *asioHostApi;
  3479. result = PaUtil_ValidateStreamPointer( s );
  3480. if( result != paNoError )
  3481. return result;
  3482. result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
  3483. if( result != paNoError )
  3484. return result;
  3485. asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
  3486. if( PA_STREAM_REP( s )->streamInterface == &asioHostApi->callbackStreamInterface
  3487. || PA_STREAM_REP( s )->streamInterface == &asioHostApi->blockingStreamInterface )
  3488. {
  3489. /* s is an ASIO stream */
  3490. *stream = (PaAsioStream *)s;
  3491. return paNoError;
  3492. }
  3493. else
  3494. {
  3495. return paIncompatibleStreamHostApi;
  3496. }
  3497. }
  3498. PaError PaAsio_SetStreamSampleRate( PaStream* s, double sampleRate )
  3499. {
  3500. PaAsioStream *stream;
  3501. PaError result = GetAsioStreamPointer( &stream, s );
  3502. if( result != paNoError )
  3503. return result;
  3504. if( stream != theAsioStream )
  3505. return paBadStreamPtr;
  3506. return ValidateAndSetSampleRate( sampleRate );
  3507. }