libcm is a C development framework with an emphasis on audio signal processing applications.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

cmXScore.c 117KB

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