Check that AltiVec is enabled before using it
[openal-soft.git] / examples / common / alhelpers.h
blob921d0237fdfaf05aeccd6161eb1f2ad9a8fcfbf5
1 #ifndef ALHELPERS_H
2 #define ALHELPERS_H
4 #include "AL/al.h"
5 #include "AL/alc.h"
7 #ifdef __cplusplus
8 extern "C" {
9 #endif
11 /* Some helper functions to get the name from the format enums. */
12 const char *FormatName(ALenum format);
14 /* Easy device init/deinit functions. InitAL returns 0 on success. */
15 int InitAL(char ***argv, int *argc);
16 void CloseAL(void);
18 /* Cross-platform timeget and sleep functions. */
19 int altime_get(void);
20 void al_nssleep(unsigned long nsec);
22 /* C doesn't allow casting between function and non-function pointer types, so
23 * with C99 we need to use a union to reinterpret the pointer type. Pre-C99
24 * still needs to use a normal cast and live with the warning (C++ is fine with
25 * a regular reinterpret_cast).
27 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
28 #define FUNCTION_CAST(T, ptr) (union{void *p; T f;}){ptr}.f
29 #elif defined(__cplusplus)
30 #define FUNCTION_CAST(T, ptr) reinterpret_cast<T>(ptr)
31 #else
32 #define FUNCTION_CAST(T, ptr) (T)(ptr)
33 #endif
35 #ifdef __cplusplus
36 } // extern "C"
38 #include <cstdio>
39 #include <iostream>
40 #include <string>
41 #include <string_view>
43 #include "alspan.h"
45 int InitAL(al::span<std::string_view> &args)
47 ALCdevice *device{};
49 /* Open and initialize a device */
50 if(args.size() > 1 && args[0] == "-device")
52 device = alcOpenDevice(std::string{args[1]}.c_str());
53 if(!device)
54 std::cerr<< "Failed to open \""<<args[1]<<"\", trying default\n";
55 args = args.subspan(2);
57 if(!device)
58 device = alcOpenDevice(nullptr);
59 if(!device)
61 std::fprintf(stderr, "Could not open a device!\n");
62 return 1;
65 ALCcontext *ctx{alcCreateContext(device, nullptr)};
66 if(!ctx || alcMakeContextCurrent(ctx) == ALC_FALSE)
68 if(ctx)
69 alcDestroyContext(ctx);
70 alcCloseDevice(device);
71 std::fprintf(stderr, "Could not set a context!\n");
72 return 1;
75 const ALCchar *name{};
76 if(alcIsExtensionPresent(device, "ALC_ENUMERATE_ALL_EXT"))
77 name = alcGetString(device, ALC_ALL_DEVICES_SPECIFIER);
78 if(!name || alcGetError(device) != AL_NO_ERROR)
79 name = alcGetString(device, ALC_DEVICE_SPECIFIER);
80 std::printf("Opened \"%s\"\n", name);
82 return 0;
85 #endif
87 #endif /* ALHELPERS_H */