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

cmXScore.c 117KB

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