libcm is a C development framework with an emphasis on audio signal processing applications.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

cmXScore.c 116KB

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