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

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