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

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