1 /*
2  * This software is licensed under the terms of the MIT License.
3  * See COPYING for further information.
4  * ---
5  * Copyright (c) 2011-2019, Lukas Weber <laochailan@web.de>.
6  * Copyright (c) 2012-2019, Andrei Alexeyev <akari@taisei-project.org>.
7  */
8 
9 #include "taisei.h"
10 
11 #include "resource.h"
12 #include "bgm.h"
13 #include "audio/backend.h"
14 #include "sfxbgm_common.h"
15 #include "util.h"
16 
bgm_path(const char * name)17 static char *bgm_path(const char *name) {
18 	return sfxbgm_make_path(BGM_PATH_PREFIX, name, true);
19 }
20 
check_bgm_path(const char * path)21 static bool check_bgm_path(const char *path) {
22 	return sfxbgm_check_path(BGM_PATH_PREFIX, path, true);
23 }
24 
load_music(const char * path)25 static MusicImpl *load_music(const char *path) {
26 	if(!path) {
27 		return NULL;
28 	}
29 
30 	return _a_backend.funcs.music_load(path);
31 }
32 
load_bgm_begin(const char * path,uint flags)33 static void *load_bgm_begin(const char *path, uint flags) {
34 	Music *mus = calloc(1, sizeof(Music));
35 
36 	if(strendswith(path, ".bgm")) {
37 		char *basename = resource_util_basename(BGM_PATH_PREFIX, path);
38 		mus->meta = get_resource_data(RES_BGM_METADATA, basename, flags);
39 		free(basename);
40 
41 		if(mus->meta) {
42 			mus->impl = load_music(mus->meta->loop_path);
43 		}
44 	} else {
45 		mus->impl = load_music(path);
46 	}
47 
48 	if(!mus->impl) {
49 		free(mus);
50 		mus = NULL;
51 		log_error("Failed to load bgm '%s'", path);
52 	} else if(mus->meta->loop_point > 0) {
53 		_a_backend.funcs.music_set_loop_point(mus->impl, mus->meta->loop_point);
54 	}
55 
56 	return mus;
57 }
58 
load_bgm_end(void * opaque,const char * path,uint flags)59 static void *load_bgm_end(void *opaque, const char *path, uint flags) {
60 	return opaque;
61 }
62 
unload_bgm(void * vmus)63 static void unload_bgm(void *vmus) {
64 	Music *mus = vmus;
65 	_a_backend.funcs.music_unload(mus->impl);
66 	free(mus);
67 }
68 
69 ResourceHandler bgm_res_handler = {
70     .type = RES_BGM,
71     .typename = "bgm",
72     .subdir = BGM_PATH_PREFIX,
73 
74     .procs = {
75         .find = bgm_path,
76         .check = check_bgm_path,
77         .begin_load = load_bgm_begin,
78         .end_load = load_bgm_end,
79         .unload = unload_bgm,
80     },
81 };
82