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

cmXScore.c 95KB

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