libcm is a C development framework with an emphasis on audio signal processing applications.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

cmXScore.c 105KB

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