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

cmXScore.c 111KB

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