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

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