cdnz 0.1.2

An open data format for storing music
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
// SPDX-FileCopyrightText: 2026 Twilit Jack <twilit-jack@gmail.com>
// SPDX-License-Identifier: MIT OR Apache-2.0

#![doc = include_str!("../README.md")]

pub mod cdnz_serde;
pub mod lilypond;
pub mod upgrade;

pub use cdnz_serde::VersionInfo;
use cdnz_serde::*;
use serde_with::skip_serializing_none;

use std::collections::{BTreeMap, HashMap};

use num::Rational32;

use serde::{Deserialize, Serialize};

// =========================== ROOT ===========================

/// The root object of a CDNZ file.
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Cdnz {
	pub cdnz: Metadata,
	pub global: GlobalData,
	pub parts: HashMap<String, Part>,
	pub books: Vec<Book>,
}

impl ToString for Cdnz {
	fn to_string(&self) -> String {
		format!("{:#?}", self)
	}
}

/// Metadata about the CDNZ file in question.
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Metadata {
	/// The name/title for the music.
	///
	/// This is separate from the file name, because file names are ambiguous, and are often
	/// discouraged from including certain special/Unicode characters, including spaces.
	///
	/// This does not have to be the same as the title in the header of the books, but it's highly
	/// encouraged. It could be different in, for example, books with text in a different language.
	pub score_title: String,

	/// Info about the composer of the music.
	///
	/// The composer is the author of the base melody. This might also be the name of a folk, for
	/// rhapsodies or folk song arrangements.
	pub composer: PersonInfo,
	/// Info about the arranger of the music.
	///
	/// The arranger is the author of the accompanying bass and secondary melodies. This might be
	/// the same person as the composer for original works.
	pub arranger: PersonInfo,
	/// Info about the engraver of the music.
	///
	/// The engraver is the author of the exact layout and encoding of the music, i.e. the CDNZ file.
	/// This might be the same as the composer or arranger if they're doing their first work via
	/// CDNZ or Cadenza.
	pub engraver: PersonInfo,

	/// A description of the piece, typically given by the composer, including thoughts about the
	/// piece.
	pub description: String,

	/// A SPDX tag describing the licensing of the music/arrangement.
	///
	/// Can also be `Public-Domain`, which is used for expired copyright works (e.g. baroque,
	/// classical, romance works).
	pub music_license: String,
	/// A SPDX tag describing the licensing of the engraving/encoding.
	///
	/// If you want to waive your copyright, it's recommended to use `CC0-1.0` here, instead of
	/// `Public-Domain`.
	pub engraving_license: String,
}

#[derive(Debug, Serialize, Deserialize, Default)]
#[skip_serializing_none]
pub struct PersonInfo {
	/// The name of this person or entity.
	///
	/// See `is_person` for more info about "entity".
	pub name: String,

	/// The email through which this person or entity can be reached.
	///
	/// This is an `Option`, because some works might be composed by a historical composer, or the
	/// melody might be of a folk.
	pub email: Option<String>,

	/// Whether or not this info is about a person.
	///
	/// This may be false for bands, companies or a folk, in which case `name` doesn't mean the name
	/// of a person.
	pub is_person: bool,
}

// =========================== GLOBAL DATA ===========================

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct GlobalData {
	#[serde(
		serialize_with = "serialize_position_map",
		deserialize_with = "deserialize_position_map"
	)]
	pub modifier_events: BTreeMap<Position, Vec<GlobalModEvent>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum GlobalModEvent {
	KeyChange {
		/// The note this key change references.
		note: Pitch,
		/// The mode this key change uses, in reference to the note e.g. `Major`.
		mode: KeyMode,
	},

	/// A TimeChange defines a time signature change, changing the beat structure.
	TimeChange {
		/// The number on the top of the key signature.
		count: u16,
		/// The number on the bottom of the key signature.
		unit: u16,
	},

	/// A TempoChange defines a change of tempo, usually a BPM change, but it can
	/// also define a rhythm, e.g. swing.
	TempoChange {
		/// The BPM value this TempoChange changes it to.
		///
		/// While you might not want to always display it, it's still required. See `display_tempo`
		/// for hiding the numeric value.
		bpm: Bpm,

		/// Whether to display the new BPM as a metronome mark or to hide it.
		display_tempo: bool,

		/// What text label to have beside the metronome mark or standalone.
		///
		/// e.g. "Allegro", "Moderato".
		label: Option<String>,
	},
}

