Debian Codegraph @

similar/main/songs.cpp

raw
1 /*
2 * Portions of this file are copyright Rebirth contributors and licensed as
3 * described in COPYING.txt.
4 * Portions of this file are copyright Parallax Software and licensed
5 * according to the Parallax license below.
6 * See COPYING.txt for license details.
7
8 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
9 SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
10 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
11 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
12 IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
13 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
14 FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
15 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
16 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
17 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
18 */
19
20 /*
21 *
22 * Routines to manage the songs in Descent.
23 *
24 */
25
26 #include <iterator>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include "dxxerror.h"
32 #include "pstypes.h"
33 #include "songs.h"
34 #include "strutil.h"
35 #include "digi.h"
36 #include "rbaudio.h"
37 #if DXX_USE_SDLMIXER
38 #include "digi_mixer_music.h"
39 #endif
40 #include "jukebox.h"
41 #include "config.h"
42 #include "u_mem.h"
43 #include "args.h"
44 #include "physfsx.h"
45 #include "game.h"
46 #include "console.h"
47 #include <memory>
48
49 namespace dcx {
50
51 namespace {
52
53 enum class level_song_number : unsigned
54 {
55 None = UINT32_MAX
56 };
57
58 class user_configured_level_songs : std::unique_ptr<bim_song_info[]>
59 {
60 using base_type = std::unique_ptr<bim_song_info[]>;
61 std::size_t count{};
62 public:
63 constexpr user_configured_level_songs() = default;
64 explicit user_configured_level_songs(const std::size_t length) :
65 base_type{std::make_unique<bim_song_info[]>(length)}, count{length}
66 {
67 }
68 auto size() const
69 {
70 return count;
71 }
72 void reset()
73 {
74 count = {};
75 base_type::reset();
76 }
77 void resize(const std::size_t length)
78 {
79 base_type::operator=(std::make_unique<bim_song_info[]>(length));
80 count = {length};
81 }
82 bim_song_info &operator[](const song_number i) const
83 {
84 return base_type::operator[](static_cast<std::size_t>(i));
85 }
86 user_configured_level_songs &operator=(user_configured_level_songs &&) = default;
87 void operator=(std::vector<bim_song_info> &&v);
88 };
89
90 void user_configured_level_songs::operator=(std::vector<bim_song_info> &&v)
91 {
92 if (v.empty())
93 {
94 /* If the vector is empty, use `reset` so that this object
95 * stores `nullptr` instead of a pointer to a zero-length array.
96 * Storing `nullptr` causes `operator bool()` to return false.
97 * Storing a zero-length array causes `operator bool()` to
98 * return true.
99 *
100 * A true return causes a divide-by-zero later when the object
101 * is considered true, but then reports a length of zero.
102 */
103 reset();
104 return;
105 }
106 resize(v.size());
107 std::ranges::move(v, this->get());
108 }
109
110 static song_number build_song_number_from_level_song_number(const level_song_number i)
111 {
112 return song_number{underlying_value(i) + underlying_value(song_number::first_level_song)};
113 }
114
115 static song_number Song_playing{song_number::None}; // song_number::None if no song playing, else the Descent song number
116 #if DXX_USE_SDL_REDBOOK_AUDIO
117 static int Redbook_playing = 0; // Redbook track num differs from Song_playing. We need this for Redbook repeat hooks.
118 #endif
119
120 user_configured_level_songs BIMSongs;
121 user_configured_level_songs BIMSecretSongs;
122
123 }
124
125 song_number songs_is_playing()
126 {
127 return Song_playing;
128 }
129
130 //takes volume in range 0..8
131 //NOTE that we do not check what is playing right now (except Redbook) This is because here we don't (want) know WHAT we're playing - let the subfunctions do it (i.e. digi_win32_set_music_volume() knows if a MIDI plays or not)
132 void songs_set_volume(int volume)
133 {
134 #ifdef _WIN32
135 digi_win32_set_midi_volume(volume);
136 #endif
137 #if DXX_USE_SDL_REDBOOK_AUDIO
138 if (CGameCfg.MusicType == music_type::Redbook)
139 {
140 RBASetVolume(0);
141 RBASetVolume(volume);
142 }
143 #else
144 (void)volume;
145 #endif
146 #if DXX_USE_SDLMIXER
147 mix_set_music_volume(volume);
148 #endif
149 }
150
151 namespace {
152
153 struct deferred_physfs_pathname
154 {
155 std::optional<const char *> dirname;
156 const char *const physfs_virtual_path;
157 deferred_physfs_pathname(const char *p) :
158 physfs_virtual_path{p}
159 {
160 }
161 const char *get_dirname();
162 };
163
164 const char *deferred_physfs_pathname::get_dirname()
165 {
166 if (!dirname)
167 {
168 const auto r{PHYSFS_getRealDir(physfs_virtual_path)};
169 dirname = r;
170 return r;
171 }
172 return *dirname;
173 }
174
175 static bool is_valid_song_extension(const std::ranges::subrange<std::span<char>::iterator> extension)
176 {
177 /* This is a special purpose tolower, which only works due to the special
178 * circumstances in this function.
179 * - the user-supplied `extension` may be any set of characters, including
180 * non-letters
181 * - candidate extensions are known to be lowercase letters only, and are
182 * not transformed
183 * - applying this transform to a user-defined input character has 3 cases:
184 * - if the input is ASCII uppercase, it becomes ASCII lowercase
185 * - if the input is ASCII lowercase, it is unchanged
186 * - if the input is not a letter, it is changed to some other non-letter
187 * Since the comparison only seeks matches, and all candidate extensions
188 * are all lowercase letters, changing one non-letter to a different
189 * non-letter preserves the inequality.
190 */
191 auto &&lower_letter = [](const char c) -> char {
192 return c | ('a' - 'A');
193 };
194 using namespace std::string_view_literals;
195 #define SONG_STRING_VIEW_CONCAT_UDL(EXTENSION) EXTENSION##sv
196 #define SONG_STRING_VIEW(EXTENSION) SONG_STRING_VIEW_CONCAT_UDL(EXTENSION)
197 const auto is_HMP{std::ranges::equal(extension, SONG_STRING_VIEW(SONG_EXT_HMP), {}, lower_letter)};
198 #if DXX_USE_SDLMIXER
199 if (!is_HMP)
200 {
201 if (const auto is_MID{std::ranges::equal(extension, SONG_STRING_VIEW(SONG_EXT_MID), {}, lower_letter)})
202 return is_MID;
203 if (const auto is_OGG{std::ranges::equal(extension, SONG_STRING_VIEW(SONG_EXT_OGG), {}, lower_letter)})
204 return is_OGG;
205 if (const auto is_FLAC{std::ranges::equal(extension, SONG_STRING_VIEW(SONG_EXT_FLAC), {}, lower_letter)})
206 return is_FLAC;
207 if (const auto is_MP3{std::ranges::equal(extension, SONG_STRING_VIEW(SONG_EXT_MP3), {}, lower_letter)})
208 return is_MP3;
209 }
210 #endif
211 #undef SONG_STRING_VIEW
212 #undef SONG_STRING_VIEW_CONCAT_UDL
213 return is_HMP;
214 }
215
216 template <std::size_t N>
217 requires(
218 /* Compile-time check that the input string will not overflow the output
219 * buffer.
220 */
221 requires(bim_song_info song) {
222 requires(std::size(song.filename) >= N);
223 }
224 )
225 static inline void assign_builtin_song(bim_song_info &song, const char (&str)[N])
226 {
227 std::ranges::copy(str, std::ranges::begin(song.filename));
228 }
229
230 static void add_song(deferred_physfs_pathname &pathname, const unsigned lineno, std::vector<bim_song_info> &songs, const std::ranges::subrange<std::span<char>::iterator> entry_input)
231 {
232 /* Some versions of `descent.sng` are not a simple list of songs, but
233 * instead have a song, whitespace, and then other text on the line. The
234 * original parser used sscanf to extract the filename, which caused the
235 * extraction to stop on the first whitespace. Implement an equivalent
236 * early stop here, by scanning the input range for whitespace. When no
237 * whitespace is found, `input == entry_input`.
238 */
239 const std::ranges::subrange<std::span<char>::iterator> input{
240 entry_input.begin(),
241 std::ranges::find_if(entry_input, [](const char c) { return std::isspace(static_cast<unsigned>(c)); })
242 };
243 static constexpr std::size_t maximum_song_filename_characters_to_print{20 /* arbitrary cap to balance full output versus flooding the user's terminal */};
244 const auto clamp_filename_characters_count{[](const std::size_t actual_size) -> int {
245 return static_cast<int>(std::min(actual_size, maximum_song_filename_characters_to_print));
246 }};
247 const auto get_filename_truncation_hint_text{[](const std::size_t actual_size) {
248 return actual_size > maximum_song_filename_characters_to_print ? " (truncated)" : "";
249 }};
250 const std::size_t input_size{input.size()};
251 if (const std::size_t limit{std::tuple_size<decltype(bim_song_info::filename)>::value - 1}; input_size > limit)
252 {
253 /* Drop excessively long filenames. */
254 con_printf(CON_NORMAL, "warning: song file \"%s\"/\"%s\":%u: ignoring excessively long filename; maximum allowed length is %" DXX_PRI_size_type ", but found %" DXX_PRI_size_type " (\"%.*s\"%s)", pathname.get_dirname(), pathname.physfs_virtual_path, lineno, limit, input_size, clamp_filename_characters_count(input_size), input.data(), get_filename_truncation_hint_text(input_size));
255 return;
256 }
257 auto &&reverse_input{std::ranges::views::reverse(input)};
258 if (const auto &&ri_dot{std::ranges::find(reverse_input, '.')}; ri_dot == reverse_input.end())
259 {
260 if (entry_input.size() == 1 && *entry_input.begin() == 0x1a)
261 /* Descent v1.5 ships a `descent.hog` that contains a `descent.sng`
262 * that has a line consisting only of this one byte. Suppress the
263 * warning, so that users do not need to override the retail song
264 * file to silence the diagnostic.
265 */
266 return;
267 /* Drop filenames that lack a dot. */
268 con_printf(CON_NORMAL, "warning: song file \"%s\"/\"%s\":%u: ignoring filename with no dot (\"%.*s\"%s[%" DXX_PRI_size_type "])", pathname.get_dirname(), pathname.physfs_virtual_path, lineno, clamp_filename_characters_count(input_size), input.data(), get_filename_truncation_hint_text(input_size), input_size);
269 return;
270 }
271 /* Due to `std::reverse_iterator` rules, `reverse_iterator::operator*()`
272 * returns `*std::prev(reverse_iterator::base())`, so `find` returns an
273 * iterator one forward of the '.'. Therefore, `.base()` points to the
274 * first character in the extension, not to the dot.
275 */
276 else if (const std::ranges::subrange extension{ri_dot.base(), input.end()}; !is_valid_song_extension(extension))
277 {
278 /* Drop filenames that lack a valid song extension. */
279 #if DXX_USE_SDLMIXER
280 #define DXX_ADD_SONG_EXTENSION_HINT "s: " SONG_EXT_MID ", " SONG_EXT_OGG ", " SONG_EXT_FLAC ", " SONG_EXT_MP3 ", "
281 #else
282 #define DXX_ADD_SONG_EXTENSION_HINT ": "
283 #endif
284 const std::size_t extension_size{extension.size()};
285 con_printf(CON_NORMAL, "warning: song file \"%s\"/\"%s\":%u: ignoring filename with unacceptable filename extension (\"%.*s\"%s[%" DXX_PRI_size_type "]) on filename (\"%.*s\"%s[%" DXX_PRI_size_type "]); acceptable value" DXX_ADD_SONG_EXTENSION_HINT SONG_EXT_HMP, pathname.get_dirname(), pathname.physfs_virtual_path, lineno, clamp_filename_characters_count(extension_size), extension.data(), get_filename_truncation_hint_text(extension_size), extension_size, clamp_filename_characters_count(input_size), input.data(), get_filename_truncation_hint_text(input_size), input_size);
286 #undef DXX_ADD_SONG_EXTENSION_HINT
287 return;
288 }
289 /* The input is not a `bim_song_info`, so a direct use of
290 * `emplace_back(input)` is not well-formed.
291 *
292 * Using `emplace_back(bim_song_info(...))` is well-formed, but constructs
293 * a temporary to pass to emplace_back, which then copy-constructs the
294 * vector element.
295 *
296 * Pass an instance of an object that is convertible to the element_type,
297 * and rely on copy elision to construct the converted value directly into
298 * the vector element.
299 */
300 struct emplace_subrange
301 {
302 std::ranges::subrange<std::span<char>::iterator> input;
303 operator bim_song_info() const
304 {
305 /* `input` does not include a terminating null, so zero initialize
306 * `r` before copying `input` into it. Zeroing the entire buffer
307 * is cheap, and avoids a lookup of the length of the input buffer.
308 */
309 bim_song_info r{};
310 std::ranges::copy(input, std::ranges::begin(r.filename));
311 return r;
312 }
313 };
314 auto &e{songs.emplace_back(emplace_subrange{input})};
315 assert(!e.filename.back());
316 /* Check verbosity before preparing arguments, so that the dirname is not
317 * computed if the con_printf call will not use it.
318 */
319 if (CON_VERBOSE <= CGameArg.DbgVerbose)
320 con_printf(CON_VERBOSE, "note: song file \"%s\"/\"%s\":%u: adding filename \"%s\"", pathname.get_dirname(), pathname.physfs_virtual_path, lineno, e.filename.data());
321 }
322
323 }
324
325 }
326
327 namespace dsx {
328
329 namespace {
330
331 // Set up everything for our music
332 // NOTE: you might think this is done once per runtime but it's not! It's done for EACH song so that each mission can have it's own descent.sng structure. We COULD optimize that by only doing this once per mission.
333 static void songs_init()
334 {
335 using namespace std::string_view_literals;
336
337 BIMSongs.reset();
338 BIMSecretSongs.reset();
339
340 // try dxx-r.sng - a songfile specifically for dxx which level authors CAN use (dxx does not care if descent.sng contains MP3/OGG/etc. as well) besides the normal descent.sng containing files other versions of the game cannot play. this way a mission can contain a DOS-Descent compatible OST (hmp files) as well as a OST using MP3, OGG, etc.
341 auto fp = PHYSFSX_openReadBuffered("dxx-r.sng").first;
342
343 const bool canUseExtensions{!!fp}; // can use extensions ONLY if dxx-r.sng
344 if (!fp) // try to open regular descent.sng
345 fp = PHYSFSX_openReadBuffered("descent.sng").first;
346
347 if (!fp) // No descent.sng available. Define a default song-set
348 {
349 constexpr std::size_t predef{30}; // define 30 songs - period
350
351 user_configured_level_songs builtin_songs{predef};
352
353 assign_builtin_song(builtin_songs[song_number::title], "descent.hmp");
354 assign_builtin_song(builtin_songs[song_number::briefing], "briefing.hmp");
355 assign_builtin_song(builtin_songs[song_number::credits], "credits.hmp");
356 assign_builtin_song(builtin_songs[song_number::endlevel], "endlevel.hmp"); // can't find it? give a warning
357 assign_builtin_song(builtin_songs[song_number::endgame], "endgame.hmp"); // ditto
358
359 for (const auto i : constant_xrange<unsigned, 0u, predef>{})
360 {
361 auto &s{builtin_songs[build_song_number_from_level_song_number(level_song_number{i})]};
362 const auto d{s.filename.data()};
363 const auto fs{s.filename.size()};
364 std::snprintf(d, fs, "game%02u.hmp", i + 1);
365 if (PHYSFSX_exists_ignorecase(d))
366 continue;
367 std::snprintf(d, fs, "game%u.hmp", i);
368 if (PHYSFSX_exists_ignorecase(d))
369 continue;
370 else
371 {
372 s = {}; // music not available
373 break;
374 }
375 }
376 BIMSongs = std::move(builtin_songs);
377 /* BIMSecretSongs remains unset. There is no built-in default song
378 * list for secret levels.
379 */
380 }
381 else
382 {
383 const auto use_secret_songs{[](const bool canUseExtensions, const PHYSFSX_fgets_t::result &result) {
384 if (!canUseExtensions)
385 return canUseExtensions;
386 /* If extensions are allowed, check whether this line uses an
387 * extension directive.
388 */
389 if (constexpr std::string_view secret_label{"!Rebirth.secret "sv}; result.size() > secret_label.size() &&
390 std::ranges::equal(std::span(result.begin(), secret_label.size()), secret_label))
391 return canUseExtensions;
392 return false;
393 }};
394 std::vector<bim_song_info> main_songs, secret_songs;
395 unsigned lineno{0};
396 deferred_physfs_pathname deferred_pathname{fp.filename};
397 for (PHYSFSX_gets_line_t<81> inputline; const auto result{PHYSFSX_fgets(inputline, fp)};)
398 {
399 ++lineno;
400 if (result.empty())
401 continue;
402 add_song(deferred_pathname, lineno, use_secret_songs(canUseExtensions, result) ? secret_songs : main_songs, result);
403 }
404 #if DXX_BUILD_DESCENT == 1
405 // HACK: If Descent.hog is patched from 1.0 to 1.5, descent.sng is turncated. So let's patch it up here
406 constexpr std::size_t truncated_song_count = 12;
407 if (!canUseExtensions &&
408 main_songs.size() == truncated_song_count &&
409 PHYSFS_fileLength(fp) == 422)
410 {
411 main_songs.resize(truncated_song_count + 15);
412 for (const auto i : constant_xrange<unsigned, truncated_song_count, 27>{})
413 {
414 auto &s = main_songs[i];
415 snprintf(std::data(s.filename), std::size(s.filename), "game%02u.hmp", i - 4);
416 }
417 }
418 #endif
419 BIMSongs = std::move(main_songs);
420 BIMSecretSongs = std::move(secret_songs);
421 }
422
423 fp.reset();
424
425 if (CGameArg.SndNoMusic)
426 CGameCfg.MusicType = music_type::None;
427
428 // If SDL_Mixer is not supported (or deactivated), switch to no-music type if SDL_mixer-related music type was selected
429 else if (CGameArg.SndDisableSdlMixer)
430 {
431 #ifndef _WIN32
432 if (CGameCfg.MusicType == music_type::Builtin)
433 CGameCfg.MusicType = music_type::None;
434 #endif
435 if (CGameCfg.MusicType == music_type::Custom)
436 CGameCfg.MusicType = music_type::None;
437 }
438
439 switch (CGameCfg.MusicType)
440 {
441 case music_type::None:
442 case music_type::Builtin:
443 break;
444 #if DXX_USE_SDL_REDBOOK_AUDIO
445 case music_type::Redbook:
446 RBAInit();
447 break;
448 #endif
449 case music_type::Custom:
450 jukebox_load();
451 break;
452 }
453
454 songs_set_volume(CGameCfg.MusicVolume);
455 }
456
457 }
458
459 }
460
461 void songs_uninit()
462 {
463 songs_stop_all();
464 #if DXX_USE_SDLMIXER
465 jukebox_unload();
466 #endif
467 BIMSecretSongs.reset();
468 BIMSongs.reset();
469 }
470
471 //stop any songs - builtin, redbook or jukebox - that are currently playing
472 void songs_stop_all(void)
473 {
474 #ifdef _WIN32
475 digi_win32_stop_midi_song(); // Stop midi song, if playing
476 #endif
477 #if DXX_USE_SDL_REDBOOK_AUDIO
478 RBAStop();
479 #endif
480 #if DXX_USE_SDLMIXER
481 mix_stop_music();
482 #endif
483
484 Song_playing = song_number::None;
485 }
486
487 void songs_pause(void)
488 {
489 #ifdef _WIN32
490 digi_win32_pause_midi_song();
491 #endif
492 #if DXX_USE_SDL_REDBOOK_AUDIO
493 if (CGameCfg.MusicType == music_type::Redbook)
494 RBAPause();
495 #endif
496 #if DXX_USE_SDLMIXER
497 mix_pause_music();
498 #endif
499 }
500
501 void songs_resume(void)
502 {
503 #ifdef _WIN32
504 digi_win32_resume_midi_song();
505 #endif
506 #if DXX_USE_SDL_REDBOOK_AUDIO
507 if (CGameCfg.MusicType == music_type::Redbook)
508 RBAResume();
509 #endif
510 #if DXX_USE_SDLMIXER
511 mix_resume_music();
512 #endif
513 }
514
515 void songs_pause_resume(void)
516 {
517 #if DXX_USE_SDL_REDBOOK_AUDIO
518 if (CGameCfg.MusicType == music_type::Redbook)
519 RBAPauseResume();
520 #endif
521 #if DXX_USE_SDLMIXER
522 mix_pause_resume_music();
523 #endif
524 }
525
526 #if DXX_BUILD_DESCENT == 1
527 /*
528 * This list may not be exhaustive!!
529 */
530 #define D1_MAC_OEM_DISCID 0xde0feb0e // Descent CD that came with the Mac Performa 6400, hope mine isn't scratched [too much]
531
532 #if DXX_USE_SDL_REDBOOK_AUDIO
533 #define REDBOOK_ENDLEVEL_TRACK 4
534 #define REDBOOK_ENDGAME_TRACK (RBAGetNumberOfTracks())
535 #define REDBOOK_FIRST_LEVEL_TRACK (songs_have_cd() ? 6 : 1)
536 #endif
537 #elif DXX_BUILD_DESCENT == 2
538 /*
539 * Some of these have different Track listings!
540 * Which one is the "correct" order?
541 */
542 #define D2_1_DISCID 0x7d0ff809 // Descent II
543 #define D2_2_DISCID 0xe010a30e // Descent II
544 #define D2_3_DISCID 0xd410070d // Descent II
545 #define D2_4_DISCID 0xc610080d // Descent II
546 #define D2_DEF_DISCID 0x87102209 // Definitive collection Disc 2
547 #define D2_OEM_DISCID 0xac0bc30d // Destination: Quartzon
548 #define D2_OEM2_DISCID 0xc40c0a0d // Destination: Quartzon
549 #define D2_VERTIGO_DISCID 0x53078208 // Vertigo
550 #define D2_VERTIGO2_DISCID 0x64071408 // Vertigo + DMB
551 #define D2_MAC_DISCID 0xb70ee40e // Macintosh
552 #define D2_IPLAY_DISCID 0x22115710 // iPlay for Macintosh
553
554 #if DXX_USE_SDL_REDBOOK_AUDIO
555 #define REDBOOK_TITLE_TRACK 2
556 #define REDBOOK_CREDITS_TRACK 3
557 #define REDBOOK_FIRST_LEVEL_TRACK (songs_have_cd() ? 4 : 1)
558 #endif
559 #endif
560
561 // 0 otherwise
562 namespace dsx {
563 namespace {
564 #if DXX_USE_SDL_REDBOOK_AUDIO
565 static int songs_have_cd()
566 {
567 unsigned long discid;
568
569 if (CGameCfg.OrigTrackOrder)
570 return 1;
571
572 if (!(CGameCfg.MusicType == music_type::Redbook))
573 return 0;
574
575 discid = RBAGetDiscID();
576 con_printf(CON_DEBUG, "CD-ROM disc ID is 0x%08lx", discid);
577
578 switch (discid) {
579 #if DXX_BUILD_DESCENT == 1
580 case D1_MAC_OEM_DISCID: // Doesn't work with your Mac Descent CD? Please tell!
581 return 1;
582 #elif DXX_BUILD_DESCENT == 2
583 case D2_1_DISCID:
584 case D2_2_DISCID:
585 case D2_3_DISCID:
586 case D2_4_DISCID:
587 case D2_DEF_DISCID:
588 case D2_OEM_DISCID:
589 case D2_OEM2_DISCID:
590 case D2_VERTIGO_DISCID:
591 case D2_VERTIGO2_DISCID:
592 case D2_MAC_DISCID:
593 case D2_IPLAY_DISCID:
594 return 1;
595 #endif
596 default:
597 return 0;
598 }
599 }
600 #endif
601
602 #if DXX_BUILD_DESCENT == 1
603 #if DXX_USE_SDL_REDBOOK_AUDIO
604 static void redbook_repeat_func()
605 {
606 pause_game_world_time p;
607 RBAPlayTracks(Redbook_playing, 0, redbook_repeat_func);
608 }
609 #endif
610 #elif DXX_BUILD_DESCENT == 2
611 #if DXX_USE_SDL_REDBOOK_AUDIO || DXX_USE_SDLMIXER
612 static void play_credits_track()
613 {
614 pause_game_world_time p;
615 songs_play_song(song_number::credits, 1);
616 }
617 #endif
618 #endif
619
620 #if DXX_USE_SDL_REDBOOK_AUDIO
621 static void play_redbook_track_if_available(const song_number songnum, const int redbook_track, const int num_tracks, const int repeat)
622 {
623 if (redbook_track > num_tracks)
624 return;
625 #if DXX_BUILD_DESCENT == 1
626 constexpr auto repeat_func{&redbook_repeat_func};
627 #elif DXX_BUILD_DESCENT == 2
628 constexpr auto repeat_func{&play_credits_track};
629 #endif
630 if (RBAPlayTracks(redbook_track, redbook_track, repeat ? repeat_func : nullptr))
631 {
632 Redbook_playing = redbook_track;
633 Song_playing = songnum;
634 }
635 }
636 #endif
637
638 }
639
640 }
641
642 // play a filename as music, depending on filename extension.
643 int songs_play_file(char *filename, int repeat, void (*hook_finished_track)())
644 {
645 songs_stop_all();
646 #if defined(_WIN32) || DXX_USE_SDLMIXER
647 const char *fptr = strrchr(filename, '.');
648 if (fptr == NULL)
649 return 0;
650
651 ++ fptr;
652 if (!d_stricmp(fptr, SONG_EXT_HMP))
653 {
654 #if defined(_WIN32)
655 return digi_win32_play_midi_song( filename, repeat );
656 #elif DXX_USE_SDLMIXER
657 return mix_play_file( filename, repeat, hook_finished_track );
658 #else
659 return 0;
660 #endif
661 }
662 #if DXX_USE_SDLMIXER
663 else if ( !d_stricmp(fptr, SONG_EXT_MID) ||
664 !d_stricmp(fptr, SONG_EXT_OGG) ||
665 !d_stricmp(fptr, SONG_EXT_FLAC) ||
666 !d_stricmp(fptr, SONG_EXT_MP3) )
667 {
668 return mix_play_file( filename, repeat, hook_finished_track );
669 }
670 #endif
671 #endif
672 return 0;
673 }
674
675 namespace dsx {
676
677 void songs_play_song(const song_number songnum, const int repeat)
678 {
679 songs_init();
680
681 switch (CGameCfg.MusicType)
682 {
683 case music_type::Builtin:
684 {
685 if (underlying_value(songnum) >= BIMSongs.size())
686 break;
687 // EXCEPTION: If song_number::endlevel is not available, continue playing level song.
688 auto &s = BIMSongs[songnum];
689 if (songnum == song_number::endlevel && Song_playing >= song_number::first_level_song && !PHYSFSX_exists_ignorecase(s.filename.data()))
690 return;
691
692 Song_playing = song_number::None;
693 if (songs_play_file(s.filename.data(), repeat, nullptr))
694 Song_playing = songnum;
695 break;
696 }
697 #if DXX_USE_SDL_REDBOOK_AUDIO
698 case music_type::Redbook:
699 {
700 const auto num_tracks{RBAGetNumberOfTracks()};
701
702 #if DXX_BUILD_DESCENT == 1
703 Song_playing = song_number::None;
704 if (songnum < song_number::endgame)
705 {
706 play_redbook_track_if_available(songnum, underlying_value(songnum) + 2, num_tracks, repeat);
707 }
708 else if (songnum == song_number::endgame) // The endgame track is the last track
709 {
710 play_redbook_track_if_available(songnum, REDBOOK_ENDGAME_TRACK, num_tracks, repeat);
711 }
712 else if (songnum > song_number::endgame)
713 {
714 play_redbook_track_if_available(songnum, underlying_value(songnum) + 1, num_tracks, repeat);
715 }
716 #elif DXX_BUILD_DESCENT == 2
717 // keep playing current music if chosen song is unavailable (e.g. SONG_ENDLEVEL)
718 if (songnum == song_number::title)
719 {
720 play_redbook_track_if_available(songnum, REDBOOK_TITLE_TRACK, num_tracks, repeat);
721 }
722 else if (songnum == song_number::credits)
723 {
724 play_redbook_track_if_available(songnum, REDBOOK_CREDITS_TRACK, num_tracks, repeat);
725 }
726 #endif
727 break;
728 }
729 #endif
730 #if DXX_USE_SDLMIXER
731 case music_type::Custom:
732 {
733 // EXCEPTION: If song_number::endlevel is undefined, continue playing level song.
734 if (songnum == song_number::endlevel && Song_playing >= song_number::first_level_song && !CGameCfg.CMMiscMusic[songnum].front())
735 return;
736
737 Song_playing = song_number::None;
738 #if DXX_BUILD_DESCENT == 1
739 int play = songs_play_file(CGameCfg.CMMiscMusic[songnum].data(), repeat, NULL);
740 #elif DXX_BUILD_DESCENT == 2
741 const auto use_credits_track{songnum == song_number::title && CGameCfg.OrigTrackOrder};
742 int play = songs_play_file(CGameCfg.CMMiscMusic[songnum].data(),
743 // Play the credits track after the title track and loop the credits track if original CD track order was chosen
744 use_credits_track ? 0 : repeat,
745 use_credits_track ? play_credits_track : NULL);
746 #endif
747 if (play)
748 Song_playing = songnum;
749 break;
750 }
751 #endif
752 default:
753 Song_playing = song_number::None;
754 break;
755 }
756
757 return;
758 }
759
760 #if DXX_USE_SDL_REDBOOK_AUDIO
761 namespace {
762 static void redbook_first_song_func()
763 {
764 pause_game_world_time p;
765 Song_playing = song_number::None; // Playing Redbook tracks will not modify Song_playing. To repeat we must reset this so songs_play_level_song does not think we want to re-play the same song again.
766 songs_play_level_song(1, 0);
767 }
768 }
769 #endif
770
771 // play track given by levelnum (depending on the music type and it's playing behaviour) or increment/decrement current track number via offset value
772
773 void songs_play_level_song(int levelnum, int offset)
774 {
775 Assert( levelnum != 0 );
776
777 songs_init();
778 const level_song_number level_songnum{(levelnum > 0) ? static_cast<unsigned>(levelnum - 1) : static_cast<unsigned>(-levelnum)};
779
780 switch (CGameCfg.MusicType)
781 {
782 case music_type::Builtin:
783 {
784 if (offset)
785 return;
786
787 Song_playing = song_number::None;
788 if (levelnum < 0)
789 {
790 /* Secret songs are processed separately and do not need
791 * to exclude non-levels. Secret songs start at offset 0, so a
792 * test for `size == 0` is sufficient.
793 */
794 if (const auto size{BIMSecretSongs.size()})
795 {
796 const auto secretsongnum{static_cast<song_number>((-levelnum - 1) % size)};
797 if (songs_play_file(BIMSecretSongs[secretsongnum].filename.data(), 1, nullptr))
798 Song_playing = secretsongnum;
799 }
800 break;
801 }
802 /* Level songs start at offset `song_number::first_level_song`, so
803 * require that the song list contain more than that many entries.
804 * A list with at most `song_number::first_level_song` entries only
805 * has non-level songs, so nothing can be played for level songs.
806 */
807 if (const auto size{BIMSongs.size()}; size > static_cast<std::size_t>(song_number::first_level_song))
808 {
809 /* Compute `count_level_songs` to exclude songs assigned to
810 * non-levels, such as title, briefing, etc.
811 */
812 const auto count_level_songs{size - static_cast<std::size_t>(song_number::first_level_song)};
813 const song_number songnum{build_song_number_from_level_song_number(static_cast<level_song_number>(underlying_value(level_songnum) % count_level_songs))};
814 if (songs_play_file(BIMSongs[songnum].filename.data(), 1, nullptr))
815 Song_playing = songnum;
816 }
817 break;
818 }
819 #if DXX_USE_SDL_REDBOOK_AUDIO
820 case music_type::Redbook:
821 {
822 const auto n_tracks{RBAGetNumberOfTracks()};
823 int tracknum;
824 const song_number songnum{build_song_number_from_level_song_number(level_songnum)};
825
826 if (!offset)
827 {
828 // we have just been told to play the same as we do already -> ignore
829 if (Song_playing >= song_number::first_level_song && songnum == Song_playing)
830 return;
831
832 #if DXX_BUILD_DESCENT == 1
833 const int bn_tracks{n_tracks};
834 #elif DXX_BUILD_DESCENT == 2
835 const int bn_tracks{n_tracks + 1};
836 #endif
837 if (bn_tracks < REDBOOK_FIRST_LEVEL_TRACK)
838 /* If there are insufficient tracks to have any level songs, break */
839 break;
840 tracknum = REDBOOK_FIRST_LEVEL_TRACK + (
841 (bn_tracks <= REDBOOK_FIRST_LEVEL_TRACK)
842 /* If there is exactly one level track, pick level track 0.
843 */
844 ? 0
845 /* Otherwise, pick the appropriate song, and wrap back to
846 * the start if there are too few tracks to give each level
847 * a unique song.
848 */
849 : (underlying_value(level_songnum) % (bn_tracks - REDBOOK_FIRST_LEVEL_TRACK))
850 );
851 }
852 else
853 {
854 tracknum = Redbook_playing+offset;
855 if (tracknum < REDBOOK_FIRST_LEVEL_TRACK)
856 tracknum = n_tracks - (REDBOOK_FIRST_LEVEL_TRACK - tracknum) + 1;
857 else if (tracknum > n_tracks)
858 tracknum = REDBOOK_FIRST_LEVEL_TRACK + (tracknum - n_tracks) - 1;
859 }
860
861 Song_playing = song_number::None;
862 if (RBAEnabled() && (tracknum <= n_tracks))
863 {
864 #if DXX_BUILD_DESCENT == 1
865 const auto have_cd{songs_have_cd()};
866 const auto play{RBAPlayTracks(tracknum, !have_cd ? n_tracks : tracknum, have_cd ? redbook_repeat_func : redbook_first_song_func)};
867 #elif DXX_BUILD_DESCENT == 2
868 const auto play{RBAPlayTracks(tracknum, n_tracks, redbook_first_song_func)};
869 #endif
870 if (play)
871 {
872 Song_playing = songnum;
873 Redbook_playing = tracknum;
874 }
875 }
876 break;
877 }
878 #endif
879 #if DXX_USE_SDLMIXER
880 case music_type::Custom:
881 {
882 if (CGameCfg.CMLevelMusicPlayOrder == LevelMusicPlayOrder::Random)
883 CGameCfg.CMLevelMusicTrack[0] = d_rand() % CGameCfg.CMLevelMusicTrack[1]; // simply a random selection - no check if this song has already been played. But that's how I roll!
884 else if (!offset)
885 {
886 if (CGameCfg.CMLevelMusicPlayOrder == LevelMusicPlayOrder::Continuous)
887 {
888 static level_song_number last_songnum{level_song_number::None};
889
890 if (Song_playing >= song_number::first_level_song)
891 return;
892
893 // As soon as we start a new level, go to next track
894 if (last_songnum != level_song_number::None && level_songnum != last_songnum)
895 ((CGameCfg.CMLevelMusicTrack[0] + 1 >= CGameCfg.CMLevelMusicTrack[1])
896 ? CGameCfg.CMLevelMusicTrack[0] = 0
897 : CGameCfg.CMLevelMusicTrack[0]++);
898 last_songnum = level_songnum;
899 }
900 else if (CGameCfg.CMLevelMusicPlayOrder == LevelMusicPlayOrder::Level)
901 CGameCfg.CMLevelMusicTrack[0] = underlying_value(level_songnum) % CGameCfg.CMLevelMusicTrack[1];
902 }
903 else
904 {
905 CGameCfg.CMLevelMusicTrack[0] += offset;
906 if (CGameCfg.CMLevelMusicTrack[0] < 0)
907 CGameCfg.CMLevelMusicTrack[0] = CGameCfg.CMLevelMusicTrack[1] + CGameCfg.CMLevelMusicTrack[0];
908 if (CGameCfg.CMLevelMusicTrack[0] + 1 > CGameCfg.CMLevelMusicTrack[1])
909 CGameCfg.CMLevelMusicTrack[0] = CGameCfg.CMLevelMusicTrack[0] - CGameCfg.CMLevelMusicTrack[1];
910 }
911
912 Song_playing = song_number::None;
913 if (jukebox_play())
914 Song_playing = build_song_number_from_level_song_number(level_songnum);
915
916 break;
917 }
918 #endif
919 default:
920 Song_playing = song_number::None;
921 break;
922 }
923
924 #if DXX_BUILD_DESCENT == 1
925 // If we couldn't play the song, most likely because it wasn't specified, play no music.
926 if (Song_playing == song_number::None)
927 songs_stop_all();
928 #endif
929 return;
930 }
931
932 }