libcm is a C development framework with an emphasis on audio signal processing applications.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

cmXScore.c 96KB

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