libcm is a C development framework with an emphasis on audio signal processing applications.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244
  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. double graceDurSec = 1.0/15.0; // duration of all grace notes in seconds
  1260. for(; 1; ++graceGroupId)
  1261. {
  1262. cmXsNote_t* gn0p = NULL;
  1263. cmXsNote_t* gn1p = NULL;
  1264. unsigned gN = 0;
  1265. cmXsPart_t* pp = p->partL;
  1266. double ticksPerSec = 0;
  1267. for(; pp!=NULL; pp=pp->link)
  1268. {
  1269. cmXsMeas_t* mp = pp->measL;
  1270. for(; mp!=NULL; mp=mp->link)
  1271. {
  1272. cmXsNote_t* np = mp->noteL;
  1273. for(; np!=NULL; np=np->slink )
  1274. {
  1275. // notice change of tempo
  1276. if( cmIsFlag(np->flags,kMetronomeXsFl) )
  1277. {
  1278. // ticks/sec = ticks/qn * qn/sec
  1279. ticksPerSec = mp->divisions * np->duration / 60.0;
  1280. }
  1281. // if this note is part of the grace note group we are searching for
  1282. if( np->graceGroupId == graceGroupId )
  1283. {
  1284. // track the first note in the grace note list
  1285. if( gn0p == NULL )
  1286. gn0p = np;
  1287. // add the note to the end of the grace note list
  1288. if( gn1p != NULL )
  1289. gn1p->grace = np;
  1290. // track the last note in the grace note list
  1291. gn1p = np;
  1292. // set each grace note to have 1/20 of a second duration
  1293. if( cmIsFlag(np->flags,kGraceXsFl) )
  1294. np->duration = floor(ticksPerSec * graceDurSec);
  1295. gN += 1;
  1296. }
  1297. } //
  1298. }
  1299. }
  1300. // no records were found for this grace id - we're done
  1301. if( gn0p == NULL )
  1302. break;
  1303. // grace note groups must have at least 3 members
  1304. if( gN < 3 )
  1305. {
  1306. rc = cmErrMsg(&p->err,kSyntaxErrorXsRC,"The grace not group ending in meas %i has fewer than 3 (%i) members.", gn1p->meas->number, gN );
  1307. break;
  1308. }
  1309. // gn0p is now set to the first note in th group
  1310. // gn1p is now set to the last note in the group
  1311. // verify that the first note is marked with kBegGraceXsFl
  1312. if( cmIsNotFlag(gn0p->flags,kBegGraceXsFl) )
  1313. {
  1314. 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 );
  1315. break;
  1316. }
  1317. // verify that the last note is marked with kEndGraceXsFl
  1318. if( cmIsNotFlag(gn1p->flags,kEndGraceXsFl) )
  1319. {
  1320. 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 );
  1321. break;
  1322. }
  1323. // count the total number of events between gn0p and gn1p
  1324. cmXsNote_t* n0p = NULL;
  1325. cmXsNote_t* n1p = gn0p;
  1326. cmXsMeas_t* mp = gn0p->meas;
  1327. unsigned aN = 0;
  1328. for(; n0p != gn1p; n1p=n1p->slink )
  1329. {
  1330. // if we are crossing a measure boundary
  1331. if( n1p == NULL )
  1332. {
  1333. mp = mp->link;
  1334. assert(mp!=NULL);
  1335. n1p = mp->noteL;
  1336. }
  1337. if(1)
  1338. {
  1339. bool fl = n0p != NULL && n0p->tick < n1p->tick;
  1340. unsigned type = n1p->flags & (kBegGraceXsFl|kEndGraceXsFl|kAddGraceXsFl|kSubGraceXsFl|kFirstGraceXsFl);
  1341. printf("%3i 0x%08x %i %5i %i\n",n1p->graceGroupId,type,n1p->tick,n1p->duration,fl);
  1342. }
  1343. ++aN;
  1344. n0p = n1p;
  1345. }
  1346. // create a vector of pointers to all events between gn0p and gn1p
  1347. cmXsNote_t* aV[ aN ];
  1348. unsigned i;
  1349. n1p = gn0p;
  1350. n0p = NULL;
  1351. mp = gn0p->meas;
  1352. for(i=0; n0p != gn1p; n1p=n1p->slink )
  1353. {
  1354. // if we are crossing a measure boundary
  1355. if( n1p == NULL )
  1356. {
  1357. mp = mp->link;
  1358. assert(mp!=NULL);
  1359. n1p = mp->noteL;
  1360. }
  1361. assert(i<aN);
  1362. aV[i++] = n1p;
  1363. n0p = n1p;
  1364. }
  1365. switch( gn1p->flags & (kAddGraceXsFl | kSubGraceXsFl | kFirstGraceXsFl) )
  1366. {
  1367. case kAddGraceXsFl:
  1368. _cmXScoreGraceInsertTime(p, graceGroupId, aV, aN );
  1369. break;
  1370. case kSubGraceXsFl:
  1371. _cmXScoreGraceOverlayTime(p, graceGroupId, aV, aN );
  1372. break;
  1373. case kFirstGraceXsFl:
  1374. break;
  1375. default:
  1376. { assert(0); }
  1377. }
  1378. }
  1379. return rc;
  1380. }
  1381. cmXsRC_t cmXScoreInitialize( cmCtx_t* ctx, cmXsH_t* hp, const cmChar_t* xmlFn )
  1382. {
  1383. cmXsRC_t rc = kOkXsRC;
  1384. if((rc = cmXScoreFinalize(hp)) != kOkXsRC )
  1385. return rc;
  1386. cmXScore_t* p = cmMemAllocZ(cmXScore_t,1);
  1387. cmErrSetup(&p->err,&ctx->rpt,"XScore");
  1388. // create a local linked heap
  1389. if( cmLHeapIsValid( p->lhH = cmLHeapCreate(8196,ctx)) == false )
  1390. return cmErrMsg(&p->err,kLHeapFailXsRC,"Lheap create failed.");
  1391. // open the music xml file
  1392. if( cmXmlAlloc(ctx, &p->xmlH, xmlFn) != kOkXmlRC )
  1393. {
  1394. rc = cmErrMsg(&p->err,kXmlFailXsRC,"Unable to open the MusicXML file '%s'.",cmStringNullGuard(xmlFn));
  1395. goto errLabel;
  1396. }
  1397. //cmXmlPrint(p->xmlH,&ctx->rpt);
  1398. // parse the part-list
  1399. if((rc = _cmXScoreParsePartList( p )) != kOkXsRC )
  1400. goto errLabel;
  1401. // parse each score 'part'
  1402. cmXsPart_t* pp = p->partL;
  1403. for(; pp!=NULL; pp=pp->link)
  1404. if((rc = _cmXScoreParsePart(p,pp)) != kOkXsRC )
  1405. goto errLabel;
  1406. // fill in the note->slink chain to link the notes in each measure in time order
  1407. _cmXScoreSort(p);
  1408. _cmXScoreSpreadGraceNotes(p);
  1409. _cmXScoreSort(p);
  1410. _cmXScoreSetAbsoluteTime(p);
  1411. _cmXScoreResolveTiesAndLoc(p);
  1412. _cmXScoreRemoveDuplicateNotes(p);
  1413. _cmXScoreSetMeasGroups(p,kEvenXsFl);
  1414. _cmXScoreSetMeasGroups(p,kDynXsFl);
  1415. _cmXScoreSetMeasGroups(p,kTempoXsFl);
  1416. //_cmXScoreResolveOctaveShift(p);
  1417. // CSV output initialize failed.
  1418. if( cmCsvInitialize(&p->csvH,ctx) != kOkCsvRC )
  1419. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV output object create failed.");
  1420. errLabel:
  1421. if( rc != kOkXsRC )
  1422. _cmXScoreFinalize(p);
  1423. else
  1424. hp->h = p;
  1425. return rc;
  1426. }
  1427. cmXsRC_t cmXScoreFinalize( cmXsH_t* hp )
  1428. {
  1429. cmXsRC_t rc = kOkXsRC;
  1430. if( hp == NULL || cmXScoreIsValid(*hp)==false )
  1431. return kOkXsRC;
  1432. cmXScore_t* p = _cmXScoreHandleToPtr(*hp);
  1433. if((rc = _cmXScoreFinalize(p)) != kOkXsRC )
  1434. return rc;
  1435. hp->h = NULL;
  1436. return rc;
  1437. }
  1438. bool cmXScoreIsValid( cmXsH_t h )
  1439. { return h.h != NULL; }
  1440. //-------------------------------------------------------------------------------------------
  1441. typedef struct
  1442. {
  1443. unsigned idx; // Fields from the reordering input file which are
  1444. unsigned voice; // used to match the reorder record to
  1445. unsigned locIdx; // the associated a cmXsNode_t record.
  1446. unsigned tick; //
  1447. unsigned durtn; //
  1448. float rval; //
  1449. unsigned midi; //
  1450. cmXsNote_t* note; // The cmXsNote_t* associated with this cmXsReorder_t record
  1451. unsigned dynIdx; // cmInvalidIdx=ignore otherwise index into _cmXScoreDynMarkArray[]
  1452. unsigned newFlags; // 0=ignore | kSostUp/DnXsFl | kDampUp/DnXsFl | kTieEndXsFl
  1453. unsigned newTick; // 0=ignore >0 new tick value
  1454. unsigned graceFlags; // 0=ignore See kXXXGraceXsFl
  1455. unsigned graceGroupId; // 0=ignore >0=grace note group id
  1456. unsigned pitch; // 0=ignore >0 new pitch
  1457. } cmXsReorder_t;
  1458. typedef struct _cmXScoreDynMark_str
  1459. {
  1460. const cmChar_t* mark; //
  1461. unsigned id; // (1-17) maps to velocity
  1462. unsigned dyn; // pppp - fff (1-9) as used by cmScore
  1463. int adjust; // {-1,0,+1}
  1464. unsigned vel; // associated MIDI velocity
  1465. } _cmXScoreDynMark_t;
  1466. _cmXScoreDynMark_t _cmXScoreDynMarkArray[] =
  1467. {
  1468. {"pppp-", 1, 1, -1, 3},
  1469. {"pppp", 2, 1, 0, 10},
  1470. {"pppp+", 3, 1, 1, 22},
  1471. {"ppp-", 3, 2, -1, 22},
  1472. {"ppp", 4, 2, 0, 29},
  1473. {"ppp+", 5, 2, 1, 36},
  1474. {"pp-", 5, 3, -1, 36},
  1475. {"pp", 6, 3, 0, 43},
  1476. {"pp+", 7, 3, 1, 50},
  1477. {"p-", 7, 4, -1, 50},
  1478. {"p", 8, 4, 0, 57},
  1479. {"p+", 9, 4, 1, 64},
  1480. {"mp-", 9, 5, -1, 64},
  1481. {"mp", 10, 5, 0, 71},
  1482. {"mp+", 11, 5, 1, 78},
  1483. {"mf-", 11, 6, -1, 78},
  1484. {"mf", 12, 6, 0, 85},
  1485. {"mf+", 13, 6, 1, 92},
  1486. {"f-", 13, 7, -1, 92},
  1487. {"f", 14, 7, 0, 99},
  1488. {"f+", 15, 7, 1, 106},
  1489. {"ff", 16, 8, 0, 113},
  1490. {"ff+", 17, 8, 1, 120},
  1491. {"fff", 18, 9, 0, 127},
  1492. {NULL,0,0,0,0}
  1493. };
  1494. cmXsNote_t* _cmXsReorderFindNote( cmXScore_t* p, unsigned measNumb, const cmXsReorder_t* r, unsigned iii )
  1495. {
  1496. cmXsPart_t* pp = p->partL;
  1497. for(; pp!=NULL; pp=pp->link)
  1498. {
  1499. cmXsMeas_t* mp = pp->measL;
  1500. for(; mp!=NULL; mp=mp->link)
  1501. if( mp->number == measNumb)
  1502. {
  1503. cmXsNote_t* np = mp->noteL;
  1504. int index = 0;
  1505. for(; np!=NULL; np=np->slink,++index)
  1506. {
  1507. if( np->voice->id == r->voice &&
  1508. np->locIdx == r->locIdx &&
  1509. np->tick == r->tick &&
  1510. np->duration == r->durtn &&
  1511. np->rvalue == r->rval &&
  1512. np->pitch == r->midi &&
  1513. index == r->idx )
  1514. {
  1515. return np;
  1516. }
  1517. }
  1518. }
  1519. }
  1520. cmErrMsg(&p->err,kSyntaxErrorXsRC,"Reorder note not found meas:%i index:%i.",measNumb,iii);
  1521. return NULL;
  1522. }
  1523. void _cmXScoreInsertPedalEvent( cmXScore_t* p, const cmXsReorder_t* r, unsigned flags )
  1524. {
  1525. // Create a new score event record
  1526. cmXsNote_t* nn = cmLhAllocZ(p->lhH,cmXsNote_t,1);
  1527. nn->uid = p->nextUid++;
  1528. nn->voice = r->note->voice;
  1529. nn->meas = r->note->meas;
  1530. nn->flags = flags;
  1531. // Pedal down events occur after the event they are attached to
  1532. if( cmIsFlag(flags,kSostDnXsFl | kDampDnXsFl ) )
  1533. {
  1534. nn->tick = r->note->tick + 1;
  1535. _cmXScoreInsertNoteAfter(r->note,nn);
  1536. }
  1537. else
  1538. {
  1539. // Pedal up events occur before the event they are attached to
  1540. if( cmIsFlag(flags,kSostUpXsFl | kDampUpXsFl ) )
  1541. {
  1542. nn->tick = r->note->tick==0 ? 0 : r->note->tick - 1;
  1543. _cmXScoreInsertNoteBefore(r->note,nn);
  1544. }
  1545. else
  1546. { assert(0); }
  1547. }
  1548. }
  1549. cmXsRC_t _cmXScoreReorderMeas( cmXScore_t* p, unsigned measNumb, cmXsReorder_t* rV, unsigned rN )
  1550. {
  1551. unsigned i;
  1552. if( rN == 0 )
  1553. return kOkXsRC;
  1554. // set the 'note' field on each cmXsReorder_t record
  1555. for(i=0; i<rN; ++i)
  1556. if((rV[i].note = _cmXsReorderFindNote(p,measNumb,rV+i,i)) == NULL )
  1557. return kSyntaxErrorXsRC;
  1558. cmXsMeas_t* mp = rV[0].note->meas;
  1559. cmXsNote_t* n0p = NULL;
  1560. assert( mp->number == measNumb );
  1561. // Reassign the slink of the cmXsNote_t records in this measure
  1562. // according to their order in rV[].
  1563. for(i=0; i<rN; ++i)
  1564. {
  1565. if( n0p == NULL )
  1566. mp->noteL = rV[i].note;
  1567. else
  1568. n0p->slink = rV[i].note;
  1569. // if a new tick was specified
  1570. if( rV[i].newTick != 0 )
  1571. rV[i].note->tick = rV[i].newTick;
  1572. // if a dynamic or velocity mark was included
  1573. if( rV[i].dynIdx != cmInvalidIdx )
  1574. {
  1575. rV[i].note->dynamics = _cmXScoreDynMarkArray[ rV[i].dynIdx ].dyn;
  1576. rV[i].note->vel = _cmXScoreDynMarkArray[ rV[i].dynIdx ].vel;
  1577. }
  1578. // if the tie end flag was set
  1579. if( cmIsFlag(rV[i].newFlags,kTieEndXsFl) )
  1580. {
  1581. rV[i].note->flags |= kTieEndXsFl;
  1582. rV[i].note->flags = cmClrFlag(rV[i].note->flags, kOnsetXsFl);
  1583. rV[i].newFlags = cmClrFlag(rV[i].newFlags,kTieEndXsFl );
  1584. }
  1585. // if a new note value was specified
  1586. if( rV[i].pitch != 0 )
  1587. rV[i].note->pitch = rV[i].pitch;
  1588. rV[i].note->flags |= rV[i].graceFlags;
  1589. rV[i].note->graceGroupId = rV[i].graceGroupId;
  1590. n0p = rV[i].note;
  1591. n0p->slink = NULL;
  1592. }
  1593. // Insert new note records for pedal up/dn events.
  1594. for(i=0; i<rN; ++i)
  1595. {
  1596. if( rV[i].newFlags != 0 )
  1597. {
  1598. if( cmIsFlag(rV[i].newFlags,kDampDnXsFl ) )
  1599. _cmXScoreInsertPedalEvent(p,rV + i,kDampDnXsFl);
  1600. if( cmIsFlag(rV[i].newFlags,kSostDnXsFl ) )
  1601. _cmXScoreInsertPedalEvent(p,rV + i,kSostDnXsFl);
  1602. if( cmIsFlag(rV[i].newFlags,kDampUpXsFl ) )
  1603. _cmXScoreInsertPedalEvent(p,rV + i,kDampUpXsFl);
  1604. if( cmIsFlag(rV[i].newFlags,kSostUpXsFl ) )
  1605. _cmXScoreInsertPedalEvent(p,rV + i,kSostUpXsFl);
  1606. }
  1607. }
  1608. return kOkXsRC;
  1609. }
  1610. cmXsRC_t _cmXScoreReorderParseDyn(cmXScore_t* p, const cmChar_t* b, unsigned lineNumb, unsigned* dynIdxRef )
  1611. {
  1612. cmXsRC_t rc = kOkXsRC;
  1613. const cmChar_t* s;
  1614. *dynIdxRef = cmInvalidIdx;
  1615. // locate the '!' which indicates the start of a dynamic marking
  1616. if( (s = strchr(b,'!')) == NULL )
  1617. return rc;
  1618. ++s; // increment past the '!'
  1619. if( *s == 0 )
  1620. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unexpected end-of-line on dynamics parsing on line:%i.",lineNumb);
  1621. // some dynamic markings are surrounded by parenthesis (to indicate a dynamic level with greater uncertainty)
  1622. if( *s == '(' )
  1623. ++s; // skip the paren.
  1624. if( *s == 0 )
  1625. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unexpected end-of-line on dynamics parsing on line:%i.",lineNumb);
  1626. unsigned i = 0;
  1627. unsigned j = 0;
  1628. unsigned n = 6;
  1629. bool doneFl = false;
  1630. cmChar_t mark[n+1];
  1631. memset(mark,0,n+1);
  1632. for(i=0; j<n && doneFl==false; ++i)
  1633. {
  1634. switch(s[i])
  1635. {
  1636. case 'm':
  1637. case 'p':
  1638. case 'f':
  1639. case '+':
  1640. case '-':
  1641. mark[j++] = s[i];
  1642. break;
  1643. case ')': // ending paren.
  1644. case 0: // end of string
  1645. case ' ': // end of mark
  1646. case '\n': // end of line
  1647. default: // anything else
  1648. doneFl = true;
  1649. break;
  1650. }
  1651. }
  1652. if( !doneFl )
  1653. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Illegal dynamic mark (%s) syntax on line:%i.",mark,lineNumb);
  1654. // look up the dynamic mark in the reference table
  1655. for(j=0; _cmXScoreDynMarkArray[j].mark!=NULL; ++j)
  1656. if( strcmp(mark,_cmXScoreDynMarkArray[j].mark) == 0 )
  1657. break;
  1658. if( _cmXScoreDynMarkArray[j].mark == NULL )
  1659. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"The dynamic mark '%s' is not legal on line:%i.",mark,lineNumb);
  1660. *dynIdxRef = j;
  1661. return rc;
  1662. }
  1663. cmXsRC_t _cmXScoreReorderParseFlags(cmXScore_t* p, const cmChar_t* b, unsigned line, unsigned* newFlagsRef )
  1664. {
  1665. cmXsRC_t rc = kOkXsRC;
  1666. const cmChar_t* s;
  1667. bool doneFl = false;
  1668. unsigned i = 0;
  1669. *newFlagsRef = 0;
  1670. // tilde indicates a pedal event
  1671. if((s = strchr(b,'~')) == NULL )
  1672. return rc;
  1673. do
  1674. {
  1675. ++s;
  1676. switch( *s )
  1677. {
  1678. case 'd':
  1679. *newFlagsRef |= kSostDnXsFl; // sostenuto pedal down just after this note onset
  1680. break;
  1681. case 'u':
  1682. *newFlagsRef |= kSostUpXsFl; // sostenuto pedal up just before this event
  1683. break;
  1684. case 'x':
  1685. *newFlagsRef |= (kSostUpXsFl | kSostDnXsFl); // sostenuto pedal up just before this event and sost down just after it.
  1686. break;
  1687. case 'D':
  1688. *newFlagsRef |= kDampDnXsFl; // damper pedal down
  1689. break;
  1690. case 'U':
  1691. *newFlagsRef |= kDampUpXsFl; // damper pedal up
  1692. break;
  1693. case '_':
  1694. *newFlagsRef |= kTieEndXsFl; // set tie end flag
  1695. break;
  1696. default:
  1697. if( i == 0 )
  1698. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unexpected flag marking '%c' on line %i.",*s,line);
  1699. doneFl = true;
  1700. }
  1701. ++i;
  1702. }while(!doneFl);
  1703. return rc;
  1704. }
  1705. cmXsRC_t _cmXScoreReorderParseTick(cmXScore_t* p, const cmChar_t* b, unsigned line, unsigned* tickRef )
  1706. {
  1707. cmXsRC_t rc = kOkXsRC;
  1708. const cmChar_t* s;
  1709. if((s = strchr(b,'@')) == NULL )
  1710. return rc;
  1711. ++s;
  1712. if(!isdigit(*s))
  1713. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Unexpected tick reorder value '%c' on line %i.",*s,line);
  1714. if(sscanf(s,"%i",tickRef) != 1 )
  1715. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"tick reorder parse failed on line %i.",line);
  1716. return rc;
  1717. }
  1718. cmXsRC_t _cmXScoreReorderParseGrace(cmXScore_t* p, const cmChar_t* b, unsigned line, cmXsReorder_t* r, unsigned* graceGroupIdRef )
  1719. {
  1720. cmXsRC_t rc = kOkXsRC;
  1721. const cmChar_t* s;
  1722. if((s = strchr(b,'%')) == NULL )
  1723. return rc;
  1724. ++s;
  1725. r->graceGroupId = *graceGroupIdRef;
  1726. while(1)
  1727. {
  1728. switch(*s)
  1729. {
  1730. case 'b': r->graceFlags |= kBegGraceXsFl; break;
  1731. case 'a': r->graceFlags |= kAddGraceXsFl | kEndGraceXsFl; break;
  1732. case 's': r->graceFlags |= kSubGraceXsFl | kEndGraceXsFl; break;
  1733. case 'f': r->graceFlags |= kFirstGraceXsFl | kEndGraceXsFl; break;
  1734. case 'g': break;
  1735. case '%':
  1736. *graceGroupIdRef += 1;
  1737. ++s;
  1738. continue;
  1739. default:
  1740. { assert(0); }
  1741. }
  1742. break;
  1743. }
  1744. return rc;
  1745. }
  1746. cmXsRC_t _cmXScoreReorderParsePitch(cmXScore_t* p, const cmChar_t* b, unsigned line, unsigned* pitchRef )
  1747. {
  1748. cmXsRC_t rc = kOkXsRC;
  1749. cmChar_t* s;
  1750. cmChar_t buf[4];
  1751. unsigned i,j;
  1752. memset(buf,0,sizeof(buf));
  1753. *pitchRef = 0;
  1754. if((s = strchr(b,'$')) == NULL )
  1755. return rc;
  1756. ++s;
  1757. j=2;
  1758. for(i=0; i<j && s[i]; ++i,++s)
  1759. {
  1760. buf[i] = *s;
  1761. if( i==1 && (*s=='#' || *s=='b') )
  1762. j = 3;
  1763. if( i==0 && strchr("ABCDEFG",*s)==NULL )
  1764. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Illegal pitch letter ('%c')specification line %i.",*s,line);
  1765. if( i==1 && !isdigit(*s) && *s!='#' && *s!='b' )
  1766. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Illegal pitch level ('%c') specification line %i.",*s,line);
  1767. if( i==2 && !isdigit(*s) )
  1768. return cmErrMsg(&p->err,kSyntaxErrorXsRC,"Illegal pitch octave ('%c') specification line %i.",*s,line);
  1769. }
  1770. unsigned pitch = cmSciPitchToMidi(buf);
  1771. if( pitch<kInvalidMidiByte)
  1772. *pitchRef = pitch;
  1773. else
  1774. rc = cmErrMsg(&p->err,kSyntaxErrorXsRC,"Pitch conversion from '%s' failed on line %i.",buf,line);
  1775. return rc;
  1776. }
  1777. cmXsRC_t cmXScoreReorder( cmXsH_t h, const cmChar_t* fn )
  1778. {
  1779. typedef enum { kFindMeasStId, kFindEventStId, kReadEventStId } stateId_t;
  1780. cmXsRC_t rc = kOkXsRC;
  1781. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  1782. cmFileH_t fH = cmFileNullHandle;
  1783. cmChar_t* b = NULL;
  1784. unsigned bN = 0;
  1785. unsigned ln = 0;
  1786. stateId_t stateId = kFindMeasStId;
  1787. unsigned rN = 1024;
  1788. unsigned ri = 0;
  1789. unsigned measNumb = 0;
  1790. unsigned graceGroupId = 1;
  1791. cmXsReorder_t rV[ rN ];
  1792. if( cmFileOpen(&fH,fn,kReadFileFl,p->err.rpt) != kOkFileRC )
  1793. {
  1794. rc = cmErrMsg(&p->err,kFileFailXsRC,"The reordering file '%s' could not be opened.",cmStringNullGuard(fn));
  1795. return rc;
  1796. }
  1797. for(; cmFileGetLineAuto(fH,&b,&bN)==kOkFileRC; ++ln)
  1798. {
  1799. switch( stateId )
  1800. {
  1801. case kFindEventStId: // scanning past labels to an event line
  1802. {
  1803. unsigned voice,loc;
  1804. if( sscanf(b,"%i %i",&voice,&loc) != 2 )
  1805. continue;
  1806. stateId = kReadEventStId;
  1807. }
  1808. // fall through
  1809. case kReadEventStId:
  1810. {
  1811. cmXsReorder_t r;
  1812. char pitchStr[4];
  1813. memset(&r,0,sizeof(r));
  1814. // parse an event line
  1815. if( sscanf(b,"%i %i %i %i %i %f",&r.idx,&r.voice,&r.locIdx,&r.tick,&r.durtn,&r.rval) == 6 )
  1816. {
  1817. assert( strlen(b)>=52);
  1818. int PC = 39; // text file column where first pitch char occurs
  1819. if( b[PC] == ' ')
  1820. r.midi = 0;
  1821. else
  1822. {
  1823. pitchStr[0] = b[PC+0];
  1824. pitchStr[1] = b[PC+1];
  1825. pitchStr[2] = b[PC+2];
  1826. pitchStr[3] = 0;
  1827. if( !isdigit(pitchStr[2]) )
  1828. r.midi = 0;
  1829. else
  1830. {
  1831. if( pitchStr[1] == ' ')
  1832. {
  1833. pitchStr[1] = pitchStr[2];
  1834. pitchStr[2] = 0;
  1835. }
  1836. r.midi = cmSciPitchToMidi(pitchStr);
  1837. }
  1838. }
  1839. // parse the dynamic marking following a '!'
  1840. if((rc = _cmXScoreReorderParseDyn(p,b,ln+1,&r.dynIdx)) != kOkXsRC )
  1841. goto errLabel;
  1842. // parse the flag edits
  1843. if((rc = _cmXScoreReorderParseFlags(p,b,ln+1, &r.newFlags)) != kOkXsRC )
  1844. goto errLabel;
  1845. // parse the @newtick marker
  1846. if((rc = _cmXScoreReorderParseTick(p, b, ln+1, &r.newTick)) != kOkXsRC )
  1847. goto errLabel;
  1848. // parse the %grace note marker
  1849. if((rc = _cmXScoreReorderParseGrace(p, b, ln+1, &r, &graceGroupId)) != kOkXsRC )
  1850. goto errLabel;
  1851. // parse the $pitch marker
  1852. if((rc = _cmXScoreReorderParsePitch(p, b, ln+1, &r.pitch )) != kOkXsRC )
  1853. goto errLabel;
  1854. // process grace notes - these need to be processed separate from
  1855. // the _cmXScoreReorderMeas() because grace notes may cross measure boundaries.
  1856. /*
  1857. if( r.graceType != 0 )
  1858. {
  1859. r.graceGroupId = graceGroupId;
  1860. // if this is an end of a grace note group
  1861. if( r.graceType != 'g' && r.graceType != 'b' )
  1862. {
  1863. graceGroupId += 1;
  1864. }
  1865. }
  1866. */
  1867. // store the record
  1868. assert( ri < rN );
  1869. rV[ri++] = r;
  1870. continue;
  1871. }
  1872. // the end of the measure was encountered -
  1873. // reorder the measure based on the cmXsReorder_t in rV[ri]
  1874. if((rc = _cmXScoreReorderMeas(p, measNumb, rV, ri )) != kOkXsRC )
  1875. goto errLabel;
  1876. ri = 0;
  1877. stateId = kFindMeasStId;
  1878. // fall through
  1879. }
  1880. case kFindMeasStId: // scanning for a bar-line
  1881. {
  1882. char colon;
  1883. if( sscanf(b,"%i %c",&measNumb,&colon) == 2 && colon == ':' )
  1884. {
  1885. //printf("meas: %i \n",measNumb);
  1886. stateId = kFindEventStId;
  1887. }
  1888. }
  1889. break;
  1890. }
  1891. }
  1892. // the ticks may have changed so the 'secs' and 'dsecs' must be updated
  1893. _cmXScoreSetAbsoluteTime( p );
  1894. // the bar lines should be the first event in the measure
  1895. _cmXScoreFixBarLines(p);
  1896. // resort to force the links to be correct
  1897. _cmXScoreSort(p);
  1898. // process the grace notes.
  1899. _cmXScoreProcessGraceNotes( p );
  1900. // inserting grace notes may have left the score unsorted
  1901. _cmXScoreSort(p);
  1902. errLabel:
  1903. cmFileClose(&fH);
  1904. cmMemFree(b);
  1905. return rc;
  1906. }
  1907. /*
  1908. kMidiFileIdColScIdx= 0,
  1909. kTypeLabelColScIdx = 3,
  1910. kDSecsColScIdx = 4,
  1911. kSecsColScIdx = 5,
  1912. kD0ColScIdx = 9,
  1913. kD1ColScIdx = 10,
  1914. kPitchColScIdx = 11,
  1915. kBarColScIdx = 13,
  1916. kSkipColScIdx = 14,
  1917. kEvenColScIdx = 15,
  1918. kGraceColScIdx = 16,
  1919. kTempoColScIdx = 17,
  1920. kFracColScIdx = 18,
  1921. kDynColScIdx = 19,
  1922. kSectionColScIdx = 20,
  1923. kRecdPlayColScIdx = 21,
  1924. kRemarkColScIdx = 22
  1925. */
  1926. cmXsRC_t _cmXScoreWriteCsvHdr( cmXScore_t* p )
  1927. {
  1928. const cmChar_t* s[] =
  1929. {
  1930. "id","trk","evt","opcode","dticks","micros","status",
  1931. "meta","ch","d0","d1","arg0","arg1","bar","skip",
  1932. "even","grace","tempo","t frac","dyn","section","play_recd","remark",NULL
  1933. };
  1934. cmCsvCell_t* lcp = NULL;
  1935. if( cmCsvAppendRow( p->csvH, &lcp, cmCsvInsertSymText(p->csvH,s[0]), 0, 0 ) != kOkCsvRC )
  1936. return cmErrMsg(&p->err,kCsvFailXsRC,"CSV append row failed.");
  1937. unsigned i;
  1938. for(i=1; s[i]!=NULL; ++i)
  1939. {
  1940. if( cmCsvInsertIdentColAfter(p->csvH, lcp, &lcp, s[i], 0 ) != kOkCsvRC )
  1941. return cmErrMsg(&p->err,kCsvFailXsRC,"CSV error inserting CSV title %i.\n",i);
  1942. }
  1943. return kOkXsRC;
  1944. }
  1945. cmXsRC_t _cmXScoreWriteCsvBlankCols( cmXScore_t* p, unsigned cnt, cmCsvCell_t** leftCellPtrPtr )
  1946. {
  1947. unsigned i;
  1948. for(i=0; i<cnt; ++i)
  1949. if( cmCsvInsertIdentColAfter(p->csvH,*leftCellPtrPtr,leftCellPtrPtr,"",0) != kOkCsvRC )
  1950. return cmErrMsg(&p->err,kCsvFailXsRC,"CSV output failed on blank column.");
  1951. return kOkCsvRC;
  1952. }
  1953. const cmChar_t* _cmXScoreTranslateDynamics( cmXScore_t* p, const cmXsNote_t* np, cmChar_t* buf, unsigned bufN )
  1954. {
  1955. if( cmIsFlag(np->flags,kDynXsFl) && np->dynamics != 0 )
  1956. {
  1957. const cmChar_t* dynStr = NULL;
  1958. switch(np->dynamics)
  1959. {
  1960. case 1: dynStr = "pppp"; break;
  1961. case 2: dynStr = "ppp"; break;
  1962. case 3: dynStr = "pp"; break;
  1963. case 4: dynStr = "p"; break;
  1964. case 5: dynStr = "mp"; break;
  1965. case 6: dynStr = "mf"; break;
  1966. case 7: dynStr = "f"; break;
  1967. case 8: dynStr = "ff"; break;
  1968. case 9: dynStr = "fff"; break;
  1969. default:
  1970. cmErrMsg(&p->err,kSyntaxErrorXsRC,"An invalid dynamic value (%i) was encountered.",np->dynamics);
  1971. goto errLabel;
  1972. }
  1973. if( np->dynGroupId == 0 )
  1974. snprintf(buf,bufN,"%s",dynStr);
  1975. else
  1976. snprintf(buf,bufN,"%s %i",dynStr,np->dynGroupId);
  1977. return buf;
  1978. }
  1979. errLabel:
  1980. return "";
  1981. }
  1982. const cmChar_t* cmXsFormatMeasurementCsvField( unsigned flags, unsigned fl, char abbrev, unsigned sectionId, char* buf, unsigned bufN )
  1983. {
  1984. assert( bufN > 1 );
  1985. buf[0] = ' ';
  1986. buf[1] = 0;
  1987. if( cmIsFlag(flags,fl) )
  1988. {
  1989. if( sectionId != 0 )
  1990. snprintf(buf,bufN-1,"%c %i%c",abbrev,sectionId, cmIsFlag(flags,kHeelXsFl)?'*':' ');
  1991. else
  1992. buf[0] = abbrev;
  1993. }
  1994. return buf;
  1995. }
  1996. cmXsRC_t _cmXScoreWriteCsvRow(
  1997. cmXScore_t* p,
  1998. unsigned rowIdx,
  1999. unsigned uid,
  2000. unsigned bar,
  2001. const cmChar_t* sectionStr,
  2002. const cmChar_t* opCodeStr,
  2003. double dsecs,
  2004. double secs,
  2005. unsigned d0,
  2006. unsigned d1,
  2007. unsigned pitch, // set to -1 if the pitch is not valid
  2008. double frac,
  2009. const cmChar_t* dynStr,
  2010. unsigned flags,
  2011. const cmChar_t* evenStr,
  2012. const cmChar_t* tempoStr)
  2013. {
  2014. cmXsRC_t rc = kOkXsRC;
  2015. cmCsvCell_t* lcp = NULL;
  2016. // append an empty row to the CSV object
  2017. if( cmCsvAppendRow( p->csvH, &lcp, cmCsvInsertSymUInt(p->csvH, rowIdx ), 0, 0 ) != kOkCsvRC )
  2018. {
  2019. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV append row failed.");
  2020. goto errLabel;
  2021. }
  2022. /*
  2023. // col 0 : blanks
  2024. if( cmCsvInsertUIntColAfter(p->csvH, lcp, &lcp, rowIdx, 0 ) != kOkCsvRC )
  2025. {
  2026. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV output row index failed.");
  2027. goto errLabel;
  2028. }
  2029. */
  2030. // col 1 : track (always 1)
  2031. if( cmCsvInsertUIntColAfter(p->csvH,lcp,&lcp,1,0) != kOkCsvRC )
  2032. {
  2033. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'd0'.");
  2034. goto errLabel;
  2035. }
  2036. // col 2 : evt (set to event uid, or blank if uid == -1)
  2037. if( uid == -1 )
  2038. {
  2039. if((rc = _cmXScoreWriteCsvBlankCols(p,1,&lcp)) != kOkXsRC )
  2040. goto errLabel;
  2041. }
  2042. else
  2043. if( cmCsvInsertUIntColAfter(p->csvH,lcp,&lcp,uid,0) != kOkCsvRC )
  2044. {
  2045. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'd0'.");
  2046. goto errLabel;
  2047. }
  2048. // col 3 : output the opcode
  2049. if( cmCsvInsertIdentColAfter(p->csvH,lcp,&lcp,opCodeStr,0) != kOkCsvRC )
  2050. {
  2051. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on opcode label.");
  2052. goto errLabel;
  2053. }
  2054. // col 4 : dsecs
  2055. if( cmCsvInsertDoubleColAfter(p->csvH,lcp,&lcp,dsecs,0) != kOkCsvRC )
  2056. {
  2057. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'dsecs'.");
  2058. goto errLabel;
  2059. }
  2060. // col 5 : secs
  2061. if( cmCsvInsertDoubleColAfter(p->csvH,lcp,&lcp,secs,0) != kOkCsvRC )
  2062. {
  2063. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'secs'.");
  2064. goto errLabel;
  2065. }
  2066. // cols 6,7,8 blanks
  2067. if((rc = _cmXScoreWriteCsvBlankCols(p,3,&lcp)) != kOkXsRC )
  2068. goto errLabel;
  2069. // col 9 : d0
  2070. if( cmCsvInsertUIntColAfter(p->csvH,lcp,&lcp,d0,0) != kOkCsvRC )
  2071. {
  2072. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'd0'.");
  2073. goto errLabel;
  2074. }
  2075. // col 10 : d1
  2076. if( cmCsvInsertUIntColAfter(p->csvH,lcp,&lcp,d1,0) != kOkCsvRC )
  2077. {
  2078. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'd1'.");
  2079. goto errLabel;
  2080. }
  2081. // col 11 : pitch
  2082. if( pitch == -1 )
  2083. {
  2084. if((rc = _cmXScoreWriteCsvBlankCols(p,1,&lcp)) != kOkXsRC )
  2085. goto errLabel;
  2086. }
  2087. else
  2088. {
  2089. if( cmCsvInsertIdentColAfter(p->csvH,lcp,&lcp,cmMidiToSciPitch(pitch,NULL,0),0) != kOkCsvRC )
  2090. {
  2091. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'pitch'.");
  2092. goto errLabel;
  2093. }
  2094. }
  2095. // col 12 : blanks
  2096. if((rc = _cmXScoreWriteCsvBlankCols(p,1 + (cmIsFlag(flags,kBarXsFl) ? 0 : 1), &lcp)) != kOkXsRC )
  2097. goto errLabel;
  2098. // col 13 : bar number
  2099. if( cmIsFlag(flags,kBarXsFl) )
  2100. {
  2101. if( cmCsvInsertUIntColAfter(p->csvH,lcp,&lcp,bar,0) != kOkCsvRC )
  2102. {
  2103. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'pitch'.");
  2104. goto errLabel;
  2105. }
  2106. }
  2107. // col 14 : skip (blank for now)
  2108. if((rc = _cmXScoreWriteCsvBlankCols(p,1,&lcp)) != kOkXsRC )
  2109. goto errLabel;
  2110. // col 15: even (all grace notes are 'even' notes
  2111. if( cmCsvInsertQTextColAfter(p->csvH,lcp,&lcp, evenStr, 0) != kOkCsvRC )
  2112. {
  2113. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on eveness flag label.");
  2114. goto errLabel;
  2115. }
  2116. // col 16: grace
  2117. if( cmCsvInsertIdentColAfter(p->csvH,lcp,&lcp,cmIsFlag(flags,kGraceXsFl) ? "g" : "",0) != kOkCsvRC )
  2118. {
  2119. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on eveness flag label.");
  2120. goto errLabel;
  2121. }
  2122. // col 17: tempo
  2123. if( cmCsvInsertQTextColAfter(p->csvH,lcp,&lcp,tempoStr,0) != kOkCsvRC )
  2124. {
  2125. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on eveness flag label.");
  2126. goto errLabel;
  2127. }
  2128. // col 18: frac
  2129. if( frac == 0 )
  2130. {
  2131. if((rc = _cmXScoreWriteCsvBlankCols(p,1,&lcp)) != kOkXsRC )
  2132. goto errLabel;
  2133. }
  2134. else
  2135. {
  2136. if( cmCsvInsertDoubleColAfter(p->csvH,lcp,&lcp,1.0/frac,0) != kOkCsvRC )
  2137. {
  2138. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 't frac'.");
  2139. goto errLabel;
  2140. }
  2141. }
  2142. // col 19: dynamic marking
  2143. if( cmCsvInsertQTextColAfter(p->csvH, lcp, &lcp, dynStr, 0 ) != kOkCsvRC )
  2144. {
  2145. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on 'dynamics'.");
  2146. goto errLabel;
  2147. }
  2148. //if((rc = _cmXScoreWriteCsvBlankCols(p,1,&lcp)) != kOkXsRC )
  2149. // goto errLabel;
  2150. // col 20: section
  2151. if( cmCsvInsertIdentColAfter(p->csvH,lcp,&lcp,sectionStr!=NULL ? sectionStr : "",0) != kOkCsvRC )
  2152. {
  2153. rc = cmErrMsg(&p->err,kCsvFailXsRC,"CSV insert failed on eveness flag label.");
  2154. goto errLabel;
  2155. }
  2156. // col 21, 22 : recd-play, remark (blank for now)
  2157. if((rc = _cmXScoreWriteCsvBlankCols(p,2,&lcp)) != kOkXsRC )
  2158. goto errLabel;
  2159. errLabel:
  2160. return rc;
  2161. }
  2162. cmXsRC_t cmXScoreWriteCsv( cmXsH_t h, const cmChar_t* csvFn )
  2163. {
  2164. cmXsRC_t rc = kOkXsRC;
  2165. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  2166. unsigned rowIdx = 1;
  2167. const cmChar_t* sectionIdStr = NULL;
  2168. if( !cmCsvIsValid(p->csvH) )
  2169. return cmErrMsg(&p->err,kCsvFailXsRC,"The CSV output object is not initialized.");
  2170. if((rc = _cmXScoreWriteCsvHdr( p )) != kOkXsRC )
  2171. goto errLabel;
  2172. cmXsPart_t* pp = p->partL;
  2173. for(; pp!=NULL; pp=pp->link)
  2174. {
  2175. cmXsMeas_t* mp = pp->measL;
  2176. for(; mp!=NULL; mp=mp->link)
  2177. {
  2178. cmXsNote_t* np = mp->noteL;
  2179. for(; np!=NULL; np=np->slink)
  2180. {
  2181. // if this is a section event
  2182. if( cmIsFlag(np->flags,kSectionXsFl) )
  2183. sectionIdStr = np->tvalue;
  2184. // if this is a bar event
  2185. if( cmIsFlag(np->flags,kBarXsFl) )
  2186. {
  2187. _cmXScoreWriteCsvRow(p,rowIdx,-1,mp->number,sectionIdStr,"bar",np->dsecs,np->secs,0,0,-1,0,"",np->flags,"","");
  2188. sectionIdStr = NULL;
  2189. }
  2190. else
  2191. {
  2192. // if this is a pedal event
  2193. if( cmIsFlag(np->flags,kDampDnXsFl|kDampUpXsFl|kDampUpDnXsFl|kSostDnXsFl|kSostUpXsFl) )
  2194. {
  2195. unsigned d0 = cmIsFlag(np->flags,kSostDnXsFl |kSostUpXsFl) ? 66 : 64; // pedal MIDI ctl id
  2196. unsigned d1 = cmIsFlag(np->flags,kDampDnXsFl|kSostDnXsFl) ? 64 : 0; // pedal-dn: d1>=64 pedal-up:<64
  2197. _cmXScoreWriteCsvRow(p,rowIdx,-1,mp->number,sectionIdStr,"ctl",np->dsecs,np->secs,d0,d1,-1,0,"",np->flags,"","");
  2198. sectionIdStr = NULL;
  2199. if( cmIsFlag(np->flags,kDampUpDnXsFl) )
  2200. {
  2201. rowIdx += 1;
  2202. double millisecond = 0.0;
  2203. _cmXScoreWriteCsvRow(p,rowIdx,-1,mp->number,sectionIdStr,"ctl",millisecond,np->secs+millisecond,d0,64,-1,0,"",np->flags,"","");
  2204. }
  2205. }
  2206. else
  2207. {
  2208. // if this is a sounding note event
  2209. if( cmIsFlag(np->flags,kOnsetXsFl) )
  2210. {
  2211. unsigned bufN = 128;
  2212. cmChar_t ebuf[ bufN+1]; ebuf[bufN] = 0;
  2213. cmChar_t dbuf[ bufN+1]; dbuf[bufN] = 0;
  2214. cmChar_t tbuf[ bufN+1]; tbuf[bufN] = 0;
  2215. double frac = np->rvalue + (cmIsFlag(np->flags,kDotXsFl) ? (np->rvalue/2) : 0);
  2216. const cmChar_t* dyn = _cmXScoreTranslateDynamics( p, np, dbuf, bufN );
  2217. unsigned vel = np->vel==0 ? 60 : np->vel;
  2218. //
  2219. _cmXScoreWriteCsvRow(p,rowIdx,np->uid,mp->number,sectionIdStr,"non",np->dsecs,np->secs,np->pitch,vel,np->pitch,frac,dyn,np->flags,
  2220. cmXsFormatMeasurementCsvField(np->flags, kEvenXsFl, 'e', np->evenGroupId, ebuf, bufN ),
  2221. cmXsFormatMeasurementCsvField(np->flags, kTempoXsFl,'t', np->tempoGroupId, tbuf, bufN ));
  2222. sectionIdStr = NULL;
  2223. }
  2224. }
  2225. }
  2226. rowIdx += 1;
  2227. }
  2228. }
  2229. }
  2230. // Section labels are output on the next bar/pedal/note
  2231. // but what if there is no bar pedal note-on after the section label
  2232. if( sectionIdStr != NULL )
  2233. cmErrMsg(&p->err,kSyntaxErrorXsRC,"The section label '%s' was ignored because it was not followed by a score event.",sectionIdStr);
  2234. if( cmCsvWrite( p->csvH, csvFn ) != kOkCsvRC )
  2235. rc = cmErrMsg(&p->err,kCsvFailXsRC,"The CSV output write failed on file '%s'.",csvFn);
  2236. errLabel:
  2237. return rc;
  2238. }
  2239. void _cmXScoreReportTitle( cmRpt_t* rpt )
  2240. {
  2241. cmRptPrintf(rpt," idx voc loc tick durtn rval flags\n");
  2242. cmRptPrintf(rpt," --- --- ----- ------- ----- ---- --- ---------------\n");
  2243. }
  2244. void _cmXScoreReportNote( cmRpt_t* rpt, const cmXsNote_t* note,unsigned index )
  2245. {
  2246. const cmChar_t* B = cmIsFlag(note->flags,kBarXsFl) ? "|" : "-";
  2247. const cmChar_t* R = cmIsFlag(note->flags,kRestXsFl) ? "R" : "-";
  2248. const cmChar_t* G = cmIsFlag(note->flags,kGraceXsFl) ? "G" : "-";
  2249. const cmChar_t* D = cmIsFlag(note->flags,kDotXsFl) ? "." : "-";
  2250. const cmChar_t* C = cmIsFlag(note->flags,kChordXsFl) ? "C" : "-";
  2251. const cmChar_t* e = cmIsFlag(note->flags,kEvenXsFl) ? "e" : "-";
  2252. const cmChar_t* d = cmIsFlag(note->flags,kDynXsFl) ? "d" : "-";
  2253. const cmChar_t* t = cmIsFlag(note->flags,kTempoXsFl) ? "t" : "-";
  2254. const cmChar_t* P = cmIsFlag(note->flags,kDampDnXsFl) ? "V" : "-";
  2255. const cmChar_t* s = cmIsFlag(note->flags,kSostDnXsFl) ? "{" : "-";
  2256. const cmChar_t* S = cmIsFlag(note->flags,kSectionXsFl) ? "S" : "-";
  2257. const cmChar_t* H = cmIsFlag(note->flags,kHeelXsFl) ? "H" : "-";
  2258. const cmChar_t* T0 = cmIsFlag(note->flags,kTieBegXsFl) ? "T" : "-";
  2259. const cmChar_t* T1 = cmIsFlag(note->flags,kTieEndXsFl) ? "_" : "-";
  2260. const cmChar_t* O = cmIsFlag(note->flags,kOnsetXsFl) ? "*" : "-";
  2261. P = cmIsFlag(note->flags,kDampUpXsFl) ? "^" : P;
  2262. P = cmIsFlag(note->flags,kDampUpDnXsFl) ? "X" : P;
  2263. s = cmIsFlag(note->flags,kSostUpXsFl) ? "}" : s;
  2264. //const cmChar_t* N = note->pitch==0 ? " " : cmMidiToSciPitch( note->pitch, NULL, 0 );
  2265. cmChar_t N[] = {'\0','\0','\0','\0'};
  2266. cmChar_t acc = note->alter==-1?'b':(note->alter==1?'#':' ');
  2267. snprintf(N,4,"%c%c%1i",note->step,acc,note->octave);
  2268. 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",
  2269. index,
  2270. note->voice->id,
  2271. note->locIdx,
  2272. note->tick,
  2273. note->duration,
  2274. note->rvalue,
  2275. N,B,R,G,D,C,e,d,t,P,s,S,H,T0,T1,O);
  2276. if( cmIsFlag(note->flags,kSectionXsFl) )
  2277. cmRptPrintf(rpt," %s",cmStringNullGuard(note->tvalue));
  2278. if( cmIsFlag(note->flags,kMetronomeXsFl) )
  2279. cmRptPrintf(rpt," %i bpm",note->duration);
  2280. if( note->evenGroupId != 0 )
  2281. cmRptPrintf(rpt," e=%i",note->evenGroupId);
  2282. if( note->dynGroupId != 0 )
  2283. cmRptPrintf(rpt," d=%i",note->dynGroupId);
  2284. if( note->tempoGroupId != 0 )
  2285. cmRptPrintf(rpt," t=%i",note->tempoGroupId);
  2286. if( note->graceGroupId != 0)
  2287. cmRptPrintf(rpt," g=%i",note->graceGroupId);
  2288. }
  2289. void cmXScoreReport( cmXsH_t h, cmRpt_t* rpt, bool sortFl )
  2290. {
  2291. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  2292. cmXsPart_t* pp = p->partL;
  2293. for(; pp!=NULL; pp=pp->link)
  2294. {
  2295. cmRptPrintf(rpt,"Part:%s\n",pp->idStr);
  2296. const cmXsMeas_t* meas = pp->measL;
  2297. for(; meas!=NULL; meas=meas->link)
  2298. {
  2299. unsigned idx = 0;
  2300. 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);
  2301. _cmXScoreReportTitle(rpt);
  2302. if( sortFl )
  2303. {
  2304. const cmXsNote_t* note = meas->noteL;
  2305. unsigned t0 = 0;
  2306. unsigned t1 = 0;
  2307. for(; note!=NULL; note=note->slink,++idx)
  2308. {
  2309. _cmXScoreReportNote(rpt,note,idx);
  2310. t1 = note->slink==NULL ? note->tick : note->slink->tick;
  2311. if( !(t0 <= note->tick && note->tick <= t1) )
  2312. {
  2313. cmRptPrintf(rpt," +");
  2314. }
  2315. t0 = note->tick;
  2316. if( note->slink!=NULL || note->voice->id==0)
  2317. cmRptPrintf(rpt,"\n");
  2318. else
  2319. cmRptPrintf(rpt," %i\n", note->tick + note->duration);
  2320. }
  2321. }
  2322. else
  2323. {
  2324. const cmXsVoice_t* v = meas->voiceL;
  2325. for(; v!=NULL; v=v->link)
  2326. {
  2327. const cmXsNote_t* note = v->noteL;
  2328. cmRptPrintf(rpt," voice:%i\n",v->id);
  2329. for(; note!=NULL; note=note->mlink)
  2330. {
  2331. _cmXScoreReportNote(rpt,note,idx);
  2332. if( note->mlink!=NULL || note->voice->id==0)
  2333. cmRptPrintf(rpt,"\n");
  2334. else
  2335. cmRptPrintf(rpt," %i\n", note->tick + note->duration);
  2336. }
  2337. }
  2338. }
  2339. }
  2340. }
  2341. }
  2342. cmXsRC_t _cmXsWriteMidiFile( cmCtx_t* ctx, cmXsH_t h, const cmChar_t* dir, const cmChar_t* fn )
  2343. {
  2344. cmXsRC_t rc = kOkXsRC;
  2345. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  2346. if( p->partL==NULL || p->partL->measL == NULL )
  2347. return rc;
  2348. cmMidiFileH_t mfH = cmMidiFileNullHandle;
  2349. unsigned trkN = 2;
  2350. unsigned ticksPerQN = p->partL->measL->divisions;
  2351. const cmChar_t* outFn = cmFsMakeFn(dir,fn,"mid",NULL);
  2352. if( cmMidiFileCreate( ctx, &mfH, trkN, ticksPerQN ) != kOkMfRC )
  2353. return cmErrMsg(&p->err,kMidiFailXsRC,"Unable to create the MIDI file object.");
  2354. cmXsPart_t* pp = p->partL;
  2355. // for each part
  2356. for(; pp!=NULL; pp=pp->link)
  2357. {
  2358. cmXsMeas_t* mp = pp->measL;
  2359. // for each measure
  2360. for(; mp!=NULL; mp=mp->link)
  2361. {
  2362. cmXsNote_t* np = mp->noteL;
  2363. if( mp->divisions != ticksPerQN )
  2364. 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);
  2365. // for each note in this measure
  2366. for(; np!=NULL; np=np->slink)
  2367. {
  2368. switch( np->flags & (kOnsetXsFl|kMetronomeXsFl|kDampDnXsFl|kDampUpDnXsFl|kSostDnXsFl) )
  2369. {
  2370. case kOnsetXsFl:
  2371. if( cmMidiFileInsertTrackChMsg(mfH, 1, np->tick, kNoteOnMdId, np->pitch, np->vel ) != kOkMfRC
  2372. ||cmMidiFileInsertTrackChMsg(mfH, 1, np->tick + np->duration, kNoteOffMdId, np->pitch, 0 ) != kOkMfRC )
  2373. {
  2374. rc = kMidiFailXsRC;
  2375. }
  2376. break;
  2377. case kDampDnXsFl:
  2378. case kDampUpDnXsFl:
  2379. case kSostDnXsFl:
  2380. {
  2381. cmMidiByte_t d0 = cmIsFlag(np->flags,kSostDnXsFl) ? kSostenutoCtlMdId : kSustainCtlMdId;
  2382. if( (cmMidiFileInsertTrackChMsg(mfH, 1, np->tick, kCtlMdId, d0, 127 ) != kOkMfRC )
  2383. ||(cmMidiFileInsertTrackChMsg(mfH, 1, np->tick + np->duration, kCtlMdId, d0, 0 ) != kOkMfRC ) )
  2384. {
  2385. rc = kMidiFailXsRC;
  2386. }
  2387. }
  2388. break;
  2389. case kMetronomeXsFl:
  2390. if( cmMidFileInsertTrackTempoMsg(mfH, 0, np->tick, np->duration ) != kOkMfRC )
  2391. rc = kMidiFailXsRC;
  2392. break;
  2393. case 0:
  2394. break;
  2395. default:
  2396. { assert(0); }
  2397. }
  2398. if( rc != kOkXsRC )
  2399. {
  2400. rc = cmErrMsg(&p->err,rc,"MIDI message insert failed on '%s'.",cmStringNullGuard(outFn));
  2401. goto errLabel;
  2402. }
  2403. }
  2404. }
  2405. }
  2406. if( cmMidiFileWrite(mfH,outFn) != kOkMfRC )
  2407. {
  2408. rc = cmErrMsg(&p->err,kMidiFailXsRC,"MIDI file write failed on '%s'.",cmStringNullGuard(outFn));
  2409. goto errLabel;
  2410. }
  2411. errLabel:
  2412. cmFsFreeFn(outFn);
  2413. if( cmMidiFileClose(&mfH) != kOkMfRC )
  2414. {
  2415. rc = cmErrMsg(&p->err,kMidiFailXsRC,"Unable to create the MIDI file object.");
  2416. goto errLabel;
  2417. }
  2418. return rc;
  2419. }
  2420. typedef struct cmXsSvgEvt_str
  2421. {
  2422. unsigned flags; // k???XsFl
  2423. unsigned tick; // start tick
  2424. unsigned durTicks; // dur-ticks
  2425. unsigned voice; // score voice number
  2426. unsigned d0; // MIDI d0 (barNumb)
  2427. unsigned d1; // MIDI d1
  2428. struct cmXsSvgEvt_str* link;
  2429. } cmXsSvgEvt_t;
  2430. typedef struct cmXsMidiFile_str
  2431. {
  2432. cmXsSvgEvt_t* elist;
  2433. cmXsSvgEvt_t* eol;
  2434. unsigned pitch_min;
  2435. unsigned pitch_max;
  2436. } cmXsMidiFile_t;
  2437. cmXsRC_t _cmXsWriteMidiSvg( cmCtx_t* ctx, cmXScore_t* p, cmXsMidiFile_t* mf, const cmChar_t* dir, const cmChar_t* fn )
  2438. {
  2439. cmXsRC_t rc = kOkXsRC;
  2440. cmSvgH_t svgH = cmSvgNullHandle;
  2441. cmXsSvgEvt_t* e = mf->elist;
  2442. unsigned noteHeight = 10;
  2443. const cmChar_t* svgFn = cmFsMakeFn(dir,fn,"html",NULL);
  2444. const cmChar_t* cssFn = cmFsMakeFn(NULL,fn,"css",NULL);
  2445. cmChar_t* t0 = NULL; // temporary dynamic string
  2446. // create the SVG writer
  2447. if( cmSvgWriterAlloc(ctx,&svgH) != kOkSvgRC )
  2448. {
  2449. rc = cmErrMsg(&p->err,kSvgFailXsRC,"Unable to create the MIDI SVG output file '%s'.",cmStringNullGuard(svgFn));
  2450. goto errLabel;
  2451. }
  2452. // for each MIDI file element
  2453. for(; e!=NULL && rc==kOkXsRC; e=e->link)
  2454. {
  2455. switch( e->flags & (kOnsetXsFl|kBarXsFl|kDampDnXsFl|kDampUpDnXsFl|kSostDnXsFl))
  2456. {
  2457. // if this is a note
  2458. case kOnsetXsFl:
  2459. {
  2460. const cmChar_t* classLabel = "note";
  2461. t0 = cmTsPrintfP(t0,"note_%i%s",e->voice, cmIsFlag(e->flags,kGraceXsFl) ? "_g":"");
  2462. if( cmIsFlag(e->flags,kGraceXsFl) )
  2463. classLabel = "grace";
  2464. if( cmSvgWriterRect(svgH, e->tick, e->d0 * noteHeight, e->durTicks, noteHeight-1, t0 ) != kOkSvgRC )
  2465. rc = kSvgFailXsRC;
  2466. else
  2467. if( cmSvgWriterText(svgH, e->tick + e->durTicks/2, e->d0 * noteHeight + noteHeight/2, cmMidiToSciPitch( e->d0, NULL, 0), "pitch") != kOkSvgRC )
  2468. rc = kSvgFailXsRC;
  2469. }
  2470. break;
  2471. // if this is a bar
  2472. case kBarXsFl:
  2473. {
  2474. if( cmSvgWriterLine(svgH, e->tick, 0, e->tick, 127*noteHeight, "bar") != kOkSvgRC )
  2475. rc = kSvgFailXsRC;
  2476. else
  2477. {
  2478. if( cmSvgWriterText(svgH, e->tick, 10, t0 = cmTsPrintfP(t0,"%i",e->d0), "text" ) != kOkSvgRC )
  2479. rc = kSvgFailXsRC;
  2480. }
  2481. }
  2482. break;
  2483. // if this is a pedal event
  2484. case kDampDnXsFl:
  2485. case kDampUpDnXsFl:
  2486. case kSostDnXsFl:
  2487. {
  2488. const cmChar_t* classLabel = cmIsFlag(e->flags,kSostDnXsFl) ? "sost" : "damp";
  2489. unsigned y = (128 + cmIsFlag(e->flags,kSostDnXsFl)?1:0) * noteHeight;
  2490. cmSvgWriterRect(svgH, e->tick, y, e->durTicks, noteHeight-1, classLabel);
  2491. }
  2492. break;
  2493. }
  2494. }
  2495. if( rc != kOkXsRC )
  2496. cmErrMsg(&p->err,kSvgFailXsRC,"SVG element insert failed.");
  2497. if( rc == kOkXsRC )
  2498. if( cmSvgWriterWrite(svgH,cssFn,svgFn) != kOkSvgRC )
  2499. rc = cmErrMsg(&p->err,kSvgFailXsRC,"SVG file write to '%s' failed.",cmStringNullGuard(svgFn));
  2500. errLabel:
  2501. cmSvgWriterFree(&svgH);
  2502. cmFsFreeFn(svgFn);
  2503. cmFsFreeFn(cssFn);
  2504. cmMemFree(t0);
  2505. return rc;
  2506. }
  2507. void _cmXsPushSvgEvent( cmXScore_t* p, cmXsMidiFile_t* mf, unsigned flags, unsigned tick, unsigned durTick, unsigned voice, unsigned d0, unsigned d1 )
  2508. {
  2509. cmXsSvgEvt_t* e = cmLhAllocZ(p->lhH,cmXsSvgEvt_t,1);
  2510. e->flags = flags;
  2511. e->tick = tick;
  2512. e->durTicks = durTick;
  2513. e->voice = voice;
  2514. e->d0 = d0; // note=pitch bar=number pedal=ctl# metronome=BPM
  2515. e->d1 = d1;
  2516. if( mf->eol != NULL )
  2517. mf->eol->link = e;
  2518. else
  2519. mf->elist = e;
  2520. // track the min/max pitch
  2521. if( cmIsFlag(flags,kOnsetXsFl) )
  2522. {
  2523. mf->pitch_min = mf->eol==NULL ? d0 : cmMin(mf->pitch_min,d0);
  2524. mf->pitch_max = mf->eol==NULL ? d0 : cmMin(mf->pitch_max,d0);
  2525. }
  2526. mf->eol = e;
  2527. }
  2528. cmXsRC_t _cmXScoreGenSvg( cmCtx_t* ctx, cmXsH_t h, const cmChar_t* dir, const cmChar_t* fn )
  2529. {
  2530. cmXScore_t* p = _cmXScoreHandleToPtr(h);
  2531. cmXsPart_t* pp = p->partL;
  2532. cmXsMidiFile_t mf;
  2533. memset(&mf,0,sizeof(mf));
  2534. for(; pp!=NULL; pp=pp->link)
  2535. {
  2536. const cmXsMeas_t* meas = pp->measL;
  2537. for(; meas!=NULL; meas=meas->link)
  2538. {
  2539. const cmXsNote_t* note = meas->noteL;
  2540. for(; note!=NULL; note=note->slink)
  2541. {
  2542. // if this is a metronome marker
  2543. if( cmIsFlag(note->flags,kMetronomeXsFl) )
  2544. {
  2545. // set BPM as d0
  2546. _cmXsPushSvgEvent(p,&mf,note->flags,note->tick,0,0,note->duration,0);
  2547. continue;
  2548. }
  2549. // if this is a sounding note
  2550. if( cmIsFlag(note->flags,kOnsetXsFl) )
  2551. {
  2552. unsigned d0 = cmSciPitchToMidiPitch( note->step, note->alter, note->octave );
  2553. unsigned durTick = note->duration;
  2554. if( note->tied != NULL )
  2555. {
  2556. cmXsNote_t* tn = note->tied;
  2557. for(; tn!=NULL; tn=tn->tied)
  2558. durTick += tn->duration;
  2559. }
  2560. _cmXsPushSvgEvent(p,&mf,note->flags,note->tick,durTick,note->voice->id,d0,note->vel);
  2561. continue;
  2562. }
  2563. // if this is a bar event
  2564. if( cmIsFlag(note->flags,kBarXsFl) )
  2565. {
  2566. _cmXsPushSvgEvent(p,&mf,note->flags,note->tick,0,0,note->meas->number,0);
  2567. continue;
  2568. }
  2569. // if this is a pedal event
  2570. if( cmIsFlag(note->flags,kDampDnXsFl|kDampUpDnXsFl|kSostDnXsFl) )
  2571. {
  2572. unsigned d0 = cmIsFlag(note->flags,kSostDnXsFl) ? kSostenutoCtlMdId : kSustainCtlMdId;
  2573. _cmXsPushSvgEvent(p,&mf,note->flags,note->tick,note->duration,0,d0,127);
  2574. continue;
  2575. }
  2576. }
  2577. }
  2578. }
  2579. return _cmXsWriteMidiSvg( ctx, p, &mf, dir, fn );
  2580. }
  2581. cmXsRC_t cmXScoreTest(
  2582. cmCtx_t* ctx,
  2583. const cmChar_t* xmlFn,
  2584. const cmChar_t* reorderFn,
  2585. const cmChar_t* csvOutFn,
  2586. const cmChar_t* midiOutFn)
  2587. {
  2588. cmXsRC_t rc;
  2589. cmXsH_t h = cmXsNullHandle;
  2590. if((rc = cmXScoreInitialize( ctx, &h, xmlFn)) != kOkXsRC )
  2591. return cmErrMsg(&ctx->err,rc,"XScore alloc failed.");
  2592. if( reorderFn != NULL )
  2593. cmXScoreReorder(h,reorderFn);
  2594. // assign durations to pedal down events
  2595. _cmXScoreProcessPedals(_cmXScoreHandleToPtr(h));
  2596. if( csvOutFn != NULL )
  2597. {
  2598. cmScH_t scH = cmScNullHandle;
  2599. double srate = 44100.0;
  2600. cmXScoreWriteCsv(h,csvOutFn);
  2601. cmSymTblH_t stH = cmSymTblCreate(cmSymTblNullHandle, 0, ctx );
  2602. if( cmScoreInitialize( ctx, &scH, csvOutFn, srate, NULL, 0, NULL, NULL, stH) != kOkScRC )
  2603. cmErrMsg(&ctx->err,kFileFailXsRC,"The generated CSV file could not be parsed.");
  2604. else
  2605. {
  2606. //cmScorePrintSets(scH,&ctx->rpt);
  2607. //cmScorePrint(scH,&ctx->rpt);
  2608. cmScoreFinalize(&scH);
  2609. }
  2610. cmSymTblDestroy(&stH);
  2611. }
  2612. if( midiOutFn != NULL )
  2613. {
  2614. cmFileSysPathPart_t* pp = cmFsPathParts(midiOutFn);
  2615. _cmXScoreGenSvg( ctx, h, pp->dirStr, pp->fnStr );
  2616. _cmXsWriteMidiFile(ctx, h, pp->dirStr, pp->fnStr );
  2617. cmFsFreePathParts(pp);
  2618. }
  2619. cmXScoreReport(h,&ctx->rpt,true);
  2620. return cmXScoreFinalize(&h);
  2621. }