#[derive(Debug, Serialize, Deserialize)]
pub enum KeyMode {
	Major,
	Minor,

	// Currently disabled due to "do I need this?".
	// Might be changed in the future, I don't know a lot about church modes myself tbh.
	//Ionian,
	//Aeolian,
	Dorian,
	Phrygian,
	Lydian,
	Mixolydian,
	Locrian,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Bpm {
	pub unit: Rational32,
}

// =========================== PART ===========================

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Part {
	pub rhythmic_events: BTreeMap<Position, RhythmicEvent>,
	pub modifier_events: BTreeMap<Position, Vec<LocalModEvent>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum RhythmicEvent {
	Note { pitch: Pitch, duration: Duration },
	Rest { duration: Duration },
}

#[derive(Debug, Serialize, Deserialize)]
pub enum LocalModEvent {
	ClefChange {
		sign: ClefSign,

		/// The staff position of the clef, in increments of half a staff line, starting at the
		/// middle line.
		///
		/// Examples:
		/// - Treble: -2
		/// - Bass: 2
		/// - Alto: 0
		pos: i32,

		/// The octave transposition for a clef.
		///
		/// Usually 0, but changes for things like a "treble_8" clef (where it would be `-8`).
		octave: i32,
	},
}

impl LocalModEvent {
	/// A helper function for creating a basic treble clef.
	pub fn new_treble_clef() -> LocalModEvent {
		LocalModEvent::ClefChange {
			sign: ClefSign::G,
			pos: -2,
			octave: 0,
		}
	}
	/// A helper function for creating a basic bass clef.
	pub fn new_bass_clef() -> LocalModEvent {
		LocalModEvent::ClefChange {
			sign: ClefSign::F,
			pos: 2,
			octave: 0,
		}
	}
	/// A helper function for creating a basic alto clef.
	pub fn new_alto_clef() -> LocalModEvent {
		LocalModEvent::ClefChange {
			sign: ClefSign::C,
			pos: 0,
			octave: 0,
		}
	}
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ClefSign {
	G,
	F,
	C,
}

// =========================== BOOK ===========================

#[derive(Debug, Serialize, Deserialize)]
pub struct Book {
	pub label: String,
	pub header: Header,
	pub layout: Layout,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Header {}

#[derive(Debug, Serialize, Deserialize)]
pub enum Layout {
	Staff(Staff),
	StaffGroup(StaffGroup),
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Staff {
	/// Contains string keys linking to the parts in the root CDNZ struct.
	pub parts: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct StaffGroup {
	pub children: Vec<Layout>,
}

// =========================== PRIMITIVES ===========================

#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Position {
	/// The measure index this position is in/is relative to.
	pub measure: u32,

	/// The position in the measure as a rational.
	///
	/// (0, 1) would be the start of the measure, (1, 2) – halfway through.
	pub pos: Rational32,

	pub grace_index: u32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Pitch {
	/// A whole step, beginning at middle C.
	///
	/// Examples:
	/// - C4 (middle C): 0
	/// - A4 (concert pitch): 5
	/// - C5: 7
	/// - C3: -7
	pub step: i32,

	/// Alteration of the note, with 1/1 being a whole tone.
	///
	/// Examples:
	/// - Natural: (0, 1)
	/// - Sharp: Some((1, ))
	pub alteration: Rational32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Duration {
	/// The `logâ‚‚(x)` of the base duration of the note.
	///
	/// Examples:
	/// - Whole note: 0
	/// - Half note: 1
	/// - Quarter note: 2
	/// - Eighth note: 3
	/// - Breve: -1
	pub base: i16,

	/// The number of dots on this note.
	///
	/// Examples:
	/// - Not dotted: 0
	/// - Dotted: 1
	/// - Double-dotted: 2,
	pub dots: u16,
}

#[cfg(test)]
mod tests {
	use super::*;

	fn create_test_cdnz() -> Cdnz {
		Cdnz {
			cdnz: Metadata {
				score_title: "Symphony No. 5".to_string(),

				composer: PersonInfo {
					name: "Ludwig van Beethoven".to_string(),
					email: None,
					is_person: true,
				},
				arranger: PersonInfo {
					name: "Twilit Jack".to_string(),
					email: Some("twilit.jack@proton.me".to_string()),
					is_person: true,
				},
				engraver: PersonInfo {
					name: "Twilit Jack".to_string(),
					email: Some("twilit.jack@proton.me".to_string()),
					is_person: true,
				},

				description: "Symphony No. 5 in C minor of Ludwig van Beethoven, Op. 67, written \
					between 1804 and 1808.\n\n\
					It is one of the best-known compositions in classical music."
					.to_string(),

				music_license: "Public-Domain".to_string(),
				engraving_license: "CC0-1.0".to_string(),
			},

			global: GlobalData {
				modifier_events: BTreeMap::from([(
					Position {
						measure: 0,
						pos: Rational32::default(),
						grace_index: 0,
					},
					Vec::from([
						GlobalModEvent::KeyChange {
							note: Pitch {
								step: 0,
								alteration: Rational32::default(),
							},
							mode: KeyMode::Minor,
						},
						GlobalModEvent::TimeChange { count: 2, unit: 4 },
					]),
				)]),
			},

			parts: HashMap::from([(
				"piano".to_string(),
				Part {
					rhythmic_events: BTreeMap::from([
						(
							Position {
								measure: 0,
								pos: Rational32::default(),
								grace_index: 0,
							},
							RhythmicEvent::Rest {
								duration: Duration { base: 3, dots: 0 },
							},
						),
						(
							Position {
								measure: 0,
								pos: Rational32::new(1, 4),
								grace_index: 0,
							},
							RhythmicEvent::Note {
								pitch: Pitch {
									step: 4,
									alteration: Rational32::default(),
								},
								duration: Duration { base: 3, dots: 0 },
							},
						),
						(
							Position {
								measure: 0,
								pos: Rational32::new(2, 4),
								grace_index: 0,
							},
							RhythmicEvent::Note {
								pitch: Pitch {
									step: 4,
									alteration: Rational32::default(),
								},
								duration: Duration { base: 3, dots: 0 },
							},
						),
						(
							Position {
								measure: 0,
								pos: Rational32::new(3, 4),
								grace_index: 0,
							},
							RhythmicEvent::Note {
								pitch: Pitch {
									step: 4,
									alteration: Rational32::default(),
								},
								duration: Duration { base: 3, dots: 0 },
							},
						),
						(
							Position {
								measure: 1,
								pos: Rational32::default(),
								grace_index: 0,
							},
							RhythmicEvent::Note {
								pitch: Pitch {
									step: 2,
									alteration: Rational32::new(-1, 2),
								},
								duration: Duration { base: 0, dots: 0 },
							},
						),
					]),
					modifier_events: BTreeMap::from([]),
				},
			)]),

			books: Vec::from([Book {
				label: "Final Score".to_string(),
				header: Header {},
				layout: Layout::Staff(Staff {
					parts: Vec::from(["piano".to_string()]),
				}),
			}]),
		}
	}

	#[test]
	fn test_round_trip() {
		let original = create_test_cdnz();

		let serialized = original.serialize().expect("Serialization failed");
		let deserialized = Cdnz::deserialize(&serialized).expect("Deserialization failed");

		assert_eq!(format!("{:?}", original), format!("{:?}", deserialized));
	}

	#[test]
	fn test_view_json() {
		let original = create_test_cdnz();

		let json = serde_json::to_string_pretty(&original).expect("JSON serialization failed");
		println!("{}", json);
	}
}