libcm is a C development framework with an emphasis on audio signal processing applications.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cmXScore.c 116KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130
  1. #include "cmPrefix.h"
  2. #include "cmGlobal.h"
  3. #include "cmFloatTypes.h"
  4. #include "cmComplexTypes.h"
  5. #include "cmRpt.h"
  6. #include "cmErr.h"
  7. #include "cmCtx.h"
  8. #include "cmMem.h"
  9. #include "cmMallocDebug.h"
  10. #include "cmLinkedHeap.h"
  11. #include "cmXml.h"
  12. #include "cmText.h"
  13. #include "cmFileSys.h"
  14. #include "cmXScore.h"
  15. #include "cmTime.h"
  16. #include "cmMidi.h"
  17. #include "cmMidiFile.h"
  18. #include "cmLex.h"
  19. #include "cmCsv.h"
  20. #include "cmSymTbl.h"
  21. #include "cmScore.h"
  22. #include "cmFile.h"
  23. #include "cmSymTbl.h"
  24. #include "cmAudioFile.h"
  25. #include "cmAudioFile.h"
  26. #include "cmProcObj.h"
  27. #include "cmProcTemplate.h"
  28. #include "cmProc.h"
  29. #include "cmProc2.h"
  30. #include "cmProc5.h"
  31. #include "cmSvgWriter.h"
  32. cmXsH_t cmXsNullHandle = cmSTATIC_NULL_HANDLE;
  33. enum
  34. {
  35. kSectionXsFl = 0x00000001, // rvalue holds section number
  36. kBarXsFl = 0x00000002,
  37. kRestXsFl = 0x00000004,
  38. kGraceXsFl = 0x00000008,
  39. kDotXsFl = 0x00000010,
  40. kChordXsFl = 0x00000020,
  41. kDynXsFl = 0x00000040,
  42. kEvenXsFl = 0x00000080,
  43. kTempoXsFl = 0x00000100,
  44. kHeelXsFl = 0x00000200,
  45. kTieBegXsFl = 0x00000400,
  46. kTieEndXsFl = 0x00000800,
  47. kTieProcXsFl = 0x00001000,
  48. kDampDnXsFl = 0x00002000,
  49. kDampUpXsFl = 0x00004000,
  50. kDampUpDnXsFl = 0x00008000,
  51. kSostDnXsFl = 0x00010000,
  52. kSostUpXsFl = 0x00020000,
  53. kMetronomeXsFl = 0x00040000, // duration holds BPM
  54. kOnsetXsFl = 0x00080000, // this is a sounding note
  55. kBegGroupXsFl = 0x00100000,
  56. kEndGroupXsFl = 0x00200000,
  57. kBegGraceXsFl = 0x00400000, // (b) beg grace note group
  58. kEndGraceXsFl = 0x00800000, // end grace note group
  59. kAddGraceXsFl = 0x01000000, // (a) end grace note group operator flag - add time
  60. kSubGraceXsFl = 0x02000000, // (s) " " " " " " - subtract time
  61. kAFirstGraceXsFl = 0x04000000, // (A) add time after first note
  62. kNFirstGraceXsFl = 0x08000000, // (n) grace notes start as soon as possible after first note and add time
  63. kDeleteXsFl = 0x10000000,
  64. kDynBegForkXsFl = 0x20000000,
  65. kDynEndForkXsFl = 0x40000000,
  66. kDynEndXsFl = 0x100000000,
  67. kEvenEndXsFl = 0x200000000,
  68. kTempoEndXsFl = 0x400000000
  69. };
  70. struct cmXsMeas_str;
  71. struct cmXsVoice_str;
  72. // Values measured for each sounding note in the preceding time window....
  73. typedef struct cmXsComplexity_str
  74. {
  75. unsigned sum_d_vel; // sum of first order difference of cmXsNote_t.dynamics
  76. unsigned sum_d_rym; // sum of first order difference of cmXsNote_t.rvalue
  77. unsigned sum_d_lpch; // sum of first order difference of cmXsNote_t.pitch of note assigned to the bass cleff
  78. unsigned sum_n_lpch; // count of notes assigned to the bass cleff
  79. unsigned sum_d_rpch; // sum of first order difference of cmXsNote_t.pitch of note assigned to the treble cleff
  80. unsigned sum_n_rpch; // count of notes assigned to the treble cleff
  81. } cmXsComplexity_t;
  82. typedef struct cmXsNote_str
  83. {
  84. unsigned uid; // unique id of this note record
  85. unsigned long long flags; // See k???XsFl
  86. unsigned pitch; // midi pitch
  87. unsigned dynamics; // dynamic level 1=pppp 9=fff
  88. unsigned vel; // score specified MIDI velocity
  89. cmChar_t step; // A-G
  90. unsigned octave; // sci pitch octave
  91. int alter; // +n=sharps,-n=flats
  92. unsigned staff; // 1=treble 2=bass
  93. unsigned tick; //
  94. unsigned duration; // duration in ticks
  95. unsigned tied_dur; // duration in ticks (including all tied notes)
  96. double secs; // absolute time in seconds
  97. double dsecs; // delta time in seconds since previous event
  98. unsigned locIdx; // location index (chords share the same location index)
  99. double rvalue; // 1/rvalue = rythmic value (1/0.5 double whole 1/1 whole 1/2 half 1/4=quarter note, 1/8=eighth note, ...)
  100. const cmChar_t* tvalue; // text value
  101. unsigned evenGroupId; // eveness group id
  102. unsigned dynGroupId; // dynamics group id
  103. unsigned tempoGroupId; // tempo group id
  104. unsigned graceGroupId; // grace note group id
  105. struct cmXsVoice_str* voice; // voice this note belongs to
  106. struct cmXsMeas_str* meas; // measure this note belongs to
  107. const cmXmlNode_t* xmlNode; // note xml ptr
  108. struct cmXsNote_str* tied; // subsequent note tied to this note
  109. struct cmXsNote_str* grace; // grace note groups link backward in time from the anchor note
  110. struct cmXsNote_str* mlink; // measure note list
  111. struct cmXsNote_str* slink; // time sorted event list
  112. cmXsComplexity_t cplx;
  113. } cmXsNote_t;
  114. typedef struct cmXsVoice_str
  115. {
  116. unsigned id; // Voice id
  117. cmXsNote_t* noteL; // List of notes in this voice
  118. struct cmXsVoice_str* link; // Link to other voices in this measure
  119. } cmXsVoice_t;
  120. typedef struct cmXsSpan_str
  121. {
  122. unsigned staff;
  123. unsigned number;
  124. struct cmXsMeas_str* meas;
  125. unsigned tick0;
  126. unsigned tick1;
  127. int pitch_offset;
  128. struct cmXsSpan_str* link;
  129. } cmXsSpan_t;
  130. typedef struct cmXsMeas_str
  131. {
  132. unsigned number; // Measure number
  133. unsigned divisions; // ticks-per-quarter-note
  134. unsigned beats; // beats per measure
  135. unsigned beat_type; // whole/half/quarter/eighth ...
  136. cmXsVoice_t* voiceL; // List of voices in this measure
  137. cmXsNote_t* noteL; // List of time sorted notes in this measure
  138. struct cmXsMeas_str* link; // Link to other measures in this part.
  139. } cmXsMeas_t;
  140. typedef struct cmXsPart_str
  141. {
  142. const cmChar_t* idStr; // Id of this part
  143. cmXsMeas_t* measL; // List of measures in this part.
  144. struct cmXsPart_str* link; // Link to other parts in this score
  145. } cmXsPart_t;
  146. typedef struct
  147. {
  148. cmErr_t err;
  149. cmXmlH_t xmlH;
  150. cmLHeapH_t lhH;
  151. cmXsPart_t* partL;
  152. cmCsvH_t csvH;
  153. cmXsSpan_t* spanL;
  154. unsigned nextUid;
  155. cmXsComplexity_t cplx_max;
  156. } cmXScore_t;
  157. void _cmXScoreReport( cmXScore_t* p, cmRpt_t* rpt, bool sortFl );
  158. cmXScore_t* _cmXScoreHandleToPtr( cmXsH_t h )
  159. {
  160. cmXScore_t* p = (cmXScore_t*)h.h;
  161. assert( p != NULL );
  162. return p;
  163. }
  164. cmXsRC_t _cmXScoreFinalize( cmXScore_t* p )
  165. {
  166. cmXsRC_t rc = kOkXsRC;
  167. // release the XML file
  168. cmXmlFree( &p->xmlH );
  169. // release the local linked heap memory
  170. cmLHeapDestroy(&p->lhH);
  171. // release the CSV output object
  172. cmCsvFinalize(&p->csvH);
  173. cmMemFree(p);
  174. return rc;
  175. }
  176. cmXsRC_t _cmXScoreMissingNode( cmXScore_t* p, const cmXmlNode_t* parent, const cmChar_t* label )
  177. {
  178. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Missing XML node '%s'. Parent line:%i",label,parent->line);
  179. }
  180. cmXsRC_t _cmXScoreMissingAttribute( cmXScore_t* p, const cmXmlNode_t* np, const cmChar_t* attrLabel )
  181. {
  182. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Missing XML attribute '%s' from node '%s'.",attrLabel,np->label);
  183. }
  184. cmXsVoice_t* _cmXScoreIdToVoice( cmXsMeas_t* meas, unsigned voiceId )
  185. {
  186. cmXsVoice_t* v = meas->voiceL;
  187. for(; v!=NULL; v=v->link)
  188. if( v->id == voiceId )
  189. return v;
  190. return NULL;
  191. }
  192. cmXsRC_t _cmXScorePushNote( cmXScore_t* p, cmXsMeas_t* meas, unsigned voiceId, cmXsNote_t* note )
  193. {
  194. cmXsVoice_t* v;
  195. // get the voice recd
  196. if((v = _cmXScoreIdToVoice(meas,voiceId)) == NULL)
  197. {
  198. // the voice recd doesn't exist for this voiceId - allocate one
  199. v = cmLhAllocZ(p->lhH,cmXsVoice_t,1);
  200. v->id = voiceId;
  201. // add the voice record to the meas->voiceL
  202. if( meas->voiceL == NULL )
  203. meas->voiceL = v;
  204. else
  205. {
  206. cmXsVoice_t* vp = meas->voiceL;
  207. while( vp->link!=NULL )
  208. vp = vp->link;
  209. vp->link = v;
  210. }
  211. }
  212. // add the note record to the end of meas->voiceL
  213. if( v->noteL == NULL )
  214. v->noteL = note;
  215. else
  216. {
  217. cmXsNote_t* n = v->noteL;
  218. while( n->mlink != NULL )
  219. n = n->mlink;
  220. n->mlink = note;
  221. }
  222. note->voice = v;
  223. note->uid = p->nextUid++;
  224. note->tied_dur = note->duration;
  225. return kOkXsRC;
  226. }
  227. cmXsRC_t _cmXScoreRemoveNote( cmXsNote_t* note )
  228. {
  229. cmXsNote_t* n0 = NULL;
  230. cmXsNote_t* n1 = note->voice->noteL;
  231. unsigned cnt = 0;
  232. for(; n1!=NULL; n1=n1->mlink)
  233. {
  234. if( n1->uid == note->uid )
  235. {
  236. if( n0 == NULL )
  237. note->voice->noteL = NULL;
  238. else
  239. n0->mlink = n1->mlink;
  240. cnt = 1;
  241. break;
  242. }
  243. n0 = n1;
  244. }
  245. n0 = NULL;
  246. n1 = note->meas->noteL;
  247. for(; n1!=NULL; n1=n1->slink)
  248. {
  249. if( n1->uid == note->uid )
  250. {
  251. if( n0 == NULL )
  252. note->voice->noteL = NULL;
  253. else
  254. n0->slink = n1->slink;
  255. cnt = 2;
  256. break;
  257. }
  258. n0 = n1;
  259. }
  260. return cnt == 2 ? kOkXsRC : kSyntaxErrorXsRC;
  261. }
  262. void _cmXScoreInsertNoteBefore( cmXsNote_t* note, cmXsNote_t* nn )
  263. {
  264. assert( note != NULL );
  265. // insert the new note into the voice list before 'note'
  266. cmXsNote_t* n0 = NULL;
  267. cmXsNote_t* n1 = note->voice->noteL;
  268. for(; n1 != NULL; n1=n1->mlink )
  269. {
  270. if( n1->uid == note->uid )
  271. {
  272. if( n0 == NULL )
  273. note->voice->noteL = nn;
  274. else
  275. n0->mlink = nn;
  276. nn->mlink = note;
  277. break;
  278. }
  279. n0 = n1;
  280. }
  281. assert( n1 != NULL );
  282. // insert the new note into the time sorted note list before 'note'
  283. n0 = NULL;
  284. n1 = note->meas->noteL;
  285. for(; n1!=NULL; n1=n1->slink)
  286. {
  287. if( n1->tick >= nn->tick )
  288. {
  289. if( n0 == NULL )
  290. note->meas->noteL = nn;
  291. else
  292. n0->slink = nn;
  293. nn->slink = n1;
  294. break;
  295. }
  296. n0 = n1;
  297. }
  298. assert( n1 != NULL );
  299. }
  300. void _cmXScoreInsertNoteAfter( cmXsNote_t* note, cmXsNote_t* nn )
  301. {
  302. // insert the new note into the voice list after 'note'
  303. cmXsNote_t* n0 = note->voice->noteL;
  304. for(; n0 != NULL; n0=n0->mlink )
  305. if( n0->uid == note->uid )
  306. {
  307. nn->mlink = note->mlink;
  308. note->mlink = nn;
  309. break;
  310. }
  311. assert(n0 != NULL );
  312. // insert the new note into the time sorted note list after 'note'
  313. n0 = note->meas->noteL;
  314. for(; n0!=NULL; n0=n0->slink)
  315. {
  316. if( n0->tick >= nn->tick )
  317. {
  318. nn->slink = n0->slink;
  319. n0->slink = nn;
  320. break;
  321. }
  322. // if n0 is the last ele in the list
  323. if( n0->slink == NULL )
  324. {
  325. n0->slink = nn;
  326. nn->slink = NULL;
  327. break;
  328. }
  329. }
  330. assert(n0 != NULL);
  331. }
  332. cmXsRC_t _cmXScoreParsePartList( cmXScore_t* p )
  333. {
  334. cmXsRC_t rc = kOkXsRC;
  335. cmXsPart_t* lastPartPtr = NULL;
  336. const cmXmlNode_t* xnp;
  337. // find the 'part-list'
  338. if((xnp = cmXmlSearch( cmXmlRoot(p->xmlH), "part-list", NULL, 0)) == NULL )
  339. return _cmXScoreMissingNode(p,cmXmlRoot(p->xmlH),"part-list");
  340. const cmXmlNode_t* cnp = xnp->children;
  341. // for each child of the 'part-list'
  342. for(; cnp!=NULL; cnp=cnp->sibling)
  343. if( cmTextCmp( cnp->label, "score-part" ) == 0 )
  344. {
  345. const cmXmlAttr_t* a;
  346. // find the 'score-part' id
  347. if((a = cmXmlFindAttrib(cnp,"id")) == NULL )
  348. return _cmXScoreMissingAttribute(p,cnp,"id");
  349. // allocate a new part record
  350. cmXsPart_t* pp = cmLhAllocZ(p->lhH,cmXsPart_t,1);
  351. pp->idStr = a->value; // set the part id
  352. // link the new part record to the end of the part list
  353. if(lastPartPtr == NULL)
  354. p->partL = pp;
  355. else
  356. lastPartPtr->link = pp;
  357. lastPartPtr = pp;
  358. }
  359. return rc;
  360. }
  361. cmXsRC_t _cmXScoreParsePitch( cmXScore_t* p, const cmXmlNode_t* nnp, cmXsNote_t* np )
  362. {
  363. cmXsRC_t rc = kOkXsRC;
  364. unsigned octave = 0;
  365. double alter = 0;
  366. const cmChar_t* step = NULL;
  367. if((step = cmXmlNodeValue(nnp,"pitch","step",NULL)) == NULL )
  368. return _cmXScoreMissingNode(p,nnp,"step");
  369. if((rc = cmXmlNodeUInt( nnp,&octave,"pitch","octave",NULL)) != kOkXmlRC )
  370. return _cmXScoreMissingNode(p,nnp,"octave");
  371. cmXmlNodeDouble( nnp,&alter,"pitch","alter",NULL);
  372. int acc = alter;
  373. unsigned midi = cmSciPitchToMidiPitch(*step,acc,octave);
  374. np->pitch = midi;
  375. np->step = *step;
  376. np->octave = octave;
  377. np->alter = alter;
  378. np->flags |= kOnsetXsFl;
  379. return rc;
  380. }
  381. cmXsRC_t _cmXScoreParseNoteRValue( cmXScore_t* p, const cmXmlNode_t* nnp, const cmChar_t* label, double* rvalueRef )
  382. {
  383. typedef struct map_str
  384. {
  385. double rvalue;
  386. const cmChar_t* label;
  387. } map_t;
  388. map_t mapV[] =
  389. {
  390. {-1.0, "measure" }, // whole measure rest
  391. { 0.5, "breve" }, // double whole
  392. { 1.0, "whole" },
  393. { 2.0, "half" },
  394. { 4.0, "quarter" },
  395. { 8.0, "eighth" },
  396. {16.0, "16th" },
  397. {32.0, "32nd" },
  398. { 64.0, "64th" },
  399. {128.0, "128th" },
  400. { 0.0, "" }
  401. };
  402. const cmChar_t* str;
  403. // get the XML rvalue label
  404. if((str = cmXmlNodeValue(nnp,label,NULL)) == NULL)
  405. {
  406. if((nnp = cmXmlSearch(nnp,"rest",NULL,0)) != NULL )
  407. {
  408. const cmXmlAttr_t* a;
  409. if((a = cmXmlFindAttrib(nnp,"measure")) != NULL && cmTextCmp(a->value,"yes")==0)
  410. {
  411. *rvalueRef = -1;
  412. return kOkXsRC;
  413. }
  414. }
  415. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"The 'beat-unit' metronome value is missing on line %i.",nnp->line);
  416. }
  417. unsigned i;
  418. // lookup the rvalue numeric value from the mapV[] table
  419. for(i=0; mapV[i].rvalue!=0; ++i)
  420. if( cmTextCmp(mapV[i].label,str) == 0 )
  421. {
  422. *rvalueRef = mapV[i].rvalue;
  423. return kOkXsRC;
  424. }
  425. // the rvalue label was not found
  426. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unknown rvalue type='%s'.",str);
  427. }
  428. cmXsRC_t _cmXScoreParseColor( cmXScore_t* p, const cmXmlNode_t* nnp, cmXsNote_t* note )
  429. {
  430. cmXsRC_t rc = kOkXsRC;
  431. const cmXmlAttr_t* a;
  432. typedef struct map_str
  433. {
  434. unsigned long long value;
  435. const cmChar_t* label;
  436. } map_t;
  437. map_t mapV[] =
  438. {
  439. { kEvenXsFl, "#0000FF" }, // blue (even)
  440. { kEvenXsFl | kEvenEndXsFl, "#0000FE" }, // blue (even end)
  441. { kEvenXsFl | kEvenEndXsFl, "#0000FD" }, // blue (even end)
  442. { kTempoXsFl, "#00FF00" }, // green (tempo)
  443. { kTempoXsFl | kTempoEndXsFl, "#00FE00" }, // green (tempo end)
  444. { kDynXsFl, "#FF0000" }, // red (dynamics)
  445. { kDynXsFl | kDynEndXsFl, "#FE0000" }, // red (dynamics end)
  446. { kDynXsFl | kDynEndXsFl, "#FD0000" }, // red (dynamics end)
  447. { kTempoXsFl | kEvenXsFl, "#00FFFF" }, // green + blue (turquoise)
  448. { kTempoXsFl | kEvenXsFl | kEvenEndXsFl, "#00FFFE" }, // green + blue (turquoise) (end)
  449. { kDynXsFl | kEvenXsFl, "#FF00FF" }, // red + blue
  450. { kDynXsFl | kEvenXsFl | kEvenEndXsFl, "#FF00FE" }, // red + blue (end)
  451. { kDynXsFl | kEvenXsFl | kEvenEndXsFl, "#FF00FD" }, // red + blue (end)
  452. { kDynXsFl | kEvenXsFl, "#FF0CF7" }, // magenta (even+dyn)
  453. { kDynXsFl | kTempoXsFl, "#FF7F00" }, // red + green (brown)
  454. { kDynXsFl | kTempoXsFl, "#FE7F00" }, // red + green (brown) (end)
  455. { kDynXsFl | kTempoXsFl, "#FD7F00" }, // red + green (brown) (end)
  456. { kDynXsFl | kTempoXsFl | kTempoEndXsFl, "#FF7E00" }, //
  457. { kDynXsFl | kDynEndXsFl | kEvenXsFl | kEvenEndXsFl, "#FE00FE" }, //
  458. { kDynXsFl | kDynEndXsFl | kEvenXsFl, "#FE00FF" },
  459. { kTempoXsFl | kEvenXsFl | kDynXsFl, "#996633" }, // (purple)
  460. { kTempoXsFl | kEvenXsFl | kDynXsFl | kDynEndXsFl, "#996632" }, // (purple)
  461. { kDynXsFl, "#FF6A03" }, // 176 orange (dynamics)
  462. { kEvenXsFl, "#2F00E8" }, // 1001 blue (even)
  463. { kTempoXsFl, "#01CD1F" }, // 1196 green (tempo)
  464. { kEvenXsFl, "#3600E8" }, // 1627 blue (even)
  465. { kDynXsFl | kTempoXsFl, "#9E8F15" }, // 8827 brown (dyn + tempo)
  466. { kEvenXsFl, "#2E00E6" }, // 5393 blue (even)
  467. { kEvenXsFl, "#2C00DD" }, // 5895 blue (even)
  468. { kDynXsFl, "#FF5B03" }, // 6498 orange (dyn)
  469. { kDynXsFl, "#FF6104" }, // 6896 orange
  470. { kEvenXsFl, "#2A00E6" }, // 7781 blue
  471. { kEvenXsFl, "#2300DD" }, // 8300 blue (even)
  472. { kTempoXsFl, "#03CD22" }, // 10820 green (tempo)
  473. { kEvenXsFl, "#3400DB" }, // 11627 blue (dyn)
  474. { -1, "" }
  475. };
  476. /*
  477. orange #FF6A03
  478. magenta #FF0CF7
  479. blue #2F00E8
  480. green #01CD1F
  481. gold #9E8F15
  482. green #03CD22
  483. */
  484. if((a = cmXmlFindAttrib(nnp, "color" )) != NULL )
  485. {
  486. unsigned i;
  487. for(i=0; mapV[i].value != -1; ++i)
  488. if( cmTextCmp(a->value,mapV[i].label) == 0 )
  489. {
  490. note->flags += mapV[i].value;
  491. break;
  492. }
  493. if( mapV[i].value == -1 )
  494. cmErrMsg(&p->err,kSyntaxErrorXsRC,"The note color '%s' was not found on line %i.",a->value,nnp->line);
  495. }
  496. return rc;
  497. }
  498. // On input tick0Ref is set to the tick of the previous event.
  499. // On input tickRef is set to the tick of this event.
  500. // On output tick0Ref is set to the tick of this event.
  501. // On output tickRef is set to the tick of the next event.
  502. cmXsRC_t _cmXScoreParseNote(cmXScore_t* p, cmXsMeas_t* meas, const cmXmlNode_t* nnp, unsigned* tick0Ref, unsigned* tickRef )
  503. {
  504. cmXsRC_t rc = kOkXsRC;
  505. cmXsNote_t* note = cmLhAllocZ(p->lhH,cmXsNote_t,1);
  506. unsigned voiceId;
  507. note->meas = meas;
  508. note->xmlNode = nnp;
  509. // get the voice id for this node
  510. if( cmXmlNodeUInt(nnp,&voiceId,"voice",NULL) != kOkXmlRC )
  511. return _cmXScoreMissingNode(p,nnp,"voice");
  512. // if this note has a pitch
  513. if( cmXmlNodeHasChild(nnp,"pitch",NULL) )
  514. if((rc = _cmXScoreParsePitch(p,nnp,note)) != kOkXsRC )
  515. return rc;
  516. cmXmlNodeUInt(nnp,&note->duration,"duration",NULL); // get the note duration
  517. cmXmlNodeUInt(nnp,&note->staff,"staff",NULL); // get th staff number
  518. // is 'rest'
  519. if( cmXmlNodeHasChild(nnp,"rest",NULL) )
  520. note->flags |= kRestXsFl;
  521. // is 'grace'
  522. if( cmXmlNodeHasChild(nnp,"grace",NULL) )
  523. note->flags |= kGraceXsFl;
  524. // is 'dot'
  525. if( cmXmlNodeHasChild(nnp,"dot",NULL) )
  526. note->flags |= kDotXsFl;
  527. // is 'chord'
  528. if( cmXmlNodeHasChild(nnp,"chord",NULL) )
  529. note->flags |= kChordXsFl;
  530. // is this is first note in a tied pair
  531. if( cmXmlNodeHasChildWithAttrAndValue(nnp,"tie","type","start",NULL) )
  532. note->flags |= kTieBegXsFl;
  533. // is this is second note in a tied pair
  534. if( cmXmlNodeHasChildWithAttrAndValue(nnp,"tie","type","stop",NULL) )
  535. note->flags |= kTieEndXsFl;
  536. // has 'heel' mark
  537. if( cmXmlNodeHasChild(nnp,"notations","technical","heel",NULL) )
  538. note->flags |= kHeelXsFl;
  539. // set color coded flags
  540. if((rc = _cmXScoreParseColor(p, nnp, note )) != kOkXsRC )
  541. return rc;
  542. // get the note's rythmic value
  543. if((rc = _cmXScoreParseNoteRValue(p,nnp,"type",&note->rvalue)) != kOkXsRC )
  544. return rc;
  545. // if this is a chord note
  546. if( cmIsFlag(note->flags,kChordXsFl) )
  547. {
  548. note->tick = *tick0Ref; // then use the onset time from the previous note and do not advance time
  549. }
  550. else
  551. {
  552. *tick0Ref = *tickRef;
  553. note->tick = *tickRef;
  554. *tickRef += note->duration;
  555. }
  556. return _cmXScorePushNote(p, meas, voiceId, note );
  557. }
  558. cmXsRC_t _cmXScorePushNonNote( cmXScore_t* p, cmXsMeas_t* meas, const cmXmlNode_t* noteXmlNode, unsigned tick, unsigned duration, double rvalue, const cmChar_t* tvalue, unsigned flags )
  559. {
  560. cmXsNote_t* note = cmLhAllocZ(p->lhH,cmXsNote_t,1);
  561. unsigned voiceId = 0; // non-note's are always assigned to voiceId=0;
  562. note->tick = tick;
  563. note->flags = flags;
  564. note->rvalue = rvalue;
  565. note->tvalue = tvalue;
  566. note->duration = duration;
  567. note->tied_dur = duration;
  568. note->meas = meas;
  569. note->xmlNode = noteXmlNode;
  570. return _cmXScorePushNote(p, meas, voiceId, note );
  571. }
  572. cmXsSpan_t* _cmXScoreFindOpenOctaveShift( cmXScore_t* p, unsigned staff, unsigned number )
  573. {
  574. cmXsSpan_t* s = p->spanL;
  575. for(; s!=NULL; s=s->link)
  576. if( s->tick1 == -1 && s->staff == staff && s->number == number )
  577. return s;
  578. return NULL;
  579. }
  580. cmXsRC_t _cmXScorePushOctaveShift(cmXScore_t* p, cmXsMeas_t* meas, unsigned staff, unsigned span_number, const cmChar_t* type_str, unsigned tick)
  581. {
  582. assert( meas != NULL);
  583. cmXsSpan_t* s;
  584. if( cmTextCmp(type_str,"stop") == 0 )
  585. {
  586. if((s = _cmXScoreFindOpenOctaveShift(p,staff,span_number)) == NULL )
  587. return cmErrWarnMsg(&p->err,kUnterminatedOctaveShiftXsrRC,"An illegal octave shift was encounted in meas %i.\n",meas->number);
  588. s->tick1 = tick;
  589. }
  590. else
  591. {
  592. s = cmLhAllocZ(p->lhH,cmXsSpan_t,1);
  593. s->staff = staff;
  594. s->meas = meas;
  595. s->number = span_number;
  596. s->tick0 = tick;
  597. s->tick1 = -1;
  598. s->pitch_offset = cmTextCmp(type_str,"up")==0 ? -12 : 12;
  599. s->link = p->spanL;
  600. p->spanL = s;
  601. }
  602. return kOkXsRC;
  603. }
  604. cmXsRC_t _cmXScoreParseDirection(cmXScore_t* p, cmXsMeas_t* meas, const cmXmlNode_t* dnp, unsigned tick)
  605. {
  606. cmXsRC_t rc = kOkXsRC;
  607. const cmXmlNode_t* np = NULL;
  608. const cmXmlAttr_t* a = NULL;
  609. unsigned flags = 0;
  610. int offset = 0;
  611. double rvalue = 0;
  612. const cmChar_t* tvalue = NULL;
  613. unsigned duration = 0;
  614. bool pushFl = true;
  615. unsigned staff = 0;
  616. cmXmlNodeInt( dnp, &offset, "offset", NULL );
  617. cmXmlNodeUInt(dnp, &staff, "staff", NULL );
  618. // if this is a metronome direction
  619. if((np = cmXmlSearch( dnp, "metronome", NULL, 0)) != NULL )
  620. {
  621. if( cmXmlNodeUInt(np,&duration,"per-minute",NULL) != kOkXmlRC )
  622. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"The 'per-minute' metronome value is missing on line %i.",np->line);
  623. if((rc = _cmXScoreParseNoteRValue(p,np,"beat-unit",&rvalue)) != kOkXsRC )
  624. return rc;
  625. flags = kMetronomeXsFl;
  626. }
  627. else
  628. // if this is a pedal direction
  629. if((np = cmXmlSearch( dnp, "pedal",NULL,0)) != NULL )
  630. {
  631. if((a = cmXmlFindAttrib(np,"type")) == NULL )
  632. return _cmXScoreMissingAttribute(p, np, "type" );
  633. if( cmTextCmp(a->value,"start") == 0 )
  634. flags = kDampDnXsFl;
  635. else
  636. if( cmTextCmp(a->value,"change") == 0 )
  637. flags = kDampUpDnXsFl;
  638. else
  639. if( cmTextCmp(a->value,"stop") == 0 )
  640. flags = kDampUpXsFl;
  641. else
  642. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unrecognized pedal type:'%s'.",cmStringNullGuard(a->value));
  643. }
  644. else
  645. // if this is a 'words' direction
  646. if((np = cmXmlSearch( dnp, "words", NULL, 0)) != NULL )
  647. {
  648. if((a = cmXmlFindAttrib(np,"enclosure")) != NULL && cmTextCmp(a->value,"rectangle")==0 )
  649. {
  650. if( cmTextIsEmpty( tvalue = np->dataStr ) )
  651. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Section number is blank or missing on line %i.",np->line);
  652. flags = kSectionXsFl;
  653. }
  654. }
  655. else
  656. // if this is an 'octave-shift' direction
  657. if((np = cmXmlSearch( dnp, "octave-shift", NULL, 0)) != NULL )
  658. {
  659. unsigned span_number = -1;
  660. if( cmXmlAttrUInt(np,"number",&span_number) != kOkXmlRC )
  661. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Octave-shift is missing a 'number' attribute.");
  662. if((a = cmXmlFindAttrib(np,"type")) == NULL)
  663. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Octave-shift is missing a 'type' attribute.");
  664. rc = _cmXScorePushOctaveShift(p,meas,staff,span_number,a->value,tick+offset);
  665. pushFl = false;
  666. }
  667. else
  668. {
  669. pushFl = false;
  670. }
  671. if( pushFl )
  672. rc = _cmXScorePushNonNote(p,meas,dnp,tick+offset,duration,rvalue,tvalue,flags);
  673. return rc;
  674. }
  675. // On input tickRef is set to the absolute tick of the bar line and on output it is set
  676. // to the absolute tick of the next bar line.
  677. cmXsRC_t _cmXScoreParseMeasure(cmXScore_t* p, cmXsPart_t* pp, const cmXmlNode_t* mnp, unsigned* tickRef)
  678. {
  679. cmXsRC_t rc = kOkXsRC;
  680. const cmXmlNode_t* np = NULL;
  681. unsigned tick = *tickRef;
  682. unsigned tick0= 0;
  683. cmXsMeas_t* m = NULL;
  684. // allocate the 'measure' record
  685. cmXsMeas_t* meas = cmLhAllocZ(p->lhH,cmXsMeas_t,1);
  686. // get measure number
  687. if( cmXmlAttrUInt(mnp,"number", &meas->number) != kOkXmlRC )
  688. return _cmXScoreMissingAttribute(p,mnp,"number");
  689. if( pp->measL == NULL )
  690. pp->measL = meas;
  691. else
  692. {
  693. m = pp->measL;
  694. while( m->link != NULL )
  695. m = m->link;
  696. m->link = meas;
  697. meas->divisions = m->divisions;
  698. meas->beats = m->beats;
  699. meas->beat_type = m->beat_type;
  700. }
  701. // get measure attributes node
  702. if((np = cmXmlSearch(mnp,"attributes",NULL,0)) != NULL)
  703. {
  704. cmXmlNodeUInt(np,&meas->divisions,"divisions",NULL);
  705. cmXmlNodeUInt(np,&meas->beats, "time","beats",NULL);
  706. cmXmlNodeUInt(np,&meas->beat_type,"time","beat-type",NULL);
  707. }
  708. // store the bar line
  709. if((rc = _cmXScorePushNonNote(p,meas,mnp,tick,0,0,NULL,kBarXsFl)) != kOkXsRC )
  710. return rc;
  711. np = mnp->children;
  712. // for each child of the 'meas' XML node
  713. for(; rc==kOkXsRC && np!=NULL; np=np->sibling)
  714. {
  715. // if this is a 'note' node
  716. if( cmTextCmp(np->label,"note") == 0 )
  717. {
  718. rc = _cmXScoreParseNote(p,meas,np,&tick0,&tick);
  719. }
  720. else
  721. // if this is a 'backup' node
  722. if( cmTextCmp(np->label,"backup") == 0 )
  723. {
  724. unsigned backup;
  725. cmXmlNodeUInt(np,&backup,"duration",NULL);
  726. if( backup > tick )
  727. tick = 0;
  728. else
  729. tick -= backup;
  730. tick0 = tick;
  731. }
  732. else
  733. // if this is a 'direction' node
  734. if( cmTextCmp(np->label,"direction") == 0 )
  735. {
  736. rc = _cmXScoreParseDirection(p,meas,np,tick);
  737. }
  738. }
  739. *tickRef = tick;
  740. return rc;
  741. }
  742. cmXsRC_t _cmXScoreParsePart( cmXScore_t* p, cmXsPart_t* pp )
  743. {
  744. cmXsRC_t rc = kOkXsRC;
  745. const cmXmlNode_t* xnp;
  746. cmXmlAttr_t partAttr = { "id", pp->idStr };
  747. unsigned barTick = 0;
  748. // find the 'part'
  749. if((xnp = cmXmlSearch( cmXmlRoot(p->xmlH), "part", &partAttr, 1)) == NULL )
  750. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"The part '%s' was not found.",pp->idStr);
  751. // for each child of this part - find each measure
  752. const cmXmlNode_t* cnp = xnp->children;
  753. for(; cnp!=NULL; cnp=cnp->sibling)
  754. if( cmTextCmp(cnp->label,"measure") == 0 )
  755. if((rc = _cmXScoreParseMeasure(p,pp,cnp,&barTick)) != kOkXsRC )
  756. return rc;
  757. return rc;
  758. }
  759. // Insert note 'np' into the sorted note list based at 's0'.
  760. // Return a pointer to the base of the list after the insertion.
  761. cmXsNote_t* _cmXScoreInsertSortedNote( cmXsNote_t* s0, cmXsNote_t* np )
  762. {
  763. assert( np != NULL );
  764. // np->slink is not NULL if the list is being resorted
  765. np->slink = NULL;
  766. // this list is empty so np is the first element on the list
  767. if( s0 == NULL )
  768. return np;
  769. // np is before the first element on the list
  770. if( np->tick < s0->tick )
  771. {
  772. np->slink = s0;
  773. return np;
  774. }
  775. cmXsNote_t* s1 = s0;
  776. cmXsNote_t* s2 = s0->slink;
  777. while( s2 != NULL )
  778. {
  779. if( s2->tick > np->tick )
  780. {
  781. s1->slink = np;
  782. np->slink = s2;
  783. return s0;
  784. }
  785. s1 = s2;
  786. s2 = s2->slink;
  787. }
  788. s1->slink = np;
  789. return s0;
  790. }
  791. // Set the cmXsNode_t.secs and dsecs.
  792. void _cmXScoreSetAbsoluteTime( cmXScore_t* p )
  793. {
  794. double tpqn = 0; // ticks per quarter note
  795. double tps = 0; // ticks per second
  796. unsigned metro_tick = 0;
  797. double metro_sec = 0;
  798. double sec0 = 0;
  799. cmXsPart_t* pp = p->partL;
  800. for(; pp!=NULL; pp=pp->link)
  801. {
  802. cmXsMeas_t* mp = pp->measL;
  803. for(; mp!=NULL; mp=mp->link)
  804. {
  805. if( mp->divisions != 0 )
  806. tpqn = mp->divisions;
  807. cmXsNote_t* np = mp->noteL;
  808. for(; np!=NULL; np=np->slink)
  809. {
  810. // Seconds are calculated as:
  811. // dticks = np->tick - metro_tick; // where metro_tick is the absolute tick of the last metro event
  812. // secs = (dticks/tps) + metro_secs; // where metro_secs is the absoute time of the last metro event
  813. unsigned dticks = np->tick - metro_tick;
  814. double secs = tps==0 ? 0 : (dticks/tps) + metro_sec;
  815. double dsecs = secs - sec0;
  816. //
  817. if( cmIsFlag(np->flags,kMetronomeXsFl) )
  818. {
  819. double bpm = np->duration; // beats per minute
  820. double bps = bpm / 60.0; // beats per second
  821. tps = bps * tpqn; // ticks per second
  822. metro_tick = np->tick; // store tick of the last metronome marker
  823. metro_sec = secs; // store time of the last metronome marker
  824. }
  825. if( cmIsFlag(np->flags,kBarXsFl|kDampDnXsFl|kDampUpXsFl|kDampUpDnXsFl|kSostDnXsFl|kSostUpXsFl|kOnsetXsFl|kSectionXsFl) )
  826. {
  827. np->secs = secs;
  828. np->dsecs = dsecs;
  829. sec0 = secs;
  830. }
  831. }
  832. }
  833. }
  834. }
  835. void _cmXScoreSort( cmXScore_t* p )
  836. {
  837. // for each part
  838. cmXsPart_t* pp = p->partL;
  839. for(; pp!=NULL; pp=pp->link)
  840. {
  841. // for each measure in this part
  842. cmXsMeas_t* mp = pp->measL;
  843. for(; mp!=NULL; mp=mp->link)
  844. {
  845. // explicitely set noteL to NULL to in case we are re-sorting
  846. mp->noteL = NULL;
  847. // for each voice in this measure
  848. cmXsVoice_t* vp = mp->voiceL;
  849. for(; vp!=NULL; vp=vp->link)
  850. {
  851. // for each note in this measure
  852. cmXsNote_t* np = vp->noteL;
  853. for(; np!=NULL; np=np->mlink)
  854. mp->noteL = _cmXScoreInsertSortedNote(mp->noteL,np);
  855. }
  856. }
  857. }
  858. // The order of events may have changed update the absolute time.
  859. _cmXScoreSetAbsoluteTime( p );
  860. }
  861. // All notes in a[aN] are on the same tick
  862. unsigned _cmXsSpreadGraceNotes( cmXsNote_t** a, unsigned aN )
  863. {
  864. unsigned i;
  865. bool barFl = false;
  866. // set barFl to true if a bar marker is included in the notes
  867. for(i=0; i<aN; ++i)
  868. if( cmIsFlag(a[i]->flags,kBarXsFl) )
  869. barFl = true;
  870. // spread any grace notes by one tick
  871. unsigned nextGraceTick = UINT_MAX;
  872. for(i=0; i<aN; ++i)
  873. if( cmIsFlag(a[i]->flags,kGraceXsFl) )
  874. {
  875. if( nextGraceTick == UINT_MAX )
  876. nextGraceTick = a[i]->tick + 1;
  877. else
  878. {
  879. a[i]->tick = nextGraceTick;
  880. nextGraceTick += 1;
  881. }
  882. }
  883. // if this tick group includes the bar ...
  884. if( barFl && nextGraceTick != UINT_MAX )
  885. {
  886. // ... then move all non-grace note events (except the bar marker) after
  887. // the grace notes
  888. for(i=0; i<aN; ++i)
  889. if( cmIsNotFlag(a[i]->flags,kGraceXsFl) && cmIsNotFlag(a[i]->flags,kBarXsFl) )
  890. a[i]->tick = nextGraceTick;
  891. }
  892. return nextGraceTick==UINT_MAX ? 0 : nextGraceTick;
  893. }
  894. void _cmXScoreSpreadGraceNotes( cmXScore_t* p )
  895. {
  896. cmXsPart_t* pp = p->partL;
  897. for(; pp!=NULL; pp=pp->link)
  898. {
  899. // tick1 is the location of the minimum current tick
  900. // (or 0 if it should be ignored)
  901. unsigned tick1 = 0;
  902. cmXsMeas_t* mp = pp->measL;
  903. for(; mp!=NULL; mp=mp->link)
  904. {
  905. cmXsNote_t* np = mp->noteL;
  906. unsigned aN = 128;
  907. cmXsNote_t* a[ aN ];
  908. unsigned ai = 0;
  909. // The first event in a measure may have been forced ahead
  910. // by spreading at the end of the previous measure
  911. if( tick1 > np->tick )
  912. np->tick = tick1;
  913. else
  914. tick1 = 0;
  915. // tick0 is the tick of the current tick group we are examining
  916. // A tick group is a group of events that share the same tick.
  917. unsigned tick0 = np->tick;
  918. // for each note
  919. for(; np!=NULL; np=np->slink)
  920. {
  921. // if this event is the first of a new tick group (then a[] holds a group completed on the previous note)
  922. if( np->tick != tick0 )
  923. {
  924. // if there is more than one event in the completed tick group ...
  925. if( ai > 1 )
  926. tick1 = _cmXsSpreadGraceNotes(a,ai); // ... then process the group
  927. ai = 0; // empty the tick group array
  928. tick0 = np->tick; // update the current group's common tick
  929. }
  930. // if the min. current tick is ahead of this event then move the event ahead
  931. if( tick1 > np->tick )
  932. np->tick = tick1;
  933. else
  934. tick1 = 0; // otherwise disable tick1
  935. // add this event to the tick group
  936. assert(ai<aN);
  937. a[ai++] = np;
  938. }
  939. // if there are events in the group array then process them
  940. if( ai > 1 )
  941. tick1 = _cmXsSpreadGraceNotes(a,ai);
  942. }
  943. }
  944. }
  945. bool _cmXScoreFindTiedNote( cmXScore_t* p, cmXsMeas_t* mp, cmXsNote_t* n0p, bool rptFl )
  946. {
  947. cmXsNote_t* nbp = n0p;
  948. cmXsNote_t* nnp = n0p->slink; // begin w/ note following np
  949. unsigned measNumb = mp->number;
  950. cmChar_t acc = n0p->alter==-1?'b' : (n0p->alter==1?'#':' ');
  951. if( rptFl )
  952. printf("%i %i %s ",n0p->meas->number,n0p->tick,cmMidiToSciPitch(n0p->pitch,NULL,0));
  953. while(1)
  954. {
  955. // if we are at the end of a measure advance to the next measure
  956. if( nnp == NULL )
  957. {
  958. mp = mp->link;
  959. nnp = mp->noteL;
  960. // if a measure was completed and no end note was found ... then the tie is unterminated
  961. // (a tie must be continued in every measure which it passes through)
  962. if( mp->number > measNumb + 1 )
  963. break;
  964. }
  965. // for each note starting at nnp
  966. for(; nnp!=NULL; nnp=nnp->slink)
  967. {
  968. // if this note is tied to the originating note (np)
  969. if( nnp->voice->id == n0p->voice->id && nnp->step == n0p->step && nnp->octave == n0p->octave )
  970. {
  971. nnp->flags |= kTieProcXsFl;
  972. nnp->flags = cmClrFlag(nnp->flags,kOnsetXsFl);
  973. n0p->tied = nnp;
  974. nbp->tied_dur += nnp->duration;
  975. nnp->tied_dur = 0;
  976. if( rptFl )
  977. printf("---> %i %i %s ",nnp->meas->number,nnp->tick,cmMidiToSciPitch(nnp->pitch,NULL,0));
  978. // if this note is not tied to a subsequent note
  979. if( cmIsNotFlag(nnp->flags,kTieBegXsFl) )
  980. return true;
  981. n0p = nnp;
  982. // record the measure number of the last note with a tie-start
  983. measNumb = mp->number;
  984. }
  985. }
  986. }
  987. cmErrWarnMsg(&p->err,kUnterminatedTieXsRC,"The tied %c%c%i in measure %i (tick:%i) was not terminated.",n0p->step,acc,n0p->octave,measNumb,n0p->tick);
  988. return false;
  989. }
  990. void _cmXScoreResolveTiesAndLoc( cmXScore_t* p )
  991. {
  992. unsigned n = 0; // count of notes which begin a tie
  993. unsigned m = 0; // count of tied notes that are correctly terminated.
  994. bool rptFl = false;
  995. cmXsPart_t* pp = p->partL;
  996. // for each part
  997. for(; pp!=NULL; pp=pp->link)
  998. {
  999. unsigned locIdx = 1;
  1000. cmXsMeas_t* mp = pp->measL;
  1001. // for each measure
  1002. for(; mp!=NULL; mp=mp->link)
  1003. {
  1004. cmXsNote_t* n0 = NULL;
  1005. cmXsNote_t* np = mp->noteL;
  1006. // for each note in this measure
  1007. for(; np!=NULL; np=np->slink)
  1008. {
  1009. // if this note begins a tie and has not yet been processed
  1010. // (A note that continues a tie and therefore has a kTieBegXsFl set
  1011. // may have already been processed by an earlier tied note.)
  1012. if( cmIsFlag(np->flags,kTieBegXsFl) && cmIsNotFlag(np->flags,kTieProcXsFl))
  1013. {
  1014. if( _cmXScoreFindTiedNote(p,mp,np,rptFl) )
  1015. m += 1;
  1016. if( rptFl )
  1017. printf("\n");
  1018. n += 1;
  1019. }
  1020. // Validate the tie state of the current note.
  1021. if( cmIsFlag(np->flags,kTieEndXsFl) && cmIsFlag(np->flags,kOnsetXsFl) )
  1022. {
  1023. cmChar_t acc = np->alter==-1?'b' : (np->alter==1?'#':' ');
  1024. cmErrWarnMsg(&p->err,kUnterminatedTieXsRC,"The tied %c%c%i in measure %i marked as a tied note but is also marked to sound.",np->step,acc,np->octave,mp->number);
  1025. }
  1026. //
  1027. // Set the score location of notes marked for onset and bar lines.
  1028. //
  1029. if( cmIsFlag(np->flags,kOnsetXsFl|kBarXsFl) )
  1030. {
  1031. // if this note does not share the same location as the previous 'located' note then increment the 'loc' index
  1032. if( cmIsFlag(np->flags,kBarXsFl) || (n0!=NULL && n0->tick!=np->tick))
  1033. locIdx += 1;
  1034. np->locIdx = locIdx;
  1035. n0 = np;
  1036. }
  1037. }
  1038. }
  1039. }
  1040. printf("Tied notes found:%i Not found:%i\n",m,n-m);
  1041. }
  1042. cmXsRC_t _cmXScoreResolveOctaveShift( cmXScore_t* p )
  1043. {
  1044. const cmXsSpan_t* s;
  1045. for(s=p->spanL; s!=NULL; s=s->link)
  1046. {
  1047. if( s->tick1 == -1)
  1048. {
  1049. cmErrWarnMsg(&p->err,kSyntaxErrorXsRC,"An unterminated octave shift span was encountered in measure %i staff=%i.",s->meas->number,s->staff);
  1050. }
  1051. else
  1052. {
  1053. cmXsMeas_t* m = p->partL->measL;
  1054. for(; m!=NULL; m=m->link)
  1055. if( m->number == s->meas->number )
  1056. break;
  1057. assert( m != NULL );
  1058. cmXsNote_t* note = m->noteL;
  1059. for(; note!=NULL; note=note->slink)
  1060. if( note->staff==s->staff && s->tick0 <= note->tick && note->tick < s->tick1 )
  1061. note->pitch += s->pitch_offset;
  1062. }
  1063. }
  1064. return kOkXsRC;
  1065. }
  1066. cmXsNote_t* _cmXScoreFindOverlappingNote( cmXScore_t* p, const cmXsNote_t* knp )
  1067. {
  1068. cmXsPart_t* pp = p->partL;
  1069. // for each part
  1070. for(; pp!=NULL; pp=pp->link)
  1071. {
  1072. cmXsMeas_t* mp = pp->measL;
  1073. // for each measure
  1074. for(; mp!=NULL; mp=mp->link)
  1075. {
  1076. cmXsNote_t* np = mp->noteL;
  1077. // for each note in this measure
  1078. for(; np!=NULL; np=np->slink)
  1079. if( np->uid != knp->uid
  1080. && cmIsFlag(np->flags,kOnsetXsFl)
  1081. && knp->pitch == np->pitch
  1082. && knp->tick >= np->tick
  1083. && knp->tick < (np->tick + np->tied_dur) )
  1084. {
  1085. return np;
  1086. }
  1087. }
  1088. }
  1089. return NULL;
  1090. }
  1091. void _cmXScoreProcessOverlappingNotes( cmXScore_t* p )
  1092. {
  1093. cmXsPart_t* pp = p->partL;
  1094. // for each part
  1095. for(; pp!=NULL; pp=pp->link)
  1096. {
  1097. cmXsMeas_t* mp = pp->measL;
  1098. // for each measure
  1099. for(; mp!=NULL; mp=mp->link)
  1100. {
  1101. cmXsNote_t* np = mp->noteL;
  1102. cmXsNote_t* fnp;
  1103. // for each note in this measure
  1104. for(; np!=NULL; np=np->slink)
  1105. if( cmIsFlag(np->flags,kOnsetXsFl) && (fnp = _cmXScoreFindOverlappingNote(p,np)) != NULL)
  1106. {
  1107. // is np entirely contained inside fnp
  1108. bool embeddedFl = fnp->tick + fnp->tied_dur > np->tick + np->tied_dur;
  1109. //printf("bar=%3i %4s voice:%2i %2i : %7i %7i : %7i %7i : %7i : %c \n",np->meas->number,cmMidiToSciPitch(np->pitch,NULL,0),np->voice->id,fnp->voice->id,fnp->tick,fnp->tick+fnp->duration,np->tick,np->tick+np->duration, (fnp->tick+fnp->duration) - np->tick, embeddedFl ? 'E' : 'O');
  1110. // turn off embedded notes
  1111. if( embeddedFl )
  1112. {
  1113. if( np->voice->id == fnp->voice->id )
  1114. cmErrWarnMsg(&p->err,kOverlapWarnXsRC,"A time embedded note (bar=%i %s) was removed even though it overlapped with a note in the same voice.",np->meas->number,cmMidiToSciPitch(np->pitch,NULL,0));
  1115. np->flags = cmClrFlag(np->flags,kOnsetXsFl);
  1116. }
  1117. else
  1118. {
  1119. int d = (fnp->tick+fnp->tied_dur) - np->tick;
  1120. // shorten the first note
  1121. if( d > 0 && d < fnp->tied_dur )
  1122. fnp->tied_dur -= d;
  1123. // move the second note just past it
  1124. np->tick = fnp->tick + fnp->tied_dur + 1;
  1125. }
  1126. }
  1127. }
  1128. }
  1129. }
  1130. // The identical pitch may be notated to play simultaneously on different voices.
  1131. // As performed on the piano this will equate to a single sounding note.
  1132. // This function clears the onset flag on all except one of the duplicated notes.
  1133. void _cmXScoreRemoveDuplicateNotes( cmXScore_t* p )
  1134. {
  1135. cmXsPart_t* pp = p->partL;
  1136. // for each part
  1137. for(; pp!=NULL; pp=pp->link)
  1138. {
  1139. cmXsMeas_t* mp = pp->measL;
  1140. // for each measure
  1141. for(; mp!=NULL; mp=mp->link)
  1142. {
  1143. cmXsNote_t* np = mp->noteL;
  1144. // for each note in this measure
  1145. for(; np!=NULL; np=np->slink)
  1146. if( cmIsFlag(np->flags,kOnsetXsFl) )
  1147. {
  1148. cmXsNote_t* n0p = mp->noteL;
  1149. for(; n0p!=NULL; n0p=n0p->slink)
  1150. if( n0p!=np && cmIsFlag(n0p->flags,kOnsetXsFl) && np->locIdx==n0p->locIdx && np->pitch==n0p->pitch )
  1151. n0p->flags = cmClrFlag(n0p->flags,kOnsetXsFl);
  1152. }
  1153. }
  1154. }
  1155. }
  1156. void _cmXScoreSetMeasGroups( cmXScore_t* p, unsigned flag )
  1157. {
  1158. unsigned sectionId = 0;
  1159. cmXsNote_t* n0 = NULL;
  1160. cmXsPart_t* pp = p->partL;
  1161. // for each part
  1162. for(; pp!=NULL; pp=pp->link)
  1163. {
  1164. cmXsMeas_t* mp = pp->measL;
  1165. // for each measure
  1166. for(; mp!=NULL; mp=mp->link)
  1167. {
  1168. cmXsNote_t* np = mp->noteL;
  1169. // for each note in this measure
  1170. for(; np!=NULL; np=np->slink)
  1171. {
  1172. // if this note has a heel marker and we are looking for evenness events
  1173. if( cmIsFlag(flag,kEvenXsFl) && cmIsFlag(np->flags,kHeelXsFl) )
  1174. {
  1175. np->flags = cmSetFlag(np->flags,kBegGroupXsFl | kEndGroupXsFl );
  1176. np->evenGroupId = sectionId + 1;
  1177. }
  1178. // if this note is of the type we are looking for
  1179. if( cmIsFlag(np->flags,flag) )
  1180. {
  1181. if( n0 == NULL )
  1182. np->flags = cmSetFlag(np->flags,kBegGroupXsFl);
  1183. n0 = np;
  1184. }
  1185. // if this is a section marker
  1186. if( cmIsFlag(np->flags,kSectionXsFl) )
  1187. {
  1188. if( n0 != NULL )
  1189. {
  1190. np->flags = cmSetFlag(np->flags,kEndGroupXsFl);
  1191. switch( flag )
  1192. {
  1193. case kEvenXsFl: n0->evenGroupId = sectionId+1; break;
  1194. case kDynXsFl: n0->dynGroupId = sectionId+1; break;
  1195. case kTempoXsFl: n0->tempoGroupId= sectionId+1; break;
  1196. }
  1197. }
  1198. if( cmIsFlag(np->flags,kSectionXsFl) )
  1199. {
  1200. sectionId = 0;
  1201. if( np->tvalue == NULL )
  1202. cmErrWarnMsg(&p->err,kSyntaxErrorXsRC,"An apparent section label in measure '%i' is blank.",np->meas->number);
  1203. else
  1204. if( cmTextToUInt( np->tvalue, &sectionId, NULL ) != kOkTxRC )
  1205. cmErrWarnMsg(&p->err,kSyntaxErrorXsRC,"The section label '%s' is not an integer.",np->tvalue);
  1206. //sectionId = np->tvalue==NULL ? 0 : strtol(np->tvalue,NULL,10);
  1207. }
  1208. n0 = NULL;
  1209. }
  1210. }
  1211. }
  1212. }
  1213. }
  1214. cmXsRC_t _cmXScoreWriteScorePlotFile( cmXScore_t* p, const cmChar_t* fn )
  1215. {
  1216. cmXsRC_t rc = kOkXsRC;
  1217. cmFileH_t fH = cmFileNullHandle;
  1218. double ticks_per_sec = 0;
  1219. double onset_secs = 0;
  1220. if( cmFileOpen(&fH,fn,kWriteFileFl,p->err.rpt) != kOkFileRC )
  1221. return cmErrMsg(&p->err,kFileFailXsRC,"Unable to create the file '%s'.",cmStringNullGuard(fn));
  1222. cmXsPart_t* pp = p->partL;
  1223. for(; pp!=NULL; pp=pp->link)
  1224. {
  1225. cmXsMeas_t* mp = pp->measL;
  1226. for(; mp!=NULL; mp=mp->link)
  1227. {
  1228. cmFilePrintf(fH,"b %f %i %s B\n",onset_secs,mp->number,"bar");
  1229. cmXsNote_t* np = mp->noteL;
  1230. unsigned tick0 = 0;
  1231. for(; np!=NULL; np=np->slink)
  1232. {
  1233. if( cmIsFlag(np->flags,kMetronomeXsFl) )
  1234. {
  1235. double bps = np->tied_dur / 60.0;
  1236. // t b t
  1237. // - = - -
  1238. // s s b
  1239. ticks_per_sec = bps * mp->divisions;
  1240. }
  1241. else
  1242. {
  1243. if( cmIsFlag(np->flags,kOnsetXsFl) )
  1244. {
  1245. onset_secs += (np->tick - tick0) / ticks_per_sec;
  1246. tick0 = np->tick;
  1247. cmFilePrintf(fH,"n %f %f %i %s %s\n",onset_secs,np->tied_dur/ticks_per_sec,np->uid,cmMidiToSciPitch(np->pitch,NULL,0),cmIsFlag(np->flags,kGraceXsFl)?"G":"N");
  1248. }
  1249. }
  1250. }
  1251. onset_secs += (mp->divisions * mp->beats - tick0) / ticks_per_sec;
  1252. }
  1253. }
  1254. cmFileClose(&fH);
  1255. return rc;
  1256. }
  1257. // Force the bar event to be the first event in the measure.
  1258. void _cmXScoreFixBarLines( cmXScore_t* p )
  1259. {
  1260. cmXsPart_t* pp = p->partL;
  1261. for(; pp!=NULL; pp=pp->link)
  1262. {
  1263. cmXsMeas_t* mp = pp->measL;
  1264. for(; mp!=NULL; mp=mp->link)
  1265. {
  1266. cmXsNote_t* np = mp->noteL;
  1267. cmXsNote_t* ep = NULL;
  1268. for(; np!=NULL; np=np->slink )
  1269. {
  1270. if( cmIsFlag(np->flags,kBarXsFl) )
  1271. {
  1272. if( ep != NULL )
  1273. np->tick = ep->tick;
  1274. break;
  1275. }
  1276. if( ep == NULL )
  1277. ep = np;
  1278. }
  1279. }
  1280. }
  1281. }
  1282. // Assign pedal down durations to pedal down events.
  1283. cmXsRC_t _cmXScoreProcessPedals( cmXScore_t* p )
  1284. {
  1285. cmXsRC_t rc = kOkXsRC;
  1286. cmXsPart_t* pp = p->partL;
  1287. for(; pp!=NULL; pp=pp->link)
  1288. {
  1289. cmXsNote_t* dnp = NULL; // pointer to last damper down event
  1290. cmXsNote_t* snp = NULL; // pointer to last sostenuto down event
  1291. cmXsMeas_t* mp = pp->measL;
  1292. for(; mp!=NULL; mp=mp->link)
  1293. {
  1294. cmXsNote_t* np = mp->noteL;
  1295. for(; np!=NULL; np=np->slink )
  1296. {
  1297. unsigned x = np->flags & (kDampDnXsFl|kDampUpXsFl|kDampUpDnXsFl|kSostUpXsFl|kSostDnXsFl);
  1298. switch( x )
  1299. {
  1300. case 0:
  1301. break;
  1302. case kDampDnXsFl:
  1303. if( dnp != NULL )
  1304. cmErrWarnMsg(&p->err,kPedalStateErrorXsRc,"Damper down not preceded by damper up in measure:%i.",mp->number);
  1305. else
  1306. dnp = np;
  1307. break;
  1308. case kDampUpXsFl:
  1309. if( dnp == NULL )
  1310. cmErrWarnMsg(&p->err,kPedalStateErrorXsRc,"Damper up not preceded by damper down in measure:%i.",mp->number);
  1311. else
  1312. {
  1313. dnp->duration = np->tick - dnp->tick;
  1314. dnp = NULL;
  1315. }
  1316. break;
  1317. case kDampUpDnXsFl:
  1318. if( dnp == NULL )
  1319. cmErrWarnMsg(&p->err,kPedalStateErrorXsRc,"Damper up/down not preceded by damper down in measure:%i.",mp->number);
  1320. else
  1321. {
  1322. dnp->duration = np->tick - dnp->tick;
  1323. dnp = np;
  1324. }
  1325. break;
  1326. case kSostDnXsFl:
  1327. if( snp != NULL )
  1328. cmErrWarnMsg(&p->err,kPedalStateErrorXsRc,"Sostenuto down not preceded by sostenuto up in measure:%i.",mp->number);
  1329. else
  1330. snp = np;
  1331. break;
  1332. case kSostUpXsFl:
  1333. if( snp == NULL )
  1334. cmErrWarnMsg(&p->err,kPedalStateErrorXsRc,"Sostenuto up not preceded by sostenuto down in measure:%i.",mp->number);
  1335. else
  1336. {
  1337. snp->duration = np->tick - snp->tick;
  1338. snp = NULL;
  1339. }
  1340. break;
  1341. default:
  1342. {
  1343. assert(0);
  1344. }
  1345. } // switch
  1346. } // for notes
  1347. } // for measures
  1348. if( dnp != NULL )
  1349. cmErrWarnMsg(&p->err,kPedalStateErrorXsRc,"Damper left down at the end of a part.");
  1350. if( snp != NULL )
  1351. cmErrWarnMsg(&p->err,kPedalStateErrorXsRc,"Sostenuto left down at the end of a part.");
  1352. }
  1353. _cmXScoreSort(p);
  1354. return rc;
  1355. }
  1356. void _cmXScoreInsertTime( cmXScore_t* p, cmXsMeas_t* mp, cmXsNote_t* np, unsigned expand_ticks )
  1357. {
  1358. for(; mp!=NULL; mp=mp->link)
  1359. {
  1360. if( np == NULL )
  1361. np = mp->noteL;
  1362. for(; np!=NULL; np=np->slink)
  1363. np->tick += expand_ticks;
  1364. }
  1365. }
  1366. void _cmXScoreGraceInsertTimeBase( cmXScore_t* p, unsigned graceGroupId, cmXsNote_t* aV[], unsigned aN, unsigned initTick )
  1367. {
  1368. cmXsNote_t* np = NULL;
  1369. unsigned expand_ticks = 0;
  1370. unsigned ticks = initTick;
  1371. unsigned t0 = 0;
  1372. unsigned i;
  1373. for(i=0; i<aN; ++i)
  1374. if( cmIsFlag(aV[i]->flags,kGraceXsFl) && aV[i]->graceGroupId == graceGroupId )
  1375. {
  1376. // if this grace note falls on the same tick as the previous grace note
  1377. if( np != NULL && aV[i]->tick == t0 )
  1378. aV[i]->tick = np->tick;
  1379. else
  1380. {
  1381. t0 = aV[i]->tick; // store the unmodified tick value of this note
  1382. aV[i]->tick = ticks; // set the new tick value
  1383. ticks += aV[i]->duration; // calc the next grace not location
  1384. expand_ticks += aV[i]->duration; // track how much we are expanding time by
  1385. }
  1386. np = aV[i];
  1387. }
  1388. np = np->slink;
  1389. if( np != NULL )
  1390. _cmXScoreInsertTime(p,np->meas,np,expand_ticks);
  1391. }
  1392. // (a) Insert the grace notes in between the first and last note in the group
  1393. // by inserting time between the first and last note.
  1394. // Note that in effect his means that the last note is pushed back
  1395. // in time by the total duration of the grace notes.
  1396. void _cmXScoreGraceInsertTime( cmXScore_t* p, unsigned graceGroupId, cmXsNote_t* aV[], unsigned aN )
  1397. {
  1398. _cmXScoreGraceInsertTimeBase( p, graceGroupId,aV,aN, aV[aN-1]->tick );
  1399. }
  1400. // (s) Insert the grace notes in between the first and last note in the group
  1401. // but do not insert any additional time betwee the first and last note.
  1402. // In effect time is removed from the first note and taken by the grace notes.
  1403. // The time position of the last note is therefore unchanged.
  1404. void _cmXScoreGraceOverlayTime( cmXScore_t* p, unsigned graceGroupId, cmXsNote_t* aV[], unsigned aN )
  1405. {
  1406. assert(aN >= 3 );
  1407. int i = (int)aN-2;
  1408. cmXsNote_t* np = aV[aN-1];
  1409. unsigned t0 = -1;
  1410. for(; i>0; --i)
  1411. if( cmIsFlag(aV[i]->flags,kGraceXsFl) && aV[i]->graceGroupId == graceGroupId )
  1412. {
  1413. if( aV[i]->tick == t0)
  1414. aV[i]->tick = np->tick;
  1415. else
  1416. {
  1417. t0 = aV[i]->tick;
  1418. aV[i]->tick = np->tick - aV[i]->duration;
  1419. }
  1420. np = aV[i];
  1421. }
  1422. }
  1423. // (A) Play the first grace at the time of the first note in the group (which is a non-grace note)
  1424. // and then expand time while inserting the other grace notes.
  1425. void _cmXScoreGraceInsertAfterFirst( cmXScore_t* p, unsigned graceGroupId, cmXsNote_t* aV[], unsigned aN )
  1426. {
  1427. _cmXScoreGraceInsertTimeBase( p, graceGroupId,aV,aN, aV[0]->tick );
  1428. }
  1429. // (n) Play the first grace not shortly (one grace note duration) after the first note
  1430. // in the group (which is a non-grace note) and then expand time while inserting the other
  1431. // grace notes.
  1432. void _cmXScoreGraceInsertSoonAfterFirst( cmXScore_t* p, unsigned graceGroupId, cmXsNote_t* aV[], unsigned aN )
  1433. {
  1434. _cmXScoreGraceInsertTimeBase( p, graceGroupId,aV,aN, aV[0]->tick + aV[1]->duration );
  1435. }
  1436. // Adjust the locations of grace notes. Note that this must be done
  1437. // after reordering so that we can be sure that the order in time of
  1438. // the notes in each group has been set prior to building the
  1439. // grace note groups - which must be in reverse time order.
  1440. cmXsRC_t _cmXScoreProcessGraceNotes( cmXScore_t* p, unsigned nextGraceGroupId )
  1441. {
  1442. cmXsRC_t rc = kOkXsRC;
  1443. unsigned graceGroupId = 1;
  1444. double graceDurSec = 1.0/15.0; // duration of all grace notes in seconds
  1445. for(; graceGroupId<nextGraceGroupId; ++graceGroupId)
  1446. {
  1447. cmXsNote_t* gn0p = NULL; // first note in the grace group
  1448. cmXsNote_t* gn1p = NULL; // last note in the grace group
  1449. unsigned gN = 0;
  1450. cmXsPart_t* pp = p->partL;
  1451. double ticksPerSec = 0;
  1452. // Build a note chain, using cmXsNote_t.grace, between gn0p and
  1453. // gn1p containing all the grace notes with
  1454. // cmXsNote_t.graceGroupId == graceGroupId.
  1455. for(; pp!=NULL; pp=pp->link)
  1456. {
  1457. cmXsMeas_t* mp = pp->measL;
  1458. for(; mp!=NULL; mp=mp->link)
  1459. {
  1460. cmXsNote_t* np = mp->noteL;
  1461. for(; np!=NULL; np=np->slink )
  1462. {
  1463. // notice change of tempo
  1464. if( cmIsFlag(np->flags,kMetronomeXsFl) )
  1465. {
  1466. // ticks/sec = ticks/qn * qn/sec
  1467. ticksPerSec = mp->divisions * np->duration / 60.0;
  1468. }
  1469. // if this note is part of the grace note group we are searching for
  1470. if( np->graceGroupId == graceGroupId )
  1471. {
  1472. // track the first note in the grace note list
  1473. if( gn0p == NULL )
  1474. gn0p = np;
  1475. // add the note to the end of the grace note list
  1476. if( gn1p != NULL )
  1477. gn1p->grace = np;
  1478. // track the last note in the grace note list
  1479. gn1p = np;
  1480. // set each grace note to have 1/20 of a second duration
  1481. if( cmIsFlag(np->flags,kGraceXsFl) )
  1482. np->duration = np->tied_dur = floor(ticksPerSec * graceDurSec);
  1483. gN += 1;
  1484. }
  1485. } // for each note in this meassure
  1486. } // for each measure
  1487. } // for each part
  1488. // no records were found for this grace id - this grace group id was not used
  1489. if( gn0p == NULL )
  1490. continue;
  1491. // grace note groups must have at least 3 members
  1492. if( gN < 3 )
  1493. {
  1494. rc = cmErrMsg(&p->err,kSyntaxErrorXsRC,"The grace note group (groupid=%i) ending in meas %i has fewer than 3 (%i) members.", gn1p->graceGroupId, gn1p->meas->number, gN );
  1495. break;
  1496. }
  1497. // gn0p is now set to the first note in th group
  1498. // gn1p is now set to the last note in the group
  1499. // verify that the first note is marked with kBegGraceXsFl
  1500. if( cmIsNotFlag(gn0p->flags,kBegGraceXsFl) )
  1501. {
  1502. rc = cmErrMsg(&p->err,kSyntaxErrorXsRC,"The first note in a grace note group in meas %i tick %i groupid:%i is not marked with a 'b'.", gn0p->meas->number, gn0p->tick, graceGroupId );
  1503. break;
  1504. }
  1505. // verify that the last note is marked with kEndGraceXsFl
  1506. if( cmIsNotFlag(gn1p->flags,kEndGraceXsFl) )
  1507. {
  1508. rc = cmErrMsg(&p->err,kSyntaxErrorXsRC,"The last note in a grace note group in meas %i is not marked with a valid operator character.", gn1p->meas->number );
  1509. break;
  1510. }
  1511. // Count the total number of events between gn0p and gn1p
  1512. cmXsNote_t* n0p = NULL;
  1513. cmXsNote_t* n1p = gn0p;
  1514. cmXsMeas_t* mp = gn0p->meas;
  1515. unsigned aN = 0;
  1516. for(; n0p != gn1p; n1p=n1p->slink )
  1517. {
  1518. // if we are crossing a measure boundary
  1519. if( n1p == NULL )
  1520. {
  1521. mp = mp->link;
  1522. assert(mp!=NULL);
  1523. n1p = mp->noteL;
  1524. }
  1525. if(0)
  1526. {
  1527. bool fl = n0p != NULL && n0p->tick < n1p->tick;
  1528. unsigned type = n1p->flags & (kBegGraceXsFl|kEndGraceXsFl|kAddGraceXsFl|kSubGraceXsFl|kAFirstGraceXsFl|kNFirstGraceXsFl);
  1529. printf("%3i 0x%08x %i %3i %5i %i\n",n1p->graceGroupId,type,n1p->meas->number,n1p->tick,n1p->duration,fl);
  1530. }
  1531. ++aN;
  1532. n0p = n1p;
  1533. }
  1534. // create a vector of pointers to all events between gn0p and gn1p
  1535. cmXsNote_t* aV[ aN ];
  1536. unsigned i;
  1537. n1p = gn0p;
  1538. n0p = NULL;
  1539. mp = gn0p->meas;
  1540. for(i=0; n0p != gn1p; n1p=n1p->slink )
  1541. {
  1542. // if we are crossing a measure boundary
  1543. if( n1p == NULL )
  1544. {
  1545. mp = mp->link;
  1546. assert(mp!=NULL);
  1547. n1p = mp->noteL;
  1548. }
  1549. assert(i<aN);
  1550. aV[i++] = n1p;
  1551. n0p = n1p;
  1552. }
  1553. switch( gn1p->flags & (kAddGraceXsFl | kSubGraceXsFl | kAFirstGraceXsFl | kNFirstGraceXsFl ) )
  1554. {
  1555. case kAddGraceXsFl:
  1556. _cmXScoreGraceInsertTime(p, graceGroupId, aV, aN );
  1557. break;
  1558. case kSubGraceXsFl:
  1559. _cmXScoreGraceOverlayTime(p, graceGroupId, aV, aN );
  1560. break;
  1561. case kAFirstGraceXsFl:
  1562. _cmXScoreGraceInsertAfterFirst(p,graceGroupId,aV,aN);
  1563. break;
  1564. case kNFirstGraceXsFl:
  1565. _cmXScoreGraceInsertSoonAfterFirst(p,graceGroupId,aV,aN);
  1566. break;
  1567. default:
  1568. { assert(0); }
  1569. }
  1570. }
  1571. return rc;
  1572. }
  1573. cmXsNote_t* _cmXScoreDynamicForkEndNote( cmXScore_t* p, cmXsNote_t* bnp )
  1574. {
  1575. assert( cmIsFlag(bnp->flags,kDynBegForkXsFl) );
  1576. cmXsMeas_t* mp = bnp->meas;
  1577. cmXsNote_t* np = bnp->slink;
  1578. for(; mp!=NULL; mp=mp->link,np = mp==NULL?NULL : mp->noteL)
  1579. {
  1580. for(; np!=NULL; np=np->slink)
  1581. {
  1582. if( cmIsFlag(np->flags,kDynBegForkXsFl) )
  1583. {
  1584. cmErrMsg(&p->err,kSyntaxErrorXsRC,"The a dynamic fork begin (meas:%i loc:%i) was found prior to a matched end.",np->meas->number,np->locIdx);
  1585. return NULL;
  1586. }
  1587. if( cmIsFlag(np->flags,kDynEndForkXsFl) /*&& np->voice->id == bnp->voice->id*/ )
  1588. return np;
  1589. }
  1590. }
  1591. return NULL;
  1592. }
  1593. cmXsRC_t _cmXScoreProcessDynamicFork( cmXScore_t* p, cmXsNote_t* bnp )
  1594. {
  1595. cmXsNote_t* enp;
  1596. if((enp = _cmXScoreDynamicForkEndNote(p,bnp)) == NULL)
  1597. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"The dynamic fork beginning in measure %i at tick %i voice %i loc:%i was not terminated.", bnp->meas->number,bnp->tick,bnp->voice->id,bnp->locIdx);
  1598. //cmRptPrintf( p->err.rpt, "Dynamic Fork: meas:%i tick:%i loc:%i to meas:%i tick:%i loc:%i\n", bnp->meas->number, bnp->tick, bnp->locIdx, enp->meas->number, enp->tick, enp->locIdx );
  1599. double begDynFrac = bnp->dynamics;
  1600. double begVelFrac = bnp->vel;
  1601. double endDynFrac = enp->dynamics;
  1602. double endVelFrac = enp->vel;
  1603. cmXsMeas_t* mp = bnp->meas;
  1604. cmXsNote_t* np = bnp->slink;
  1605. while( mp != NULL )
  1606. {
  1607. for(; np!=NULL; np=np->slink)
  1608. {
  1609. //Conditioning this on np->dynamics==0 will may would cause 'silent' notes to be assigned
  1610. // a non-zero dynamics value - so we condition on np->vel instead.
  1611. if( cmIsFlag(np->flags,kOnsetXsFl) && np->vel == 0 )
  1612. {
  1613. double frac = ((double)np->tick - bnp->tick) / (enp->tick - bnp->tick);
  1614. np->dynamics = lround(begDynFrac + ((endDynFrac - begDynFrac) * frac));
  1615. np->vel = lround(begVelFrac + ((endVelFrac - begVelFrac) * frac));
  1616. }
  1617. if( np == enp )
  1618. break;
  1619. }
  1620. if( np == enp)
  1621. break;
  1622. if( (mp=mp->link) != NULL )
  1623. np=mp->noteL;
  1624. }
  1625. return kOkXsRC;
  1626. }
  1627. cmXsRC_t _cmXScoreProcessDynamicForks( cmXScore_t* p )
  1628. {
  1629. cmXsRC_t rc = kOkXsRC;
  1630. cmXsPart_t* pp = p->partL;
  1631. for(; pp!=NULL; pp=pp->link)
  1632. {
  1633. cmXsMeas_t* mp = pp->measL;
  1634. for(; mp!=NULL; mp=mp->link)
  1635. {
  1636. cmXsNote_t* np = mp->noteL;
  1637. for(; np!=NULL; np=np->slink )
  1638. {
  1639. if( cmIsFlag(np->flags,kDynBegForkXsFl) )
  1640. if((rc = _cmXScoreProcessDynamicFork(p,np)) != kOkXsRC )
  1641. return rc;
  1642. }
  1643. }
  1644. }
  1645. return rc;
  1646. }
  1647. //-------------------------------------------------------------------------------------------
  1648. typedef struct
  1649. {
  1650. unsigned idx; // Fields from the reordering input file which are
  1651. unsigned voice; // used to match the reorder record to
  1652. unsigned locIdx; // the associated a cmXsNode_t record.
  1653. unsigned tick; //
  1654. unsigned durtn; //
  1655. float rval; //
  1656. unsigned midi; //
  1657. cmXsNote_t* note; // The cmXsNote_t* associated with this cmXsReorder_t record
  1658. unsigned dynIdx; // cmInvalidIdx=ignore otherwise index into _cmXScoreDynMarkArray[]
  1659. unsigned newFlags; // 0=ignore | kSostUp/DnXsFl | kDampUp/DnXsFl | kTieEndXsFl
  1660. unsigned newTick; // 0=ignore >0 new tick value
  1661. unsigned graceFlags; // 0=ignore See kXXXGraceXsFl
  1662. unsigned graceGroupId; // 0=ignore >0=grace note group id
  1663. unsigned pitch; // 0=ignore >0 new pitch
  1664. } cmXsReorder_t;
  1665. typedef struct _cmXScoreDynMark_str
  1666. {
  1667. const cmChar_t* mark; //
  1668. unsigned id; // (1-17) maps to velocity
  1669. unsigned dyn; // pppp - fff (1-9) as used by cmScore
  1670. int adjust; // {-1,0,+1}
  1671. unsigned vel; // associated MIDI velocity
  1672. } _cmXScoreDynMark_t;
  1673. _cmXScoreDynMark_t _cmXScoreDynMarkArray[] =
  1674. {
  1675. {"s", 1, 0, 0, 1}, // silent note
  1676. {"pppp-", 2, 1, -1, 3},
  1677. {"pppp", 3, 1, 0, 10},
  1678. {"pppp+", 4, 1, 1, 22},
  1679. {"ppp-", 4, 2, -1, 22},
  1680. {"ppp", 5, 2, 0, 29},
  1681. {"ppp+", 6, 2, 1, 36},
  1682. {"pp-", 6, 3, -1, 36},
  1683. {"pp", 7, 3, 0, 43},
  1684. {"pp+", 8, 3, 1, 50},
  1685. {"p-", 8, 4, -1, 50},
  1686. {"p", 9, 4, 0, 57},
  1687. {"p+", 10, 4, 1, 64},
  1688. {"mp-", 10, 5, -1, 64},
  1689. {"mp", 11, 5, 0, 71},
  1690. {"mp+", 12, 5, 1, 78},
  1691. {"mf-", 12, 6, -1, 78},
  1692. {"mf", 13, 6, 0, 85},
  1693. {"mf+", 14, 6, 1, 92},
  1694. {"f-", 14, 7, -1, 92},
  1695. {"f", 15, 7, 0, 99},
  1696. {"f+", 16, 7, 1, 106},
  1697. {"ff", 17, 8, 0, 113},
  1698. {"ff+", 18, 8, 1, 120},
  1699. {"fff", 19, 9, 0, 127},
  1700. {NULL,0,0,0,0}
  1701. };
  1702. cmXsNote_t* _cmXsReorderFindNote( cmXScore_t* p, unsigned measNumb, const cmXsReorder_t* r, unsigned iii )
  1703. {
  1704. cmXsPart_t* pp = p->partL;
  1705. for(; pp!=NULL; pp=pp->link)
  1706. {
  1707. cmXsMeas_t* mp = pp->measL;
  1708. for(; mp!=NULL; mp=mp->link)
  1709. if( mp->number == measNumb)
  1710. {
  1711. cmXsNote_t* np = mp->noteL;
  1712. int index = 0;
  1713. for(; np!=NULL; np=np->slink,++index)
  1714. {
  1715. if( 0 /*mp->number==19*/ )
  1716. printf("voice: %i %i loc:%i %i tick:%i %i pitch:%i %i rval:%f %f idx:%i %i \n",
  1717. np->voice->id, r->voice,
  1718. np->locIdx , r->locIdx ,
  1719. np->tick , r->tick ,
  1720. np->pitch , r->midi ,
  1721. np->rvalue, r->rval,
  1722. index , r->idx);
  1723. if( np->voice->id == r->voice &&
  1724. np->locIdx == r->locIdx &&
  1725. np->tick == r->tick &&
  1726. //np->duration == r->durtn &&
  1727. np->rvalue == r->rval &&
  1728. np->pitch == r->midi &&
  1729. index == r->idx )
  1730. {
  1731. //printf("Found: %i \n", r->midi);
  1732. return np;
  1733. }
  1734. }
  1735. }
  1736. }
  1737. cmErrMsg(&p->err,kSyntaxErrorXsRC,"Reorder note not found meas:%i index:%i.",measNumb,iii);
  1738. return NULL;
  1739. }
  1740. void _cmXScoreInsertPedalEvent( cmXScore_t* p, const cmXsReorder_t* r, unsigned flags )
  1741. {
  1742. // Create a new score event record
  1743. cmXsNote_t* nn = cmLhAllocZ(p->lhH,cmXsNote_t,1);
  1744. nn->uid = p->nextUid++;
  1745. nn->voice = r->note->voice;
  1746. nn->meas = r->note->meas;
  1747. nn->flags = flags;
  1748. // Pedal down events occur after the event they are attached to
  1749. if( cmIsFlag(flags,kSostDnXsFl | kDampDnXsFl ) )
  1750. {
  1751. nn->tick = r->note->tick + 1;
  1752. _cmXScoreInsertNoteAfter(r->note,nn);
  1753. }
  1754. else
  1755. {
  1756. // Pedal up events occur before the event they are attached to
  1757. if( cmIsFlag(flags,kSostUpXsFl | kDampUpXsFl ) )
  1758. {
  1759. nn->tick = r->note->tick==0 ? 0 : r->note->tick - 1;
  1760. _cmXScoreInsertNoteBefore(r->note,nn);
  1761. }
  1762. else
  1763. { assert(0); }
  1764. }
  1765. }
  1766. cmXsRC_t _cmXScoreReorderMeas( cmXScore_t* p, unsigned measNumb, cmXsReorder_t* rV, unsigned rN )
  1767. {
  1768. unsigned i;
  1769. if( rN == 0 )
  1770. return kOkXsRC;
  1771. // set the 'note' field on each cmXsReorder_t record
  1772. for(i=0; i<rN; ++i)
  1773. if((rV[i].note = _cmXsReorderFindNote(p,measNumb,rV+i,i)) == NULL )
  1774. return kSyntaxErrorXsRC;
  1775. // remove deleted notes
  1776. for(i=0; i<rN; ++i)
  1777. if( cmIsFlag(rV[i].newFlags,kDeleteXsFl) )
  1778. if( _cmXScoreRemoveNote( rV[i].note ) != kOkXsRC )
  1779. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Event marked to skip was not found in measure: %i",measNumb);
  1780. cmXsMeas_t* mp = rV[0].note->meas;
  1781. cmXsNote_t* n0p = NULL;
  1782. assert( mp->number == measNumb );
  1783. // Reassign the slink of the cmXsNote_t records in this measure
  1784. // according to their order in rV[].
  1785. for(i=0; i<rN; ++i)
  1786. {
  1787. if( cmIsFlag(rV[i].newFlags,kDeleteXsFl) )
  1788. continue;
  1789. if( n0p == NULL )
  1790. mp->noteL = rV[i].note;
  1791. else
  1792. n0p->slink = rV[i].note;
  1793. // if a new tick was specified
  1794. if( rV[i].newTick != 0 )
  1795. rV[i].note->tick = rV[i].newTick;
  1796. // if a dynamic or velocity mark was included
  1797. if( rV[i].dynIdx != cmInvalidIdx )
  1798. {
  1799. rV[i].note->dynamics = _cmXScoreDynMarkArray[ rV[i].dynIdx ].dyn;
  1800. rV[i].note->vel = _cmXScoreDynMarkArray[ rV[i].dynIdx ].vel;
  1801. }
  1802. // Set the dynamic fork begin/end flags for later _cmXScoreProcessDynamicForks()
  1803. if( cmIsFlag(rV[i].newFlags,kDynBegForkXsFl) )
  1804. rV[i].note->flags = cmSetFlag(rV[i].note->flags,kDynBegForkXsFl);
  1805. if( cmIsFlag(rV[i].newFlags,kDynEndForkXsFl) )
  1806. rV[i].note->flags = cmSetFlag(rV[i].note->flags,kDynEndForkXsFl);
  1807. // if the tie end flag was set
  1808. if( cmIsFlag(rV[i].newFlags,kTieEndXsFl) )
  1809. {
  1810. rV[i].note->flags |= kTieEndXsFl;
  1811. rV[i].note->flags = cmClrFlag( rV[i].note->flags, kOnsetXsFl );
  1812. rV[i].newFlags = cmClrFlag( rV[i].newFlags, kTieEndXsFl);
  1813. }
  1814. // if a new note value was specified
  1815. if( rV[i].pitch != 0 )
  1816. rV[i].note->pitch = rV[i].pitch;
  1817. rV[i].note->flags |= rV[i].graceFlags;
  1818. rV[i].note->graceGroupId = rV[i].graceGroupId;
  1819. n0p = rV[i].note;
  1820. n0p->slink = NULL;
  1821. }
  1822. // Insert new note records for pedal up/dn events.
  1823. for(i=0; i<rN; ++i)
  1824. {
  1825. if( rV[i].newFlags != 0 )
  1826. {
  1827. if( cmIsFlag(rV[i].newFlags,kDampDnXsFl ) )
  1828. _cmXScoreInsertPedalEvent(p,rV + i,kDampDnXsFl);
  1829. if( cmIsFlag(rV[i].newFlags,kSostDnXsFl ) )
  1830. _cmXScoreInsertPedalEvent(p,rV + i,kSostDnXsFl);
  1831. if( cmIsFlag(rV[i].newFlags,kDampUpXsFl ) )
  1832. _cmXScoreInsertPedalEvent(p,rV + i,kDampUpXsFl);
  1833. if( cmIsFlag(rV[i].newFlags,kSostUpXsFl ) )
  1834. _cmXScoreInsertPedalEvent(p,rV + i,kSostUpXsFl);
  1835. }
  1836. }
  1837. return kOkXsRC;
  1838. }
  1839. cmXsRC_t _cmXScoreReorderParseDyn(cmXScore_t* p, const cmChar_t* b, unsigned lineNumb, unsigned* dynIdxRef, unsigned* flagsRef, int measNumb )
  1840. {
  1841. cmXsRC_t rc = kOkXsRC;
  1842. const cmChar_t* s = NULL;
  1843. bool begForkFl = false;
  1844. bool endForkFl = false;
  1845. *dynIdxRef = cmInvalidIdx;
  1846. // locate the '!' which indicates the start of a dynamic marking
  1847. if( (s = strchr(b,'!')) == NULL )
  1848. return rc;
  1849. ++s; // increment past the '!'
  1850. if( *s == 0 )
  1851. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unexpected end-of-line on dynamics parsing on line:%i.",lineNumb);
  1852. // some dynamic markings are surrounded by parenthesis (to indicate a dynamic level with greater uncertainty)
  1853. if( *s == '(' )
  1854. ++s; // skip the paren.
  1855. if( *s == '!')
  1856. {
  1857. //printf("E %3i %5i %s\n",measNumb,lineNumb,b);
  1858. endForkFl = true;
  1859. ++s;
  1860. }
  1861. if( *s == 0 )
  1862. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unexpected end-of-line on dynamics parsing on line:%i.",lineNumb);
  1863. // check for beg/end fork dynamic
  1864. if( isupper(*s) )
  1865. {
  1866. if( !endForkFl)
  1867. {
  1868. begForkFl=true;
  1869. //printf("B %3i %5i %s\n",measNumb,lineNumb,b);
  1870. }
  1871. }
  1872. else
  1873. {
  1874. if( endForkFl )
  1875. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"A double exclaimation point (end-of-dynamic fork) must always be followed by an upper case M,P, or F. See line:%i",lineNumb);
  1876. }
  1877. unsigned i = 0;
  1878. unsigned j = 0;
  1879. unsigned n = 6;
  1880. bool doneFl = false;
  1881. cmChar_t mark[n+1];
  1882. memset(mark,0,n+1);
  1883. for(i=0; j<n && doneFl==false; ++i)
  1884. {
  1885. char c = tolower(s[i]);
  1886. switch(c)
  1887. {
  1888. case 's':
  1889. case 'm':
  1890. case 'p':
  1891. case 'f':
  1892. case '+':
  1893. case '-':
  1894. mark[j++] = c;
  1895. break;
  1896. case ')': // ending paren.
  1897. case 0: // end of string
  1898. case ' ': // end of mark
  1899. case '\n': // end of line
  1900. default: // anything else
  1901. doneFl = true;
  1902. break;
  1903. }
  1904. }
  1905. if( !doneFl )
  1906. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Illegal dynamic mark (%s) syntax on line:%i.",mark,lineNumb);
  1907. // look up the dynamic mark in the reference table
  1908. for(j=0; _cmXScoreDynMarkArray[j].mark!=NULL; ++j)
  1909. if( strcmp(mark,_cmXScoreDynMarkArray[j].mark) == 0 )
  1910. break;
  1911. if( _cmXScoreDynMarkArray[j].mark == NULL )
  1912. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"The dynamic mark '%s' is not legal on line:%i.",mark,lineNumb);
  1913. *dynIdxRef = j;
  1914. if( begForkFl )
  1915. *flagsRef = cmSetFlag(*flagsRef,kDynBegForkXsFl);
  1916. if( endForkFl )
  1917. *flagsRef = cmSetFlag(*flagsRef,kDynEndForkXsFl);
  1918. return rc;
  1919. }
  1920. cmXsRC_t _cmXScoreReorderParseFlags(cmXScore_t* p, const cmChar_t* b, unsigned line, unsigned* newFlagsRef )
  1921. {
  1922. cmXsRC_t rc = kOkXsRC;
  1923. const cmChar_t* s;
  1924. bool doneFl = false;
  1925. unsigned i = 0;
  1926. *newFlagsRef = 0;
  1927. // tilde indicates a pedal event
  1928. if((s = strchr(b,'~')) == NULL )
  1929. return rc;
  1930. do
  1931. {
  1932. ++s;
  1933. switch( *s )
  1934. {
  1935. case 'd':
  1936. *newFlagsRef |= kSostDnXsFl; // sostenuto pedal down just after this note onset
  1937. break;
  1938. case 'u':
  1939. *newFlagsRef |= kSostUpXsFl; // sostenuto pedal up just before this event
  1940. break;
  1941. case 'x':
  1942. *newFlagsRef |= (kSostUpXsFl | kSostDnXsFl); // sostenuto pedal up just before this event and sost down just after it.
  1943. break;
  1944. case 'D':
  1945. *newFlagsRef |= kDampDnXsFl; // damper pedal down
  1946. break;
  1947. case 'U':
  1948. *newFlagsRef |= kDampUpXsFl; // damper pedal up
  1949. break;
  1950. case '_':
  1951. *newFlagsRef |= kTieEndXsFl; // set tie end flag
  1952. break;
  1953. case '&':
  1954. *newFlagsRef |= kDeleteXsFl; // delete this evetn
  1955. break;
  1956. default:
  1957. if( i == 0 )
  1958. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unexpected flag marking '%c' on line %i.",*s,line);
  1959. doneFl = true;
  1960. }
  1961. ++i;
  1962. }while(!doneFl);
  1963. return rc;
  1964. }
  1965. cmXsRC_t _cmXScoreReorderParseTick(cmXScore_t* p, const cmChar_t* b, unsigned line, unsigned* tickRef )
  1966. {
  1967. cmXsRC_t rc = kOkXsRC;
  1968. const cmChar_t* s;
  1969. if((s = strchr(b,'@')) == NULL )
  1970. return rc;
  1971. ++s;
  1972. if(!isdigit(*s))
  1973. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unexpected tick reorder value '%c' on line %i.",*s,line);
  1974. if(sscanf(s,"%i",tickRef) != 1 )
  1975. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"tick reorder parse failed on line %i.",line);
  1976. return rc;
  1977. }
  1978. cmXsRC_t _cmXScoreReorderParseGrace(cmXScore_t* p, const cmChar_t* b, unsigned line, cmXsReorder_t* r, unsigned* graceGroupIdRef )
  1979. {
  1980. cmXsRC_t rc = kOkXsRC;
  1981. const cmChar_t* s;
  1982. if((s = strchr(b,'%')) == NULL )
  1983. return rc;
  1984. ++s;
  1985. r->graceGroupId = *graceGroupIdRef;
  1986. while(1)
  1987. {
  1988. switch(*s)
  1989. {
  1990. case 'b': r->graceFlags |= kBegGraceXsFl; break;
  1991. case 'a': r->graceFlags |= kAddGraceXsFl | kEndGraceXsFl; break;
  1992. case 's': r->graceFlags |= kSubGraceXsFl | kEndGraceXsFl; break;
  1993. case 'A': r->graceFlags |= kAFirstGraceXsFl| kEndGraceXsFl; break;
  1994. case 'n': r->graceFlags |= kNFirstGraceXsFl| kEndGraceXsFl; break;
  1995. case 'g': break;
  1996. case '1':
  1997. r->graceGroupId += 1;
  1998. ++s;
  1999. continue;
  2000. case '%':
  2001. *graceGroupIdRef += 1;
  2002. ++s;
  2003. continue;
  2004. default:
  2005. {
  2006. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unexpected grace note reorder character code %c on line %i.",*s,line);
  2007. assert(0);
  2008. }
  2009. }
  2010. break;
  2011. }
  2012. return rc;
  2013. }
  2014. cmXsRC_t _cmXScoreReorderParsePitch(cmXScore_t* p, const cmChar_t* b, unsigned line, unsigned* pitchRef )
  2015. {
  2016. cmXsRC_t rc = kOkXsRC;
  2017. cmChar_t* s;
  2018. cmChar_t buf[4];
  2019. unsigned i,j;
  2020. memset(buf,0,sizeof(buf));
  2021. *pitchRef = 0;
  2022. if((s = strchr(b,'$')) == NULL )
  2023. return rc;
  2024. ++s;
  2025. j=2;
  2026. for(i=0; i<j && *s; ++i,++s)
  2027. {
  2028. buf[i] = *s;
  2029. if( i==1 && (*s=='#' || *s=='b') )
  2030. j = 3;
  2031. if( i==0 && strchr("ABCDEFG",*s)==NULL )
  2032. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Illegal pitch letter ('%c')specification line %i.",*s,line);
  2033. if( i==1 && !isdigit(*s) && *s!='#' && *s!='b' )
  2034. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Illegal pitch level ('%c') specification line %i.",*s,line);
  2035. if( i==2 && !isdigit(*s) )
  2036. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Illegal pitch octave ('%c') specification line %i.",*s,line);
  2037. }
  2038. unsigned pitch = cmSciPitchToMidi(buf);
  2039. if( pitch<kInvalidMidiByte)
  2040. *pitchRef = pitch;
  2041. else
  2042. {
  2043. rc = cmErrMsg(&p->err,kSyntaxErrorXsRC,"Pitch conversion from '%s' failed on line %i.",buf,line);
  2044. }
  2045. return rc;
  2046. }
  2047. cmXsRC_t _cmXsApplyEditFile( cmXScore_t* p, const cmChar_t* fn )
  2048. {
  2049. typedef enum { kFindMeasStId, kFindEventStId, kReadEventStId } stateId_t;
  2050. cmXsRC_t rc = kOkXsRC;
  2051. cmFileH_t fH = cmFileNullHandle;
  2052. cmChar_t* b = NULL;
  2053. unsigned bN = 0;
  2054. unsigned ln = 0;
  2055. stateId_t stateId = kFindMeasStId;
  2056. unsigned rN = 1024;
  2057. unsigned ri = 0;
  2058. unsigned measNumb = 0;
  2059. unsigned graceGroupId = 1;
  2060. cmXsReorder_t rV[ rN ];
  2061. if( cmFileOpen(&fH,fn,kReadFileFl,p->err.rpt) != kOkFileRC )
  2062. {
  2063. rc = cmErrMsg(&p->err,kFileFailXsRC,"The reordering file '%s' could not be opened.",cmStringNullGuard(fn));
  2064. return rc;
  2065. }
  2066. for(; cmFileGetLineAuto(fH,&b,&bN)==kOkFileRC; ++ln)
  2067. {
  2068. switch( stateId )
  2069. {
  2070. case kFindEventStId: // scanning past labels to an event line
  2071. {
  2072. unsigned voice,loc;
  2073. if( sscanf(b,"%i %i",&voice,&loc) != 2 )
  2074. continue;
  2075. stateId = kReadEventStId;
  2076. }
  2077. // fall through
  2078. case kReadEventStId:
  2079. {
  2080. cmXsReorder_t r;
  2081. char pitchStr[4];
  2082. memset(&r,0,sizeof(r));
  2083. // parse an event line
  2084. if( sscanf(b,"%i %i %i %i %i %f",&r.idx,&r.voice,&r.locIdx,&r.tick,&r.durtn,&r.rval) == 6 )
  2085. {
  2086. assert( strlen(b)>=52);
  2087. int PC = 39; // text file column where first pitch char occurs
  2088. if( b[PC] == ' ')
  2089. r.midi = 0;
  2090. else
  2091. {
  2092. pitchStr[0] = b[PC+0];
  2093. pitchStr[1] = b[PC+1];
  2094. pitchStr[2] = b[PC+2];
  2095. pitchStr[3] = 0;
  2096. if( !isdigit(pitchStr[2]) )
  2097. r.midi = 0;
  2098. else
  2099. {
  2100. if( pitchStr[1] == ' ')
  2101. {
  2102. pitchStr[1] = pitchStr[2];
  2103. pitchStr[2] = 0;
  2104. }
  2105. r.midi = cmSciPitchToMidi(pitchStr);
  2106. }
  2107. }
  2108. // parse the flag edits following a '~'
  2109. if((rc = _cmXScoreReorderParseFlags(p,b,ln+1, &r.newFlags)) != kOkXsRC )
  2110. goto errLabel;
  2111. // parse the dynamic marking following a '!'
  2112. if((rc = _cmXScoreReorderParseDyn(p,b,ln+1,&r.dynIdx, &r.newFlags, measNumb)) != kOkXsRC )
  2113. goto errLabel;
  2114. // parse the @newtick marker
  2115. if((rc = _cmXScoreReorderParseTick(p, b, ln+1, &r.newTick)) != kOkXsRC )
  2116. goto errLabel;
  2117. // parse the %grace note marker
  2118. if((rc = _cmXScoreReorderParseGrace(p, b, ln+1, &r, &graceGroupId)) != kOkXsRC )
  2119. goto errLabel;
  2120. // parse the $pitch marker
  2121. if((rc = _cmXScoreReorderParsePitch(p, b, ln+1, &r.pitch )) != kOkXsRC )
  2122. goto errLabel;
  2123. // process grace notes - these need to be processed separate from
  2124. // the _cmXScoreReorderMeas() because grace notes may cross measure boundaries.
  2125. /*
  2126. if( r.graceType != 0 )
  2127. {
  2128. r.graceGroupId = graceGroupId;
  2129. // if this is an end of a grace note group
  2130. if( r.graceType != 'g' && r.graceType != 'b' )
  2131. {
  2132. graceGroupId += 1;
  2133. }
  2134. }
  2135. */
  2136. // store the record
  2137. assert( ri < rN );
  2138. rV[ri++] = r;
  2139. continue;
  2140. }
  2141. // the end of the measure was encountered -
  2142. // reorder the measure based on the cmXsReorder_t in rV[ri]
  2143. if((rc = _cmXScoreReorderMeas(p, measNumb, rV, ri )) != kOkXsRC )
  2144. goto errLabel;
  2145. ri = 0;
  2146. stateId = kFindMeasStId;
  2147. // fall through
  2148. }
  2149. case kFindMeasStId: // scanning for a bar-line
  2150. {
  2151. char colon;
  2152. if( sscanf(b,"%i %c",&measNumb,&colon) == 2 && colon == ':' )
  2153. {
  2154. //printf("meas: %i \n",measNumb);
  2155. stateId = kFindEventStId;
  2156. }
  2157. }
  2158. break;
  2159. }
  2160. }
  2161. // If reorder records remain to be processed
  2162. if( ri > 0 )
  2163. if((rc = _cmXScoreReorderMeas(p, measNumb, rV, ri )) != kOkXsRC )
  2164. goto errLabel;
  2165. // the ticks may have changed so the 'secs' and 'dsecs' must be updated
  2166. _cmXScoreSetAbsoluteTime( p );
  2167. // the bar lines should be the first event in the measure
  2168. _cmXScoreFixBarLines(p);
  2169. // resort to force the links to be correct
  2170. _cmXScoreSort(p);
  2171. // process the grace notes.
  2172. _cmXScoreProcessGraceNotes( p, graceGroupId );
  2173. // inserting grace notes may have left the score unsorted
  2174. _cmXScoreSort(p);
  2175. // process the dynamic forks
  2176. _cmXScoreProcessDynamicForks(p);
  2177. //_cmXScoreReport(p, NULL, true );
  2178. errLabel:
  2179. cmFileClose(&fH);
  2180. cmMemFree(b);
  2181. return rc;
  2182. }
  2183. cmXsRC_t cmXScoreInitialize( cmCtx_t* ctx, cmXsH_t* hp, const cmChar_t* xmlFn, const cmChar_t* editFn )
  2184. {
  2185. cmXsRC_t rc = kOkXsRC;
  2186. if((rc = cmXScoreFinalize(hp)) != kOkXsRC )
  2187. return rc;
  2188. cmXScore_t* p = cmMemAllocZ(cmXScore_t,1);
  2189. cmErrSetup(&p->err,&ctx->rpt,"XScore");
  2190. // create a local linked heap
  2191. if( cmLHeapIsValid( p->lhH = cmLHeapCreate(8196,ctx)) == false )
  2192. return cmErrMsg(&p->err,kLHeapFailXsRC,"Lheap create failed.");
  2193. // open the music xml file
  2194. if( cmXmlAlloc(ctx, &p->xmlH, xmlFn) != kOkXmlRC )
  2195. {
  2196. rc = cmErrMsg(&p->err,kXmlFailXsRC,"Unable to open the MusicXML file '%s'.",cmStringNullGuard(xmlFn));
  2197. goto errLabel;
  2198. }
  2199. //cmXmlPrint(p->xmlH,&ctx->rpt);
  2200. // parse the part-list
  2201. if((rc = _cmXScoreParsePartList( p )) != kOkXsRC )
  2202. goto errLabel;
  2203. // parse each score 'part'
  2204. cmXsPart_t* pp = p->partL;
  2205. for(; pp!=NULL; pp=pp->link)
  2206. if((rc = _cmXScoreParsePart(p,pp)) != kOkXsRC )
  2207. goto errLabel;
  2208. // fill in the note->slink chain to link the notes in each measure in time order
  2209. _cmXScoreSort(p);
  2210. // kpl: 4/19/17 fix problem where notes ended up out of order by one tick _cmXScoreSpreadGraceNotes(p);
  2211. _cmXScoreSort(p);
  2212. _cmXScoreResolveTiesAndLoc(p);
  2213. _cmXScoreRemoveDuplicateNotes(p);
  2214. _cmXScoreSetMeasGroups(p,kEvenXsFl);
  2215. _cmXScoreSetMeasGroups(p,kDynXsFl);
  2216. _cmXScoreSetMeasGroups(p,kTempoXsFl);
  2217. //_cmXScoreResolveOctaveShift(p);
  2218. // CSV output initialize failed.
  2219. if( cmCsvInitialize(&p->csvH,ctx) != kOkCsvRC )
  2220. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV output object create failed.");
  2221. if( editFn != NULL )
  2222. {
  2223. if((rc = _cmXsApplyEditFile(p,editFn)) != kOkXsRC )
  2224. {
  2225. cmErrMsg(&ctx->err,rc,"XScore reorder failed.");
  2226. goto errLabel;
  2227. }
  2228. }
  2229. // assign durations to pedal down events
  2230. _cmXScoreProcessPedals(p);
  2231. // remove some notes which share a pitch and are overlapped or embedded within another note.
  2232. _cmXScoreProcessOverlappingNotes(p);
  2233. errLabel:
  2234. if( rc != kOkXsRC )
  2235. _cmXScoreFinalize(p);
  2236. else
  2237. hp->h = p;
  2238. return rc;
  2239. }
  2240. cmXsRC_t cmXScoreFinalize( cmXsH_t* hp )
  2241. {
  2242. cmXsRC_t rc = kOkXsRC;
  2243. if( hp == NULL || cmXScoreIsValid(*hp)==false )
  2244. return kOkXsRC;
  2245. cmXScore_t* p = _cmXScoreHandleToPtr(*hp);
  2246. if((rc = _cmXScoreFinalize(p)) != kOkXsRC )
  2247. return rc;
  2248. hp->h = NULL;
  2249. return rc;
  2250. }
  2251. bool cmXScoreIsValid( cmXsH_t h )
  2252. { return h.h != NULL; }
  2253. /* CSV score columns
  2254. kMidiFileIdColScIdx= 0,
  2255. kTypeLabelColScIdx = 3,
  2256. kDSecsColScIdx = 4,
  2257. kSecsColScIdx = 5,
  2258. kD0ColScIdx = 9,
  2259. kD1ColScIdx = 10,
  2260. kPitchColScIdx = 11,
  2261. kBarColScIdx = 13,
  2262. kSkipColScIdx = 14,
  2263. kEvenColScIdx = 15,
  2264. kGraceColScIdx = 16,
  2265. kTempoColScIdx = 17,
  2266. kFracColScIdx = 18,
  2267. kDynColScIdx = 19,
  2268. kSectionColScIdx = 20,
  2269. kRecdPlayColScIdx = 21,
  2270. kRemarkColScIdx = 22
  2271. */
  2272. cmXsRC_t _cmXScoreWriteCsvHdr( cmXScore_t* p )
  2273. {
  2274. const cmChar_t* s[] =
  2275. {
  2276. "id","trk","evt","opcode","dticks","micros","status",
  2277. "meta","ch","d0","d1","arg0","arg1","bar","skip",
  2278. "even","grace","tempo","t frac","dyn","section","play_recd","remark",NULL
  2279. };
  2280. cmCsvCell_t* lcp = NULL;
  2281. if( cmCsvAppendRow( p->csvH, &lcp, cmCsvInsertSymText(p->csvH,s[0]), 0, 0 ) != kOkCsvRC )
  2282. return cmErrMsg(&p->err,kCsvFailXsRC,"CSV append row failed.");
  2283. unsigned i;
  2284. for(i=1; s[i]!=NULL; ++i)
  2285. {
  2286. if( cmCsvInsertIdentColAfter(p->csvH, lcp, &lcp, s[i], 0 ) != kOkCsvRC )
  2287. return cmErrMsg(&p->err,kCsvFailXsRC,"CSV error inserting CSV title %i.\n",i);
  2288. }
  2289. return kOkXsRC;
  2290. }
  2291. cmXsRC_t _cmXScoreWriteCsvBlankCols( cmXScore_t* p, unsigned cnt, cmCsvCell_t** leftCellPtrPtr )
  2292. {
  2293. unsigned i;
  2294. for(i=0; i<cnt; ++i)
  2295. if( cmCsvInsertIdentColAfter(p->csvH,*leftCellPtrPtr,leftCellPtrPtr,"",0) != kOkCsvRC )
  2296. return cmErrMsg(&p->err,kCsvFailXsRC,"CSV output failed on blank column.");
  2297. return kOkCsvRC;
  2298. }
  2299. const cmChar_t* _cmXScoreTranslateDynamics( cmXScore_t* p, const cmXsNote_t* np, cmChar_t* buf, unsigned bufN )
  2300. {
  2301. if( cmIsFlag(np->flags,kDynXsFl) && np->dynamics != 0 )
  2302. {
  2303. const cmChar_t* dynStr = NULL;
  2304. switch(np->dynamics)
  2305. {
  2306. case 1: dynStr = "pppp"; break;
  2307. case 2: dynStr = "ppp"; break;
  2308. case 3: dynStr = "pp"; break;
  2309. case 4: dynStr = "p"; break;
  2310. case 5: dynStr = "mp"; break;
  2311. case 6: dynStr = "mf"; break;
  2312. case 7: dynStr = "f"; break;
  2313. case 8: dynStr = "ff"; break;
  2314. case 9: dynStr = "fff"; break;
  2315. default:
  2316. cmErrMsg(&p->err,kSyntaxErrorXsRC,"An invalid dynamic value (%i) was encountered.",np->dynamics);
  2317. goto errLabel;
  2318. }
  2319. if( np->dynGroupId == 0 )
  2320. snprintf(buf,bufN,"%s",dynStr);
  2321. else
  2322. snprintf(buf,bufN,"%s %i",dynStr,np->dynGroupId);
  2323. return buf;
  2324. }
  2325. errLabel:
  2326. return "";
  2327. }
  2328. const cmChar_t* cmXsFormatMeasurementCsvField( unsigned flags, unsigned fl, char abbrev, unsigned sectionId, char* buf, unsigned bufN )
  2329. {
  2330. assert( bufN > 1 );
  2331. buf[0] = ' ';
  2332. buf[1] = 0;
  2333. if( cmIsFlag(flags,fl) )
  2334. {
  2335. if( sectionId != 0 )
  2336. snprintf(buf,bufN-1,"%c %i%c",abbrev,sectionId, cmIsFlag(flags,kHeelXsFl)?'*':' ');
  2337. else
  2338. buf[0] = abbrev;
  2339. }
  2340. return buf;
  2341. }
  2342. cmXsRC_t _cmXScoreWriteCsvRow(
  2343. cmXScore_t* p,
  2344. unsigned rowIdx,
  2345. unsigned uid,
  2346. unsigned bar,
  2347. const cmChar_t* sectionStr,
  2348. const cmChar_t* opCodeStr,
  2349. double dsecs,
  2350. double secs,
  2351. unsigned d0,
  2352. unsigned d1,
  2353. unsigned pitch, // set to -1 if the pitch is not valid
  2354. double frac,
  2355. const cmChar_t* dynStr,
  2356. unsigned flags,
  2357. const cmChar_t* evenStr,
  2358. const cmChar_t* tempoStr)
  2359. {
  2360. cmXsRC_t rc = kOkXsRC;
  2361. cmCsvCell_t* lcp = NULL;
  2362. // append an empty row to the CSV object
  2363. if( cmCsvAppendRow( p->csvH, &lcp, cmCsvInsertSymUInt(p->csvH, rowIdx ), 0, 0 ) != kOkCsvRC )
  2364. {
  2365. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV append row failed.");
  2366. goto errLabel;
  2367. }
  2368. /*
  2369. // col 0 : blanks
  2370. if( cmCsvInsertUIntColAfter(p->csvH, lcp, &lcp, rowIdx, 0 ) != kOkCsvRC )
  2371. {
  2372. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV output row index failed.");
  2373. goto errLabel;
  2374. }
  2375. */
  2376. // col 1 : track (always 1)
  2377. if( cmCsvInsertUIntColAfter(p->csvH,lcp,&lcp,1,0) != kOkCsvRC )
  2378. {
  2379. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'd0'.");
  2380. goto errLabel;
  2381. }
  2382. // col 2 : evt (set to event uid, or blank if uid == -1)
  2383. if( uid == -1 )
  2384. {
  2385. if((rc = _cmXScoreWriteCsvBlankCols(p,1,&lcp)) != kOkXsRC )
  2386. goto errLabel;
  2387. }
  2388. else
  2389. if( cmCsvInsertUIntColAfter(p->csvH,lcp,&lcp,uid,0) != kOkCsvRC )
  2390. {
  2391. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'd0'.");
  2392. goto errLabel;
  2393. }
  2394. // col 3 : output the opcode
  2395. if( cmCsvInsertIdentColAfter(p->csvH,lcp,&lcp,opCodeStr,0) != kOkCsvRC )
  2396. {
  2397. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on opcode label.");
  2398. goto errLabel;
  2399. }
  2400. // col 4 : dsecs
  2401. if( cmCsvInsertDoubleColAfter(p->csvH,lcp,&lcp,dsecs,0) != kOkCsvRC )
  2402. {
  2403. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'dsecs'.");
  2404. goto errLabel;
  2405. }
  2406. // col 5 : secs
  2407. if( cmCsvInsertDoubleColAfter(p->csvH,lcp,&lcp,secs,0) != kOkCsvRC )
  2408. {
  2409. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'secs'.");
  2410. goto errLabel;
  2411. }
  2412. // cols 6,7,8 blanks
  2413. if((rc = _cmXScoreWriteCsvBlankCols(p,3,&lcp)) != kOkXsRC )
  2414. goto errLabel;
  2415. // col 9 : d0
  2416. if( cmCsvInsertUIntColAfter(p->csvH,lcp,&lcp,d0,0) != kOkCsvRC )
  2417. {
  2418. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'd0'.");
  2419. goto errLabel;
  2420. }
  2421. // col 10 : d1
  2422. if( cmCsvInsertUIntColAfter(p->csvH,lcp,&lcp,d1,0) != kOkCsvRC )
  2423. {
  2424. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'd1'.");
  2425. goto errLabel;
  2426. }
  2427. // col 11 : pitch
  2428. if( pitch == -1 )
  2429. {
  2430. if((rc = _cmXScoreWriteCsvBlankCols(p,1,&lcp)) != kOkXsRC )
  2431. goto errLabel;
  2432. }
  2433. else
  2434. {
  2435. if( cmCsvInsertIdentColAfter(p->csvH,lcp,&lcp,cmMidiToSciPitch(pitch,NULL,0),0) != kOkCsvRC )
  2436. {
  2437. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'pitch'.");
  2438. goto errLabel;
  2439. }
  2440. }
  2441. // col 12 : blanks
  2442. if((rc = _cmXScoreWriteCsvBlankCols(p,1 + (cmIsFlag(flags,kBarXsFl) ? 0 : 1), &lcp)) != kOkXsRC )
  2443. goto errLabel;
  2444. // col 13 : bar number
  2445. if( cmIsFlag(flags,kBarXsFl) )
  2446. {
  2447. if( cmCsvInsertUIntColAfter(p->csvH,lcp,&lcp,bar,0) != kOkCsvRC )
  2448. {
  2449. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'pitch'.");
  2450. goto errLabel;
  2451. }
  2452. }
  2453. // col 14 : skip (blank for now)
  2454. if((rc = _cmXScoreWriteCsvBlankCols(p,1,&lcp)) != kOkXsRC )
  2455. goto errLabel;
  2456. // col 15: even (all grace notes are 'even' notes
  2457. if( cmCsvInsertQTextColAfter(p->csvH,lcp,&lcp, evenStr, 0) != kOkCsvRC )
  2458. {
  2459. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on eveness flag label.");
  2460. goto errLabel;
  2461. }
  2462. // col 16: grace
  2463. if( cmCsvInsertIdentColAfter(p->csvH,lcp,&lcp,cmIsFlag(flags,kGraceXsFl) ? "g" : "",0) != kOkCsvRC )
  2464. {
  2465. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on eveness flag label.");
  2466. goto errLabel;
  2467. }
  2468. // col 17: tempo
  2469. if( cmCsvInsertQTextColAfter(p->csvH,lcp,&lcp,tempoStr,0) != kOkCsvRC )
  2470. {
  2471. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on eveness flag label.");
  2472. goto errLabel;
  2473. }
  2474. // col 18: frac
  2475. if( frac == 0 )
  2476. {
  2477. if((rc = _cmXScoreWriteCsvBlankCols(p,1,&lcp)) != kOkXsRC )
  2478. goto errLabel;
  2479. }
  2480. else
  2481. {
  2482. if( cmCsvInsertDoubleColAfter(p->csvH,lcp,&lcp,1.0/frac,0) != kOkCsvRC )
  2483. {
  2484. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 't frac'.");
  2485. goto errLabel;
  2486. }
  2487. }
  2488. // col 19: dynamic marking
  2489. if( cmCsvInsertQTextColAfter(p->csvH, lcp, &lcp, dynStr, 0 ) != kOkCsvRC )
  2490. {
  2491. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'dynamics'.");
  2492. goto errLabel;
  2493. }
  2494. //if((rc = _cmXScoreWriteCsvBlankCols(p,1,&lcp)) != kOkXsRC )
  2495. // goto errLabel;
  2496. // col 20: section
  2497. if( cmCsvInsertIdentColAfter(p->csvH,lcp,&lcp,sectionStr!=NULL ? sectionStr : "",0) != kOkCsvRC )
  2498. {
  2499. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on eveness flag label.");
  2500. goto errLabel;
  2501. }
  2502. // col 21, 22 : recd-play, remark (blank for now)
  2503. if((rc = _cmXScoreWriteCsvBlankCols(p,2,&lcp)) != kOkXsRC )
  2504. goto errLabel;
  2505. errLabel:
  2506. return rc;
  2507. }
  2508. cmXsRC_t cmXScoreWriteCsv( cmXsH_t h, int begMeasNumb, const cmChar_t* csvFn )
  2509. {
  2510. cmXsRC_t rc = kOkXsRC;
  2511. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  2512. unsigned rowIdx = 1;
  2513. const cmChar_t* sectionIdStr = NULL;
  2514. double baseSecs = -1;
  2515. if( !cmCsvIsValid(p->csvH) )
  2516. return cmErrMsg(&p->err,kCsvFailXsRC,"The CSV output object is not initialized.");
  2517. if((rc = _cmXScoreWriteCsvHdr( p )) != kOkXsRC )
  2518. goto errLabel;
  2519. cmXsPart_t* pp = p->partL;
  2520. for(; pp!=NULL; pp=pp->link)
  2521. {
  2522. cmXsMeas_t* mp = pp->measL;
  2523. for(; mp!=NULL; mp=mp->link)
  2524. {
  2525. if( mp->number < begMeasNumb)
  2526. continue;
  2527. cmXsNote_t* np = mp->noteL;
  2528. if( baseSecs == -1 )
  2529. baseSecs = np->secs;
  2530. for(; np!=NULL; np=np->slink)
  2531. {
  2532. double thisSecs = np->secs - baseSecs;
  2533. // if this is a section event
  2534. if( cmIsFlag(np->flags,kSectionXsFl) )
  2535. sectionIdStr = np->tvalue;
  2536. // if this is a bar event
  2537. if( cmIsFlag(np->flags,kBarXsFl) )
  2538. {
  2539. _cmXScoreWriteCsvRow(p,rowIdx,-1,mp->number,sectionIdStr,"bar",np->dsecs,thisSecs,0,0,-1,0,"",np->flags,"","");
  2540. sectionIdStr = NULL;
  2541. }
  2542. else
  2543. {
  2544. // if this is a pedal event
  2545. if( cmIsFlag(np->flags,kDampDnXsFl|kDampUpXsFl|kDampUpDnXsFl|kSostDnXsFl|kSostUpXsFl) )
  2546. {
  2547. unsigned d0 = cmIsFlag(np->flags,kSostDnXsFl |kSostUpXsFl) ? 66 : 64; // pedal MIDI ctl id
  2548. unsigned d1 = cmIsFlag(np->flags,kDampDnXsFl|kSostDnXsFl) ? 64 : 0; // pedal-dn: d1>=64 pedal-up:<64
  2549. _cmXScoreWriteCsvRow(p,rowIdx,-1,mp->number,sectionIdStr,"ctl",np->dsecs,thisSecs,d0,d1,-1,0,"",np->flags,"","");
  2550. sectionIdStr = NULL;
  2551. if( cmIsFlag(np->flags,kDampUpDnXsFl) )
  2552. {
  2553. rowIdx += 1;
  2554. double millisecond = 0.0;
  2555. _cmXScoreWriteCsvRow(p,rowIdx,-1,mp->number,sectionIdStr,"ctl",millisecond,thisSecs+millisecond,d0,64,-1,0,"",np->flags,"","");
  2556. }
  2557. }
  2558. else
  2559. {
  2560. // if this is a sounding note event
  2561. if( cmIsFlag(np->flags,kOnsetXsFl) )
  2562. {
  2563. unsigned bufN = 128;
  2564. cmChar_t ebuf[ bufN+1]; ebuf[bufN] = 0;
  2565. cmChar_t dbuf[ bufN+1]; dbuf[bufN] = 0;
  2566. cmChar_t tbuf[ bufN+1]; tbuf[bufN] = 0;
  2567. double frac = np->rvalue + (cmIsFlag(np->flags,kDotXsFl) ? (np->rvalue/2) : 0);
  2568. const cmChar_t* dyn = _cmXScoreTranslateDynamics( p, np, dbuf, bufN );
  2569. unsigned vel = np->vel==0 ? 60 : np->vel;
  2570. //
  2571. _cmXScoreWriteCsvRow(p,rowIdx,np->uid,mp->number,sectionIdStr,"non",np->dsecs,thisSecs,np->pitch,vel,np->pitch,frac,dyn,np->flags,
  2572. cmXsFormatMeasurementCsvField(np->flags, kEvenXsFl, 'e', np->evenGroupId, ebuf, bufN ),
  2573. cmXsFormatMeasurementCsvField(np->flags, kTempoXsFl,'t', np->tempoGroupId, tbuf, bufN ));
  2574. sectionIdStr = NULL;
  2575. }
  2576. }
  2577. }
  2578. rowIdx += 1;
  2579. }
  2580. }
  2581. }
  2582. // Section labels are output on the next bar/pedal/note
  2583. // but what if there is no bar pedal note-on after the section label
  2584. if( sectionIdStr != NULL )
  2585. cmErrMsg(&p->err,kSyntaxErrorXsRC,"The section label '%s' was ignored because it was not followed by a score event.",sectionIdStr);
  2586. if( cmCsvWrite( p->csvH, csvFn ) != kOkCsvRC )
  2587. rc = cmErrMsg(&p->err,kCsvFailXsRC,"The CSV output write failed on file '%s'.",csvFn);
  2588. errLabel:
  2589. return rc;
  2590. }
  2591. bool _cmXsIsCsvValid(cmCtx_t* ctx, cmXsH_t h, const cmChar_t* outFn)
  2592. {
  2593. bool retFl = true;
  2594. cmScH_t scH = cmScNullHandle;
  2595. double srate = 44100.0;
  2596. cmSymTblH_t stH = cmSymTblCreate(cmSymTblNullHandle, 0, ctx );
  2597. if( cmScoreInitialize( ctx, &scH, outFn, srate, NULL, 0, NULL, NULL, stH) != kOkScRC )
  2598. {
  2599. cmErrMsg(&ctx->err,kFileFailXsRC,"The generated CSV file (%s) could not be parsed.",cmStringNullGuard(outFn));
  2600. retFl = false;
  2601. }
  2602. else
  2603. {
  2604. //cmScorePrintSets(scH,&ctx->rpt);
  2605. //cmScorePrint(scH,&ctx->rpt);
  2606. cmScoreFinalize(&scH);
  2607. }
  2608. cmSymTblDestroy(&stH);
  2609. return retFl;
  2610. }
  2611. void _cmXScoreReportTitle( cmRpt_t* rpt )
  2612. {
  2613. cmRptPrintf(rpt," idx voc loc tick durtn rval flags\n");
  2614. cmRptPrintf(rpt," --- --- ----- ------- ----- ---- --- ---------------\n");
  2615. }
  2616. void _cmXScoreReportNote( cmRpt_t* rpt, const cmXsNote_t* note,unsigned index )
  2617. {
  2618. const cmChar_t* B = cmIsFlag(note->flags,kBarXsFl) ? "|" : "-";
  2619. const cmChar_t* R = cmIsFlag(note->flags,kRestXsFl) ? "R" : "-";
  2620. const cmChar_t* G = cmIsFlag(note->flags,kGraceXsFl) ? "G" : "-";
  2621. const cmChar_t* D = cmIsFlag(note->flags,kDotXsFl) ? "." : "-";
  2622. const cmChar_t* C = cmIsFlag(note->flags,kChordXsFl) ? "C" : "-";
  2623. const cmChar_t* P = cmIsFlag(note->flags,kDampDnXsFl) ? "V" : "-";
  2624. const cmChar_t* s = cmIsFlag(note->flags,kSostDnXsFl) ? "{" : "-";
  2625. const cmChar_t* S = cmIsFlag(note->flags,kSectionXsFl) ? "S" : "-";
  2626. const cmChar_t* H = cmIsFlag(note->flags,kHeelXsFl) ? "H" : "-";
  2627. const cmChar_t* T0 = cmIsFlag(note->flags,kTieBegXsFl) ? "T" : "-";
  2628. const cmChar_t* T1 = cmIsFlag(note->flags,kTieEndXsFl) ? "_" : "-";
  2629. const cmChar_t* O = cmIsFlag(note->flags,kOnsetXsFl) ? "*" : "-";
  2630. const cmChar_t* e = cmIsFlag(note->flags,kEvenXsFl) ? "e" : "-";
  2631. const cmChar_t* d = cmIsFlag(note->flags,kDynXsFl) ? "d" : "-";
  2632. const cmChar_t* t = cmIsFlag(note->flags,kTempoXsFl) ? "t" : "-";
  2633. if( cmIsFlag(note->flags,kEvenEndXsFl) ) e="E";
  2634. if( cmIsFlag(note->flags,kDynEndXsFl) ) d="D";
  2635. if( cmIsFlag(note->flags,kTempoEndXsFl) ) t="T";
  2636. P = cmIsFlag(note->flags,kDampUpXsFl) ? "^" : P;
  2637. P = cmIsFlag(note->flags,kDampUpDnXsFl) ? "X" : P;
  2638. s = cmIsFlag(note->flags,kSostUpXsFl) ? "}" : s;
  2639. //const cmChar_t* N = note->pitch==0 ? " " : cmMidiToSciPitch( note->pitch, NULL, 0 );
  2640. cmChar_t N[] = {'\0','\0','\0','\0'};
  2641. cmChar_t acc = note->alter==-1?'b':(note->alter==1?'#':' ');
  2642. snprintf(N,4,"%c%c%1i",note->step,acc,note->octave);
  2643. cmRptPrintf(rpt," %3i %3i %5i %7i %5i %4.1f %3s %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
  2644. index,
  2645. note->voice->id,
  2646. note->locIdx,
  2647. note->tick,
  2648. note->tied_dur,
  2649. note->rvalue,
  2650. N,B,R,G,D,C,e,d,t,P,s,S,H,T0,T1,O);
  2651. if( cmIsFlag(note->flags,kSectionXsFl) )
  2652. cmRptPrintf(rpt," %s",cmStringNullGuard(note->tvalue));
  2653. if( cmIsFlag(note->flags,kMetronomeXsFl) )
  2654. cmRptPrintf(rpt," %i bpm",note->duration);
  2655. if( note->evenGroupId != 0 )
  2656. cmRptPrintf(rpt," e=%i",note->evenGroupId);
  2657. if( note->dynGroupId != 0 )
  2658. cmRptPrintf(rpt," d=%i",note->dynGroupId);
  2659. if( note->tempoGroupId != 0 )
  2660. cmRptPrintf(rpt," t=%i",note->tempoGroupId);
  2661. if( note->graceGroupId != 0)
  2662. cmRptPrintf(rpt," g=%i",note->graceGroupId);
  2663. if( note->dynamics != 0)
  2664. cmRptPrintf(rpt," dyn=%i %i",note->dynamics,note->vel);
  2665. /*
  2666. if( cmIsFlag(note->flags,kBegGraceXsFl) )
  2667. cmRptPrintf(rpt," B");
  2668. if( cmIsFlag(note->flags,kEndGraceXsFl) )
  2669. cmRptPrintf(rpt," E");
  2670. if( cmIsFlag(note->flags,kDynBegForkXsFl) )
  2671. cmRptPrintf(rpt," B");
  2672. if( cmIsFlag(note->flags,kDynEndForkXsFl) )
  2673. cmRptPrintf(rpt," E");
  2674. */
  2675. }
  2676. void _cmXScoreReport( cmXScore_t* p, cmRpt_t* rpt, bool sortFl )
  2677. {
  2678. if( rpt == NULL )
  2679. rpt = p->err.rpt;
  2680. cmXsPart_t* pp = p->partL;
  2681. for(; pp!=NULL; pp=pp->link)
  2682. {
  2683. cmRptPrintf(rpt,"Part:%s\n",pp->idStr);
  2684. const cmXsMeas_t* meas = pp->measL;
  2685. for(; meas!=NULL; meas=meas->link)
  2686. {
  2687. unsigned idx = 0;
  2688. cmRptPrintf(rpt," %i : div:%i beat:%i beat-type:%i (%i)\n",meas->number,meas->divisions,meas->beats,meas->beat_type,meas->divisions*meas->beats);
  2689. _cmXScoreReportTitle(rpt);
  2690. if( sortFl )
  2691. {
  2692. const cmXsNote_t* note = meas->noteL;
  2693. unsigned t0 = 0;
  2694. unsigned t1 = 0;
  2695. for(; note!=NULL; note=note->slink,++idx)
  2696. {
  2697. _cmXScoreReportNote(rpt,note,idx);
  2698. t1 = note->slink==NULL ? note->tick : note->slink->tick;
  2699. if( !(t0 <= note->tick && note->tick <= t1) )
  2700. {
  2701. cmRptPrintf(rpt," +");
  2702. }
  2703. t0 = note->tick;
  2704. if( note->slink!=NULL || note->voice->id==0)
  2705. cmRptPrintf(rpt,"\n");
  2706. else
  2707. cmRptPrintf(rpt," %i\n", note->tick + note->duration);
  2708. }
  2709. }
  2710. else
  2711. {
  2712. const cmXsVoice_t* v = meas->voiceL;
  2713. for(; v!=NULL; v=v->link)
  2714. {
  2715. const cmXsNote_t* note = v->noteL;
  2716. cmRptPrintf(rpt," voice:%i\n",v->id);
  2717. for(; note!=NULL; note=note->mlink)
  2718. {
  2719. _cmXScoreReportNote(rpt,note,idx);
  2720. if( note->mlink!=NULL || note->voice->id==0)
  2721. cmRptPrintf(rpt,"\n");
  2722. else
  2723. cmRptPrintf(rpt," %i\n", note->tick + note->duration);
  2724. }
  2725. }
  2726. }
  2727. }
  2728. }
  2729. }
  2730. void cmXScoreReport( cmXsH_t h, cmRpt_t* rpt, bool sortFl )
  2731. {
  2732. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  2733. return _cmXScoreReport(p,rpt,sortFl);
  2734. }
  2735. void _cmXScoreGenEditFileWrite( void* arg, const cmChar_t* text )
  2736. {
  2737. if( text != NULL && arg != NULL )
  2738. {
  2739. cmFileH_t* hp = (cmFileH_t*)arg;
  2740. cmFilePrint(*hp,text);
  2741. }
  2742. }
  2743. cmXsRC_t cmXScoreGenEditFile( cmCtx_t* ctx, const cmChar_t* xmlFn, const cmChar_t* outFn )
  2744. {
  2745. cmXsH_t xsH = cmXsNullHandle;
  2746. cmFileH_t fH = cmFileNullHandle;
  2747. cmXsRC_t rc = kOkXsRC;
  2748. cmErr_t err;
  2749. cmRpt_t rpt;
  2750. cmErrSetup(&err,&ctx->rpt,"cmXScoreGenEditFile");
  2751. cmRptSetup(&rpt,_cmXScoreGenEditFileWrite,_cmXScoreGenEditFileWrite,&fH);
  2752. if((rc = cmXScoreInitialize(ctx,&xsH,xmlFn,NULL)) != kOkXsRC )
  2753. return rc;
  2754. if( cmFileOpen(&fH,outFn,kWriteFileFl,&ctx->rpt) != kOkFileRC )
  2755. {
  2756. cmErrMsg(&err,kFileFailXsRC,"Unable to open the output file '%s'.",cmStringNullGuard(outFn));
  2757. goto errLabel;
  2758. }
  2759. cmXScoreReport(xsH,&rpt,true);
  2760. errLabel:
  2761. if( cmFileClose(&fH) != kOkFileRC )
  2762. rc = cmErrMsg(&err,kFileFailXsRC,"File close failed on '%s'.",cmStringNullGuard(outFn));
  2763. cmXScoreFinalize(&xsH);
  2764. return rc;
  2765. }
  2766. typedef struct
  2767. {
  2768. unsigned ival;
  2769. double fval;
  2770. unsigned cnt;
  2771. } cmXsHist_t;
  2772. void _cmXsHistUpdateI( cmXsHist_t* hist, unsigned histN, unsigned ival )
  2773. {
  2774. unsigned i;
  2775. for(i=0; i<histN && hist[i].cnt!=0; ++i)
  2776. if( hist[i].ival == ival )
  2777. break;
  2778. if( i==histN )
  2779. return;
  2780. hist[i].ival = ival;
  2781. hist[i].cnt += 1;
  2782. }
  2783. void _cmXsHistUpdateF( cmXsHist_t* hist, unsigned histN, double fval )
  2784. {
  2785. unsigned i;
  2786. for(i=0; i<histN && hist[i].cnt!=0; ++i)
  2787. if( hist[i].fval == fval )
  2788. break;
  2789. if( i==histN )
  2790. return;
  2791. hist[i].fval = fval;
  2792. hist[i].cnt += 1;
  2793. }
  2794. unsigned _cmXsHistValue( cmXsHist_t* hist, unsigned histN )
  2795. {
  2796. unsigned i,n;
  2797. for(i=0,n=0; i<histN && hist[i].cnt>0; ++i)
  2798. n += 1;
  2799. return n;
  2800. }
  2801. // Measure the score complexity for the the time window 'wndSecs' seconds
  2802. // prior to the note n1 and following n0.
  2803. const cmXsNote_t* _cmXsMeasComplexityInWindow( const cmXsNote_t* n0, cmXsNote_t* n1, double wndSecs )
  2804. {
  2805. const cmXsNote_t* n2 = NULL;
  2806. unsigned l_pch_0 = 0;
  2807. unsigned l_pch_value = 0;
  2808. unsigned l_pch_cnt = n1->staff==1 ? 0 : 1;
  2809. unsigned r_pch_0 = n1->staff==1 ? 1 : 0;
  2810. unsigned r_pch_value = 0;
  2811. unsigned r_pch_cnt = 0;
  2812. unsigned i = 0;
  2813. unsigned histN = 100;
  2814. cmXsHist_t velHist[ histN ];
  2815. cmXsHist_t rymHist[ histN ];
  2816. memset(velHist,0,sizeof(velHist));
  2817. memset(rymHist,0,sizeof(rymHist));
  2818. const cmXsNote_t* n = n0;
  2819. while(n!=NULL && n != n1)
  2820. {
  2821. // if this event is less than wndSecs behind 'n1' and is not a sounding note ...
  2822. if( n1->secs - n->secs <= wndSecs && cmIsFlag(n->flags,kOnsetXsFl) )
  2823. {
  2824. _cmXsHistUpdateI( velHist, histN, n->dynamics );
  2825. _cmXsHistUpdateF( rymHist, histN, n->rvalue );
  2826. switch( n->staff )
  2827. {
  2828. case 1: // treble cleff
  2829. if( i > 0 )
  2830. {
  2831. r_pch_value += r_pch_0 > n->pitch ? r_pch_0-n->pitch : n->pitch-r_pch_0;
  2832. r_pch_cnt += 1;
  2833. }
  2834. r_pch_0 = n->pitch;
  2835. break;
  2836. case 2: // bass cleff
  2837. if( i > 0 )
  2838. {
  2839. l_pch_value += l_pch_0 > n->pitch ? l_pch_0-n->pitch : n->pitch-l_pch_0;
  2840. l_pch_cnt += 1;
  2841. }
  2842. l_pch_0 = n->pitch;
  2843. break;
  2844. default:
  2845. { assert(0); }
  2846. }
  2847. // track the first note that is inside the window
  2848. if( i == 0 )
  2849. n2 = n;
  2850. // count the number of notes in the window
  2851. i += 1;
  2852. }
  2853. cmXsMeas_t* m = n->meas;
  2854. // advance th note pointer
  2855. n = n->slink;
  2856. // if we have reached the end of a measure
  2857. if( n == NULL )
  2858. {
  2859. if( m != NULL )
  2860. {
  2861. m = m->link;
  2862. if( m != NULL )
  2863. n = m->noteL;
  2864. }
  2865. }
  2866. }
  2867. // update the cplx record in n1 with the results of this window analysis
  2868. n1->cplx.sum_d_vel = _cmXsHistValue( velHist, histN );
  2869. n1->cplx.sum_d_rym = _cmXsHistValue( rymHist, histN );
  2870. n1->cplx.sum_d_lpch = l_pch_value;
  2871. n1->cplx.sum_n_lpch = l_pch_cnt;
  2872. n1->cplx.sum_d_rpch = r_pch_value;
  2873. n1->cplx.sum_n_rpch = r_pch_cnt;
  2874. return n2;
  2875. }
  2876. // Measure the score complexity and fill in the cmXsComplexity_t record associated
  2877. // with the cmXsNote_t record of each sounding note.
  2878. cmXsRC_t _cmXsMeasComplexity( cmXsH_t h, double wndSecs )
  2879. {
  2880. cmXsRC_t rc = kOkXsRC;
  2881. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  2882. cmXsPart_t* pp = p->partL;
  2883. memset(&p->cplx_max,0,sizeof(p->cplx_max));
  2884. const cmXsNote_t* n0 = NULL;
  2885. // for each part
  2886. for(; pp!=NULL; pp=pp->link)
  2887. {
  2888. cmXsMeas_t* mp = pp->measL;
  2889. // for each measure
  2890. for(; mp!=NULL; mp=mp->link)
  2891. {
  2892. cmXsNote_t* n1 = mp->noteL;
  2893. // for each note in this measure
  2894. for(; n1!=NULL; n1=n1->slink)
  2895. if( cmIsFlag(n1->flags,kOnsetXsFl) )
  2896. {
  2897. if( n0 == NULL )
  2898. n0 = n1;
  2899. else
  2900. if((n0 = _cmXsMeasComplexityInWindow(n0,n1,wndSecs)) == NULL )
  2901. n0 = n1;
  2902. // track the max value for all complexity values to allow
  2903. // eventual normalization of the complexity values
  2904. p->cplx_max.sum_d_vel = cmMax(p->cplx_max.sum_d_vel, n1->cplx.sum_d_vel);
  2905. p->cplx_max.sum_d_rym = cmMax(p->cplx_max.sum_d_rym, n1->cplx.sum_d_rym);
  2906. p->cplx_max.sum_d_lpch = cmMax(p->cplx_max.sum_d_lpch,n1->cplx.sum_d_lpch);
  2907. p->cplx_max.sum_n_lpch = cmMax(p->cplx_max.sum_n_lpch,n1->cplx.sum_n_lpch);
  2908. p->cplx_max.sum_d_rpch = cmMax(p->cplx_max.sum_d_rpch,n1->cplx.sum_d_rpch);
  2909. p->cplx_max.sum_n_rpch = cmMax(p->cplx_max.sum_n_rpch,n1->cplx.sum_n_rpch);
  2910. }
  2911. }
  2912. }
  2913. return rc;
  2914. }
  2915. cmXsRC_t _cmXsWriteMidiFile( cmCtx_t* ctx, cmXsH_t h, int beginMeasNumb, int beginBPM, const cmChar_t* dir, const cmChar_t* fn )
  2916. {
  2917. cmXsRC_t rc = kOkXsRC;
  2918. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  2919. if( p->partL==NULL || p->partL->measL == NULL )
  2920. return rc;
  2921. cmMidiFileH_t mfH = cmMidiFileNullHandle;
  2922. unsigned trkN = 2;
  2923. unsigned ticksPerQN = p->partL->measL->divisions;
  2924. const cmChar_t* outFn = cmFsMakeFn(dir,fn,"mid",NULL);
  2925. unsigned baseTick = -1;
  2926. unsigned bpm = beginBPM==0 ? 60 : beginBPM;
  2927. //if( cmMidiFileCreate( ctx, &mfH, trkN, ticksPerQN ) != kOkMfRC )
  2928. // return cmErrMsg(&p->err,kMidiFailXsRC,"Unable to create the MIDI file object.");
  2929. cmXsPart_t* pp = p->partL;
  2930. // for each part
  2931. for(; pp!=NULL; pp=pp->link)
  2932. {
  2933. cmXsMeas_t* mp = pp->measL;
  2934. // for each measure
  2935. for(; mp!=NULL; mp=mp->link)
  2936. {
  2937. // skip all measures until we reach the first measure to output
  2938. if(mp->number < beginMeasNumb)
  2939. continue;
  2940. // if the MIDI file has not yet been created
  2941. if( !cmMidiFileIsValid(mfH) )
  2942. {
  2943. ticksPerQN = mp->divisions;
  2944. // create the MIDI file
  2945. if( cmMidiFileCreate( ctx, &mfH, trkN, ticksPerQN ) != kOkMfRC )
  2946. {
  2947. rc = cmErrMsg(&p->err,kMidiFailXsRC,"Unable to create the MIDI file object.");
  2948. goto errLabel;
  2949. }
  2950. // set the starting tempo
  2951. cmMidFileInsertTrackTempoMsg(mfH, 0, 0, bpm );
  2952. }
  2953. cmXsNote_t* np = mp->noteL;
  2954. if( baseTick == -1 )
  2955. baseTick = np->tick;
  2956. if( mp->divisions != ticksPerQN )
  2957. cmErrWarnMsg(&p->err,kMidiFailXsRC,"The 'tick per quarter note' (divisions) field in measure %i does not match the value in the first measure (%i).",mp->divisions,ticksPerQN);
  2958. unsigned ni = 0;
  2959. // for each note in this measure
  2960. for(; np!=NULL; np=np->slink,++ni)
  2961. {
  2962. unsigned thisTick = np->tick - baseTick;
  2963. switch( np->flags & (kOnsetXsFl|kMetronomeXsFl|kDampDnXsFl|kDampUpDnXsFl|kSostDnXsFl) )
  2964. {
  2965. case kOnsetXsFl:
  2966. if( cmMidiFileIsValid(mfH) )
  2967. {
  2968. if( np->tied_dur <= 0 )
  2969. cmErrWarnMsg(&p->err,kOkXsRC,"A zero length note was encountered bar:%i tick:%i (%i) %s",np->meas->number,np->tick,thisTick,cmMidiToSciPitch(np->pitch,NULL,0));
  2970. /*
  2971. if( mp->number == 20 )
  2972. {
  2973. _cmXScoreReportNote(ctx->err.rpt,np,ni);
  2974. cmRptPrintf(ctx->err.rpt,"\n");
  2975. }
  2976. */
  2977. if( np->vel == 0 )
  2978. cmErrWarnMsg(&p->err,kOkXsRC,"A sounding note with zero velocity was encountered at bar:%i tick:%i pitch:%s.",np->meas->number,np->tick,cmMidiToSciPitch(np->pitch,NULL,0));
  2979. if( cmMidiFileInsertTrackChMsg(mfH, 1, thisTick, kNoteOnMdId, np->pitch, np->vel ) != kOkMfRC
  2980. ||cmMidiFileInsertTrackChMsg(mfH, 1, thisTick + np->tied_dur, kNoteOffMdId, np->pitch, 0 ) != kOkMfRC )
  2981. {
  2982. rc = kMidiFailXsRC;
  2983. }
  2984. }
  2985. break;
  2986. case kDampDnXsFl:
  2987. case kDampUpDnXsFl:
  2988. case kSostDnXsFl:
  2989. if( cmMidiFileIsValid(mfH) )
  2990. {
  2991. if( np->duration <= 0 )
  2992. cmErrWarnMsg(&p->err,kOkXsRC,"A zero length pedal event was encountered bar:%i tick:%i (%i)",np->meas->number,np->tick,thisTick);
  2993. cmMidiByte_t d0 = cmIsFlag(np->flags,kSostDnXsFl) ? kSostenutoCtlMdId : kSustainCtlMdId;
  2994. if( (cmMidiFileInsertTrackChMsg(mfH, 1, thisTick, kCtlMdId, d0, 127 ) != kOkMfRC )
  2995. ||(cmMidiFileInsertTrackChMsg(mfH, 1, thisTick + np->duration, kCtlMdId, d0, 0 ) != kOkMfRC ) )
  2996. {
  2997. rc = kMidiFailXsRC;
  2998. }
  2999. }
  3000. break;
  3001. case kMetronomeXsFl:
  3002. bpm = np->duration;
  3003. if( cmMidiFileIsValid(mfH) )
  3004. if( cmMidFileInsertTrackTempoMsg(mfH, 0, thisTick, bpm ) != kOkMfRC )
  3005. rc = kMidiFailXsRC;
  3006. break;
  3007. case 0:
  3008. break;
  3009. default:
  3010. { assert(0); }
  3011. }
  3012. if( rc != kOkXsRC )
  3013. {
  3014. rc = cmErrMsg(&p->err,rc,"MIDI message insert failed on '%s'.",cmStringNullGuard(outFn));
  3015. goto errLabel;
  3016. }
  3017. }
  3018. }
  3019. }
  3020. if( cmMidiFileIsValid(mfH) )
  3021. if( cmMidiFileWrite(mfH,outFn) != kOkMfRC )
  3022. {
  3023. rc = cmErrMsg(&p->err,kMidiFailXsRC,"MIDI file write failed on '%s'.",cmStringNullGuard(outFn));
  3024. goto errLabel;
  3025. }
  3026. errLabel:
  3027. cmFsFreeFn(outFn);
  3028. if( cmMidiFileClose(&mfH) != kOkMfRC )
  3029. {
  3030. rc = cmErrMsg(&p->err,kMidiFailXsRC,"Unable to create the MIDI file object.");
  3031. goto errLabel;
  3032. }
  3033. return rc;
  3034. }
  3035. bool _cmXsIsMidiFileValid( cmCtx_t* ctx, cmXsH_t h, const cmChar_t* dir, const cmChar_t* fn )
  3036. {
  3037. const cmChar_t* midiFn = cmFsMakeFn(dir,fn,"mid",NULL);
  3038. cmMidiFileH_t mfH = cmMidiFileNullHandle;
  3039. if( cmMidiFileOpen( ctx, &mfH, midiFn ) == kOkMfRC )
  3040. {
  3041. cmMidiFileClose(&mfH);
  3042. return true;
  3043. }
  3044. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  3045. cmErrMsg(&p->err,kMidiFailXsRC,"The generated MIDI file '%s' is not valid.", cmStringNullGuard(midiFn));
  3046. return false;
  3047. }
  3048. typedef struct cmXsSvgEvt_str
  3049. {
  3050. unsigned flags; // k???XsFl
  3051. unsigned tick; // start tick
  3052. unsigned durTicks; // dur-ticks
  3053. unsigned voice; // score voice number
  3054. unsigned d0; // MIDI d0 (barNumb)
  3055. unsigned d1; // MIDI d1
  3056. cmXsComplexity_t cplx;
  3057. struct cmXsSvgEvt_str* link;
  3058. } cmXsSvgEvt_t;
  3059. typedef struct cmXsMidiFile_str
  3060. {
  3061. cmXsSvgEvt_t* elist;
  3062. cmXsSvgEvt_t* eol;
  3063. unsigned pitch_min;
  3064. unsigned pitch_max;
  3065. } cmXsMidiFile_t;
  3066. void _cmXsWriteMidiSvgLegend( cmSvgH_t svgH, unsigned index, const cmChar_t* label, const cmChar_t* classStr )
  3067. {
  3068. double x = 100;
  3069. double y = 120*10 - 20*index;
  3070. cmSvgWriterText( svgH, x, y, label, "legend" );
  3071. x += 75;
  3072. cmSvgWriterLine( svgH, x, y, x+125, y, classStr );
  3073. }
  3074. void _cmXsWriteMidiSvgLinePoint( cmSvgH_t svgH, double x0, double y0, double x1, double y1, double y_max, const cmChar_t* classStr, const cmChar_t* label )
  3075. {
  3076. int bn = 255;
  3077. char b[bn+1];
  3078. double y_scale = 10;
  3079. double y_label = y1;
  3080. b[0] = 0;
  3081. y0 = (y0/y_max) * 127.0 * y_scale;
  3082. y1 = (y1/y_max) * 127.0 * y_scale;
  3083. cmSvgWriterLine(svgH, x0, y0, x1, y1, classStr );
  3084. if( y0 != y1 )
  3085. snprintf(b,bn,"%5.0f %s",y_label,label==NULL?"":label);
  3086. else
  3087. {
  3088. if( label != NULL )
  3089. snprintf(b,bn,"%s",label);
  3090. }
  3091. if( strlen(b) )
  3092. cmSvgWriterText(svgH, x1, y1, b, "pt_text");
  3093. }
  3094. cmXsRC_t _cmXsWriteMidiSvg( cmCtx_t* ctx, cmXScore_t* p, cmXsMidiFile_t* mf, const cmChar_t* svgFn, bool standAloneFl, bool panZoomFl )
  3095. {
  3096. cmXsRC_t rc = kOkXsRC;
  3097. cmSvgH_t svgH = cmSvgNullHandle;
  3098. cmXsSvgEvt_t* e = mf->elist;
  3099. unsigned noteHeight = 10;
  3100. //cmChar_t* fn0 = cmMemAllocStr( fn );
  3101. //const cmChar_t* svgFn = cmFsMakeFn(dir,fn0 = cmTextAppendSS(fn0,"_midi_svg"),"html",NULL);
  3102. const cmChar_t* cssFn = cmFsMakeFn(NULL,"score_midi_svg","css",NULL);
  3103. cmChar_t* t0 = NULL; // temporary dynamic string
  3104. unsigned i = 0;
  3105. const cmXsSvgEvt_t* e0 = NULL;
  3106. //cmMemFree(fn0);
  3107. // create the SVG writer
  3108. if( cmSvgWriterAlloc(ctx,&svgH) != kOkSvgRC )
  3109. {
  3110. rc = cmErrMsg(&p->err,kSvgFailXsRC,"Unable to create the MIDI SVG output file '%s'.",cmStringNullGuard(svgFn));
  3111. goto errLabel;
  3112. }
  3113. _cmXsWriteMidiSvgLegend( svgH, 0, "Velocity", "cplx_vel" );
  3114. _cmXsWriteMidiSvgLegend( svgH, 1, "Duration", "cplx_rym" );
  3115. _cmXsWriteMidiSvgLegend( svgH, 2, "Left Pitch", "cplx_lpch" );
  3116. _cmXsWriteMidiSvgLegend( svgH, 3, "Right Pitch", "cplx_rpch" );
  3117. _cmXsWriteMidiSvgLegend( svgH, 4, "Density", "cplx_density" );
  3118. // for each MIDI file element
  3119. for(; e!=NULL && rc==kOkXsRC; e=e->link)
  3120. {
  3121. switch( e->flags & (kOnsetXsFl|kBarXsFl|kDampDnXsFl|kDampUpDnXsFl|kSostDnXsFl))
  3122. {
  3123. // if this is a note
  3124. case kOnsetXsFl:
  3125. {
  3126. //const cmChar_t* classLabel = "note";
  3127. t0 = cmTsPrintfP(t0,"note_%i%s",e->voice, cmIsFlag(e->flags,kGraceXsFl) ? "_g":"");
  3128. //if( cmIsFlag(e->flags,kGraceXsFl) )
  3129. // classLabel = "grace";
  3130. if( cmSvgWriterRect(svgH, e->tick, e->d0 * noteHeight, e->durTicks, noteHeight-1, t0 ) != kOkSvgRC )
  3131. rc = kSvgFailXsRC;
  3132. else
  3133. {
  3134. t0 = cmTsPrintfP(t0,"%s",cmMidiToSciPitch( e->d0, NULL, 0));
  3135. if( cmSvgWriterText(svgH, e->tick + e->durTicks/2, e->d0 * noteHeight + noteHeight/2, t0, "pitch") != kOkSvgRC )
  3136. rc = kSvgFailXsRC;
  3137. else
  3138. {
  3139. if( e0 != NULL )
  3140. {
  3141. bool fl = (i % 10) == 0;
  3142. _cmXsWriteMidiSvgLinePoint(svgH, e0->tick, e0->cplx.sum_d_vel, e->tick, e->cplx.sum_d_vel, p->cplx_max.sum_d_vel, "cplx_vel",fl?"V":NULL);
  3143. _cmXsWriteMidiSvgLinePoint(svgH, e0->tick, e0->cplx.sum_d_rym, e->tick, e->cplx.sum_d_rym, p->cplx_max.sum_d_rym, "cplx_rym",fl?"D":NULL);
  3144. _cmXsWriteMidiSvgLinePoint(svgH, e0->tick, e0->cplx.sum_d_lpch, e->tick, e->cplx.sum_d_lpch, p->cplx_max.sum_d_lpch, "cplx_lpch",fl?"L":NULL);
  3145. _cmXsWriteMidiSvgLinePoint(svgH, e0->tick, e0->cplx.sum_d_rpch, e->tick, e->cplx.sum_d_rpch, p->cplx_max.sum_d_rpch, "cplx_rpch",fl?"R":NULL);
  3146. _cmXsWriteMidiSvgLinePoint(svgH, e0->tick, e0->cplx.sum_n_lpch + e0->cplx.sum_n_rpch, e->tick, e->cplx.sum_n_lpch + e->cplx.sum_n_rpch, p->cplx_max.sum_n_lpch + p->cplx_max.sum_n_rpch, "cplx_density",fl?"N":NULL);
  3147. }
  3148. e0 = e;
  3149. }
  3150. }
  3151. i+=1;
  3152. }
  3153. break;
  3154. // if this is a bar
  3155. case kBarXsFl:
  3156. {
  3157. if( cmSvgWriterLine(svgH, e->tick, 0, e->tick, 127*noteHeight, "bar") != kOkSvgRC )
  3158. rc = kSvgFailXsRC;
  3159. else
  3160. {
  3161. if( cmSvgWriterText(svgH, e->tick, 10, t0 = cmTsPrintfP(t0,"%i",e->d0), "text" ) != kOkSvgRC )
  3162. rc = kSvgFailXsRC;
  3163. }
  3164. }
  3165. break;
  3166. // if this is a pedal event
  3167. case kDampDnXsFl:
  3168. case kDampUpDnXsFl:
  3169. case kSostDnXsFl:
  3170. {
  3171. const cmChar_t* classLabel = cmIsFlag(e->flags,kSostDnXsFl) ? "sost" : "damp";
  3172. unsigned y = (128 + cmIsFlag(e->flags,kSostDnXsFl)?1:0) * noteHeight;
  3173. cmSvgWriterRect(svgH, e->tick, y, e->durTicks, noteHeight-1, classLabel);
  3174. }
  3175. break;
  3176. }
  3177. }
  3178. if( rc != kOkXsRC )
  3179. cmErrMsg(&p->err,kSvgFailXsRC,"SVG element insert failed.");
  3180. if( rc == kOkXsRC )
  3181. if( cmSvgWriterWrite(svgH,cssFn,svgFn,standAloneFl, panZoomFl) != kOkSvgRC )
  3182. rc = cmErrMsg(&p->err,kSvgFailXsRC,"SVG file write to '%s' failed.",cmStringNullGuard(svgFn));
  3183. errLabel:
  3184. cmSvgWriterFree(&svgH);
  3185. //cmFsFreeFn(svgFn);
  3186. cmFsFreeFn(cssFn);
  3187. cmMemFree(t0);
  3188. return rc;
  3189. }
  3190. void _cmXsPushSvgEvent( cmXScore_t* p, cmXsMidiFile_t* mf, unsigned flags, unsigned tick, unsigned durTick, unsigned voice, unsigned d0, unsigned d1, const cmXsComplexity_t* cplx )
  3191. {
  3192. cmXsSvgEvt_t* e = cmLhAllocZ(p->lhH,cmXsSvgEvt_t,1);
  3193. e->flags = flags;
  3194. e->tick = tick;
  3195. e->durTicks = durTick;
  3196. e->voice = voice;
  3197. e->d0 = d0; // note=pitch bar=number pedal=ctl# metronome=BPM
  3198. e->d1 = d1;
  3199. if( cplx != NULL )
  3200. e->cplx = *cplx;
  3201. if( mf->eol != NULL )
  3202. mf->eol->link = e;
  3203. else
  3204. mf->elist = e;
  3205. // track the min/max pitch
  3206. if( cmIsFlag(flags,kOnsetXsFl) )
  3207. {
  3208. mf->pitch_min = mf->eol==NULL ? d0 : cmMin(mf->pitch_min,d0);
  3209. mf->pitch_max = mf->eol==NULL ? d0 : cmMin(mf->pitch_max,d0);
  3210. }
  3211. mf->eol = e;
  3212. }
  3213. cmXsRC_t _cmXScoreGenSvg( cmCtx_t* ctx, cmXsH_t h, int beginMeasNumb, const cmChar_t* svgFn, bool standAloneFl, bool panZoomFl )
  3214. {
  3215. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  3216. cmXsPart_t* pp = p->partL;
  3217. cmXsMidiFile_t mf;
  3218. memset(&mf,0,sizeof(mf));
  3219. for(; pp!=NULL; pp=pp->link)
  3220. {
  3221. const cmXsMeas_t* meas = pp->measL;
  3222. for(; meas!=NULL; meas=meas->link)
  3223. {
  3224. if( meas->number < beginMeasNumb )
  3225. continue;
  3226. const cmXsNote_t* note = meas->noteL;
  3227. for(; note!=NULL; note=note->slink)
  3228. {
  3229. // if this is a metronome marker
  3230. if( cmIsFlag(note->flags,kMetronomeXsFl) )
  3231. {
  3232. // set BPM as d0
  3233. _cmXsPushSvgEvent(p,&mf,note->flags,note->tick,0,0,note->duration,0,NULL);
  3234. continue;
  3235. }
  3236. // if this is a sounding note
  3237. if( cmIsFlag(note->flags,kOnsetXsFl) )
  3238. {
  3239. unsigned d0 = cmSciPitchToMidiPitch( note->step, note->alter, note->octave );
  3240. unsigned durTick = note->tied_dur;
  3241. if( note->tied != NULL )
  3242. {
  3243. cmXsNote_t* tn = note->tied;
  3244. for(; tn!=NULL; tn=tn->tied)
  3245. durTick += tn->tied_dur;
  3246. }
  3247. _cmXsPushSvgEvent(p,&mf,note->flags,note->tick,durTick,note->voice->id,d0,note->vel,&note->cplx);
  3248. continue;
  3249. }
  3250. // if this is a bar event
  3251. if( cmIsFlag(note->flags,kBarXsFl) )
  3252. {
  3253. _cmXsPushSvgEvent(p,&mf,note->flags,note->tick,0,0,note->meas->number,0,NULL);
  3254. continue;
  3255. }
  3256. // if this is a pedal event
  3257. if( cmIsFlag(note->flags,kDampDnXsFl|kDampUpDnXsFl|kSostDnXsFl) )
  3258. {
  3259. unsigned d0 = cmIsFlag(note->flags,kSostDnXsFl) ? kSostenutoCtlMdId : kSustainCtlMdId;
  3260. _cmXsPushSvgEvent(p,&mf,note->flags,note->tick,note->duration,0,d0,127,NULL);
  3261. continue;
  3262. }
  3263. }
  3264. }
  3265. }
  3266. return _cmXsWriteMidiSvg( ctx, p, &mf, svgFn, standAloneFl, panZoomFl );
  3267. }
  3268. cmXsRC_t cmXScoreTest(
  3269. cmCtx_t* ctx,
  3270. const cmChar_t* xmlFn,
  3271. const cmChar_t* editFn,
  3272. const cmChar_t* csvOutFn,
  3273. const cmChar_t* midiOutFn,
  3274. const cmChar_t* svgOutFn,
  3275. bool reportFl,
  3276. int beginMeasNumb,
  3277. int beginBPM,
  3278. bool standAloneFl,
  3279. bool panZoomFl )
  3280. {
  3281. cmXsRC_t rc;
  3282. cmXsH_t h = cmXsNullHandle;
  3283. if( editFn!=NULL && !cmFsIsFile(editFn) )
  3284. {
  3285. cmRptPrintf(&ctx->rpt,"The edit file %s does not exist. A new edit file will be created.",editFn);
  3286. cmXScoreGenEditFile(ctx,xmlFn,editFn);
  3287. editFn = NULL;
  3288. }
  3289. // Parse the XML file and apply the changes in editFn.
  3290. if((rc = cmXScoreInitialize( ctx, &h, xmlFn,editFn)) != kOkXsRC )
  3291. return cmErrMsg(&ctx->err,rc,"XScore alloc failed.");
  3292. if( csvOutFn != NULL )
  3293. {
  3294. cmXScoreWriteCsv(h,beginMeasNumb,csvOutFn);
  3295. _cmXsIsCsvValid(ctx,h,csvOutFn);
  3296. }
  3297. if( midiOutFn != NULL )
  3298. {
  3299. // measure the score complexity
  3300. double wndSecs = 1.0;
  3301. _cmXsMeasComplexity(h,wndSecs);
  3302. cmFileSysPathPart_t* pp = cmFsPathParts(midiOutFn);
  3303. _cmXsWriteMidiFile(ctx, h, beginMeasNumb, beginBPM, pp->dirStr, pp->fnStr );
  3304. _cmXsIsMidiFileValid(ctx, h, pp->dirStr, pp->fnStr );
  3305. cmFsFreePathParts(pp);
  3306. }
  3307. if( svgOutFn != NULL )
  3308. _cmXScoreGenSvg( ctx, h, beginMeasNumb, svgOutFn, standAloneFl, panZoomFl );
  3309. if(reportFl)
  3310. cmXScoreReport(h,&ctx->rpt,true);
  3311. return cmXScoreFinalize(&h);
  3312. }