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 106KB

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