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

cmXScore.c 96KB

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