I am creating android application that uses libvlc to play a video.
Since vlc/libvlc doesnt have any kind of event/callback for subtitles i have created my own text renderer module in modules/text_rendere/spucallback
Module compiles, but i have two problems.:
I dont see any log messages from this module
How can i use this module from libvlc
callback.h
typedef void (*spu_cb_t)(text_segment_t *p_segment);
struct spu_cb_t {
spu_cb_t cb;
};
struct spu_cb_t *callback;
callback.c
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdlib.h>
/* VLC core API headers */
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_interface.h>
#include <vlc_filter.h>
#include "callback.h"
static int Open(vlc_object_t *);
static void Close(vlc_object_t *);
static int RenderText(filter_t *,
subpicture_region_t *p_region_out,
subpicture_region_t *p_region_in,
const vlc_fourcc_t *p_chroma_list);
/* Module descriptor */
vlc_module_begin()
set_shortname(N_("SPU Callback "))
set_description(N_("SPU Callback module"))
set_capability("text renderer", 0)
set_callbacks(Open, Close)
set_category(CAT_VIDEO)
vlc_module_end ()
static int Open(vlc_object_t *p_this)
{
filter_t *p_filter = (filter_t *)p_this;
p_filter->pf_render = RenderText;
printf("spucallback:Open");
callback = (spu_cb_t*) malloc(sizeof(spu_cb_t));
if (!callback)
goto error;
return VLC_SUCCESS;
error:
free(callback);
return VLC_EGENERIC;
}
static void Close(vlc_object_t *p_this)
{
printf("spucallback:Close");
free(callback->cb);
free(callback);
}
static int RenderText(filter_t *p_filter,
subpicture_region_t *p_region_out,
subpicture_region_t *p_region_in,
const vlc_fourcc_t *p_chroma_list)
{
text_segment_t *p_segment = p_region_in->p_text;
callback->cb(p_segment);
printf("spucallback:RenderText");
return VLC_SUCCESS;
}
Code is not yet finished obviously
This log messages might be related:
[e41bfa2c] core spu text: looking for text renderer module matching "spucallback": 1 candidates
[e41bfa2c] core spu text: no suitable access module for `file:///vendor/etc/fallback_fonts.xml'
[e41bfa2c] core spu text: using text renderer module "freetype"
Related
I am hooking an existing library that is compiled using gnustl std::string instead of libc++ std::_ndk1::string. If I try to set or access these strings I just get garbage. How do I convert my std::string to std::_ndk1::string and vice versa in my hook application?
I cannot compile my hook with "-DANDROID_STL=gnustl_shared" because it no longer exists and other libraries in use require libc++.
The documentation mentions this https://developer.android.com/ndk/guides/cpp-support "The various STLs are not compatible with one another. As an example, the layout of std::string in libc++ is not the same as it is in gnustl" which is exactly the problem.
To use gnustl, you could compile all your native code with NDK r.17 or older. This is a dangerous path, because many important bugs, including security-related, have been fixed since then.
Another unsupported (and not recommended) way to deal with your problem is to get the gnustl sources from NDK r.17 and compile them with the latest NDK version.
Your best option is to have all your dependencies rebuilt with a recent version of NDK and its c++_shared runtime library.
Here's what I came up with (for now, really not ideal):
StringsProxy.cc
#include "StringsProxy.h"
#include <iostream>
#include <string>
using namespace std;
__attribute__((visibility("default")))
extern "C" StringsProxy::StringsProxy(const char* contents)
{
set_string = std::string(contents);
}
__attribute__((visibility("default")))
extern "C" StringsProxy::StringsProxy(uintptr_t str) {
set_string = *reinterpret_cast<proxy_string*>(str);
}
__attribute__((visibility("default")))
extern "C" const char* StringsProxy::c_str() {
return set_string.c_str();
}
__attribute__((visibility("default")))
extern "C" const uintptr_t* StringsProxy::ptr() {
return reinterpret_cast<uintptr_t *>(&set_string);
}
__attribute__((visibility("default")))
extern "C" StringsProxy::~StringsProxy() {
}
StringsProxy.h
#ifndef __STRINGSPROXY_H__
#define __STRINGSPROXY_H__
#include <string>
typedef std::basic_string<char> proxy_string;
class StringsProxy
{
public:
/* Initialize StringsProxy with a pointer to an existing string */
StringsProxy(uintptr_t str);
/* Initialize StringsProxy with a new string */
StringsProxy(const char* str);
/* Get C string */
virtual const char* c_str();
/* Get pointer to string for injection */
const virtual uintptr_t* ptr();
private:
proxy_string set_string;
};
#endif
Compile this into a shared object using the old NDK with -DCMAKE_ANDROID_STL_TYPE=gnustl_static
Then link this shared object to the hooking program (in CMakeLists):
target_link_libraries(${TARGET_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/abiproxy/build/armeabi-v7a/libabiproxy.so)
Then in the hooking program, can be used like this:
#include "abiproxy/StringsProxy.h"
void *setUriDebug(uintptr_t a1, uintptr_t stri) {
auto y = StringsProxy(stri);
LOGI("URI CALLED %s", y.c_str());
return setUriDebugOld(a1, stri);
}
Or in reverse:
StringsProxy assetNameBaseProxy = StringsProxy("https://example.com/");
void setResourceUrl(uintptr_t* a1, int a2) {
*(a1 + 1) = *assetNameBaseProxy.ptr();
}
This isn't by any means a good solution, but it works for my use-case.
I am developing a cross-platform mobile game (iOS and Android) using cocos2d-x.
Most of my code is written in C++, with OS specific code in Objective-C / Java / Swift using a bridge.
I was wondering if anyone has used any C++ library to host a UDP server within their app ?
EDIT: So far I have found many platform specific solutions (using Java for Android, and cocoaasync etc for iOS), but nothing specifically in C++ which has been used for a cross platform app.
Edit: I would prefer a solution without boost. Preferably something simple to include like adding a couple of files to a project.
You can most probably use Valve's GameNetworkingSockets, https://github.com/ValveSoftware/GameNetworkingSockets
They have very limited external dependencies, so you should be able to compile them for both iOS and Android
You can also take a look at this list: https://github.com/MFatihMAR/Awesome-Game-Networking, where there is a list of libraries that you can alternatively try.
You can use ASIO Standalone library. It is the same library available as boost/asio, but it doesn't require any other boost libraries. I have used boost/asio in exactly this type of project (Android/iOS) and it is by far the most superior solution.
Here is what I ended up with:
h file:
#include "Queue.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <array>
#include <iostream>
#include <thread>
using namespace std;
#define MAXBUFFER_SIZE 1024
class UDPServer {
public:
/**
* Constructor
*
* #port the port on which the UDP server is listening for packets.
*/
explicit UDPServer(unsigned short port);
/**
* Destructor
*/
~UDPServer() = default;
/**
* Setup the server.
*/
void setupServer();
/**
* Get a single message.
* For demonstration purposes, our messages is expected to be a array of int
*/
bool getMessage(std::array<int, 4>& message);
bool getIPAddress(std::array<int, 4>& message);
void setFoundIP();
bool isReady();
void nextPort();
int getPort();
private:
bool _isBoundToPort = false;
/**
* The server port.
*/
unsigned short port_;
bool isFoundIP = false;
/**
* The thread-safe message queue.
*/
Queue queue_;
Queue _ipAddresses;
/**
* The UDP server function.
*/
int UDPServerFunc();
};
cpp file:
#include "UDPServer.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
using namespace std;
/**
* This function parses an incoming message with the following format: 1;234;-89;-53;
*
* A valid message consists of 4 integer values separated by semicolons.
*/
inline std::array<int, 4> parseMessage(const std::string& input);
inline std::array<int,4> parseIp(const std::string& input);
UDPServer::UDPServer(unsigned short port) {
port_ = port;
}
bool UDPServer::getMessage(std::array<int, 4>& message) {
return queue_.pop(message);
}
bool UDPServer::getIPAddress(std::array<int, 4>& message) {
return _ipAddresses.pop(message);
}
void UDPServer::setFoundIP(){
isFoundIP = true;
}
bool UDPServer::isReady(){
return _isBoundToPort;
}
void UDPServer::nextPort(){
port_++;
}
int UDPServer::getPort(){
return port_;
}
void UDPServer::setupServer() {
// Launch the server thread.
std::thread t([this](){
UDPServerFunc();
});
t.detach();
}
int UDPServer::UDPServerFunc() {
// Creating socket file descriptor
int sockfd;
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// Filling server information
struct sockaddr_in servaddr, cliaddr;
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
servaddr.sin_family = AF_INET; // IPv
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(port_);
// Bind the socket with the server address
if (::bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
_isBoundToPort = true;
while (true) {
// Read the next message from the socket.
char message[MAXBUFFER_SIZE];
socklen_t len = sizeof(struct sockaddr);
ssize_t n = recvfrom(sockfd, (char *)&message, MAXBUFFER_SIZE, MSG_DONTWAIT,
(struct sockaddr *)&cliaddr, (socklen_t*)&len);
if (n > 0) {
message[n] = '\0';
// Parse incoming data and push the result on the queue.
// Parsed messages are represented as a std::array<int, 4>.
if(!isFoundIP){
_ipAddresses.push(parseIp(message));
}else{
queue_.push(parseMessage(message));
}
} else {
// Wait a fraction of a millisecond for the next message.
usleep(100);
}
}
return 0;
}
I removed any unnecessary code from my answer, as the meat really is just the code above. If anyone needs the extraneous functions as well, I shared the code on Github, and will add some examples later on too.
The above code is really simple and has a couple of parse functions for extracting an IP address, or a set of four numbers delimited by semicolons. The above code is simple enough to modify yourself for your own custom messages.
Queue.h is just a simple thread safe queue.
I have a header file with definition:
typedef enum acamera_metadata_enum_android_lens_facing {
// enumeration
} acamera_metadata_enum_android_lens_facing_t;
The problem is when I am trying to declare this enum as my class'es member the compiler can't find definition (header is found).
../../../../src/main/cpp/include/camera_manager.h:41:9: error: unknown type name 'acamera_metadata_enum_android_lens_facing_t'
acamera_metadata_enum_android_lens_facing_t facing;
This is my class header:
#ifndef DAVINCI_CAMERA_MANAGER_H
#define DAVINCI_CAMERA_MANAGER_H
#include <map>
#include <string>
#include <camera/NdkCameraManager.h>
#include <camera/NdkCameraError.h>
#include <camera/NdkCameraDevice.h>
#include <camera/NdkCameraMetadataTags.h> // The enumeration is defined here
#include <media/NdkImageReader.h>
namespace DaVinci {
class CameraId;
class CameraManager {
struct ACameraManager *_manager;
std::map<std::string, CameraId> _cameras;
std::string _activeCameraId;
int32_t _cameraFacing;
int32_t _cameraOrientation;
bool _valid;
public:
CameraManager();
~CameraManager();
};
// helper classes to hold enumerated camera
class CameraId {
public:
struct ACameraDevice *device;
std::string id;
acamera_metadata_enum_android_lens_facing_t facing;
bool available; // free to use ( no other apps are using
bool owner; // we are the owner of the camera
explicit CameraId(const char *id);
explicit CameraId();
};
};
#endif //DAVINCI_CAMERA_MANAGER_H
Where can the problem be?
P.S. I am using c++ 14 if it's important.
UPDATED
I created a repository with my project: https://bitbucket.org/ghostman2013/davinci_test
In your project's app/build.gradle you have minSdkVersion set to 21.
The native camera APIs were added in API level 24.
So you can either A) increase your minSdkVersion to 24 or higher, or B) Not use the native camera APIs in your library.
This is my first question, the reason i signed up to the site. I'm developing a game using Qt 5.9 and I use QTimer to spawn enemies on the screen. Everytime the timer's timeout function is called, an enemy is spawned.
What i try to do is if a player kills let's say 10 enemies, the timer interval decreases, so the enemies will spawn more frequently, making the game a little bit more challenging. The first time the timer interval is set, the game runs perfectly, but the second time the setInterval() method is called, when the player kills 10 enemies, the game suddenly crashes. I tried debugging it to figure out what might cause it, and it seems that it crashes when i try to set the spawnInterval.
I'm fairly new to coding so any advice is appreciated! Here are the relevant source files and codes from my code:
main.cpp
#include <QApplication>
#include <game.h>
Game * game;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
game = new Game();
game->show();
return a.exec();
}
game.h:
#include <QGraphicsScene>
#include <QWidget>
#include <QGraphicsView>
#include "Player.h"
#include "score.h"
#include "Health.h"
class Game: public QGraphicsView{
public:
Game(QWidget * parent=0);
QGraphicsScene * scene;
Player * player;
Score * score;
Health * health;
void setSpawnInterval(int spawnValue);
int getSpawnInterval();
void setTimerInterval();
private:
int spawnInterval = 1000;
};
#endif // GAME_H
game.cpp:
QTimer * timer1 = new QTimer();
QObject::connect(timer1,SIGNAL(timeout()),player,SLOT(spawn()));
timer1->start(getSpawnInterval());
}
void Game::setSpawnInterval(int spawnValue){
//this is the part where it crashes
spawnInterval = spawnValue;
}
int Game::getSpawnInterval(){
return spawnInterval;
}
score.h
#ifndef SCORE_H
#define SCORE_H
#include <QGraphicsTextItem>
class Score: public QGraphicsTextItem{
public:
Score(QGraphicsItem * parent=0);
void increase();
int getScore();
private:
int score;
};
#endif // SCORE_H
score.cpp
#include "score.h"
#include <QFont>
#include "game.h"
#include <QTimer>
void Score::increase()
{
score++;
if(score > 3){
Game * game;
game->setSpawnInterval(200);}
//Draw the text to the display
setPlainText(QString("Score: ") + QString::number(score));
}
int Score::getScore()
{
return score;
}
player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <QGraphicsRectItem>
#include <QEvent>
#include <QObject>
class Player: public QObject, public QGraphicsRectItem{
Q_OBJECT
public:
Player(QGraphicsItem * parent=0);
void keyPressEvent(QKeyEvent * event);
int jumpPhaseNumber = 0;
bool jumpRun = false;
public slots:
void spawn();
void jumpPhase();
};
#endif
player.cpp
void Player::spawn()
{
Enemy * enemy = new Enemy();
scene()->addItem(enemy);
}
Seems you are creating two instance of class game.
I suggest you to use static variables for accessing from multi classes.
add this class to your project:
.cpp
#include "settings.h"
int Settings::spawnInterval = 1000;
Settings::Settings(QObject *parent) : QObject(parent)
{
}
.h
#ifndef SETTINGS_H
#define SETTINGS_H
#include <QObject>
#include <QString>
class Settings : public QObject
{
Q_OBJECT
public:
explicit Settings(QObject *parent = 0);
static int spawnInterval;
};
#endif // SETTINGS_H
now we have a static variable name spawnInterval, you can access it (set/get) from any classes that include settings class like this:
#include <settings.h>
Settings::spawnInterval = 100; // set
int value = Settings::spawnInterval; //get
This line: Game * game; game->setSpawnInterval(200) causes your program to crash: you must initialize the game pointer; to fix this, for example, you can hold a reference (pointer) of game inside the Score class, thus letting you call setSpawnInterval; I would construct Score inside Game's constructor passing thisas a parameter; this saves you from creating a new class, as #aghilpro suggested. Actually a struct would be better since your information is public and accessible from other classes without the need to implement getters/setters.
I have some problems when using the dynamic loading API (<dlfcn.h>: dlopen(), dlclose(), etc) on Android.
I'm using NDK standalone toolchain (version 8) to compile the applications and libraries.
The Android version is 2.2.1 Froyo.
Here is the source code of the simple shared library.
#include <stdio.h>
int iii = 0;
int *ptr = NULL;
__attribute__((constructor))
static void init()
{
iii = 653;
}
__attribute__((destructor))
static void cleanup()
{
}
int aaa(int i)
{
printf("aaa %d\n", iii);
}
Here is the program source code which uses the mentioned library.
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
void *handle;
typedef int (*func)(int);
func bbb;
printf("start...\n");
handle = dlopen("/data/testt/test.so", RTLD_LAZY);
if (!handle)
{
return 0;
}
bbb = (func)dlsym(handle, "aaa");
if (bbb == NULL)
{
return 0;
}
bbb(1);
dlclose(handle);
printf("exit...\n");
return 0;
}
With these sources everything is working fine, but when I try to use some STL functions or classes, the program crashes with a segmentation fault, when the main() function exits, for example when using this source code for the shared library.
#include <iostream>
using namespace std;
int iii = 0;
int *ptr = NULL;
__attribute__((constructor))
static void init()
{
iii = 653;
}
__attribute__((destructor))
static void cleanup()
{
}
int aaa(int i)
{
cout << iii << endl;
}
With this code, the program crashes with segmentation fault after or the during main() function exit.
I have tried couple of tests and found the following results.
Without using of STL everything is working fine.
When use STL and do not call dlclose() at the end, everything is working fine.
I tried to compile with various compilation flags like -fno-use-cxa-atexit or -fuse-cxa-atexit, the result is the same.
What is wrong in my code that uses the STL?
Looks like I found the reason of the bug. I have tried another example with the following source files:
Here is the source code of the simple class:
myclass.h
class MyClass
{
public:
MyClass();
~MyClass();
void Set();
void Show();
private:
int *pArray;
};
myclass.cpp
#include <stdio.h>
#include <stdlib.h>
#include "myclass.h"
MyClass::MyClass()
{
pArray = (int *)malloc(sizeof(int) * 5);
}
MyClass::~MyClass()
{
free(pArray);
pArray = NULL;
}
void MyClass::Set()
{
if (pArray != NULL)
{
pArray[0] = 0;
pArray[1] = 1;
pArray[2] = 2;
pArray[3] = 3;
pArray[4] = 4;
}
}
void MyClass::Show()
{
if (pArray != NULL)
{
for (int i = 0; i < 5; i++)
{
printf("pArray[%d] = %d\n", i, pArray[i]);
}
}
}
As you can see from the code I did not used any STL related stuff.
Here is the source files of the functions library exports.
func.h
#ifdef __cplusplus
extern "C" {
#endif
int SetBabe(int);
int ShowBabe(int);
#ifdef __cplusplus
}
#endif
func.cpp
#include <stdio.h>
#include "myclass.h"
#include "func.h"
MyClass cls;
__attribute__((constructor))
static void init()
{
}
__attribute__((destructor))
static void cleanup()
{
}
int SetBabe(int i)
{
cls.Set();
return i;
}
int ShowBabe(int i)
{
cls.Show();
return i;
}
And finally this is the source code of the programm that uses the library.
main.cpp
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include "../simple_lib/func.h"
int main()
{
void *handle;
typedef int (*func)(int);
func bbb;
printf("start...\n");
handle = dlopen("/data/testt/test.so", RTLD_LAZY);
if (!handle)
{
printf("%s\n", dlerror());
return 0;
}
bbb = (func)dlsym(handle, "SetBabe");
if (bbb == NULL)
{
printf("%s\n", dlerror());
return 0;
}
bbb(1);
bbb = (func)dlsym(handle, "ShowBabe");
if (bbb == NULL)
{
printf("%s\n", dlerror());
return 0;
}
bbb(1);
dlclose(handle);
printf("exit...\n");
return 0;
}
Again as you can see the program using the library also does not using any STL related stuff, but after run of the program I got the same segmentation fault during main(...) function exit. So the issue is not connected to STL itself, and it is hidden in some other place. Then after some long research I found the bug.
Normally the destructors of static C++ variables are called immediately before main(...) function exit, if they are defined in main program, or if they are defined in some library and you are using it, then the destructors should be called immediately before dlclose(...).
On Android OS all destructors(defined in main program or in some library you are using) of static C++ variables are called during main(...) function exit. So what happens in our case? We have cls static C++ variable defined in library we are using. Then immediately before main(...) function exit we call dlclose(...) function, as a result library closed and cls becomes non valid. But the pointer of cls is stored somewhere and it's destructor should be called during main(...) function exit, and because at the time of call it is already invalid, we get segmentation fault. So the solution is to not call dlclose(...) and everything should be fine. Unfortunately with this solution we cannot use attribute((destructor)) for deinitializing of something we want to deinitialize, because it is called as a result of dlclose(...) call.
I have a general aversion to calling dlclose(). The problem is that you must ensure that nothing will try to execute code in the shared library after it has been unmapped, or you will get a segmentation fault.
The most common way to fail is to create an object whose destructor is defined in or calls code defined in the shared library. If the object still exists after dlclose(), your app will crash when the object is deleted.
If you look at logcat you should see a debuggerd stack trace. If you can decode that with the arm-eabi-addr2line tool you should be able to determine if it's in a destructor, and if so, for what class. Alternatively, take the crash address, strip off the high 12 bits, and use that as an offset into the library that was dlclose()d and try to figure out what code lives at that address.
I encountered the same headache on Linux. A work-around that fixes my segfault is to put these lines in the same file as main(), so that dlclose() is called after main returns:
static void* handle = 0;
void myDLClose(void) __attribute__ ((destructor));
void myDLClose(void)
{
dlclose(handle);
}
int main()
{
handle = dlopen(...);
/* ... real work ... */
return 0;
}
The root cause of dlclose-induced segfault may be that a particular implementation of dlclose() does not clean up the global variables inside the shared object.
You need to compile with -fpic as a compiler flag for the application that is using dlopen() and dlclose(). You should also try error handling via dlerror() and perhaps checking if the assignment of your function pointer is valid, even if it's not NULL the function pointer could be pointing to something invalid from the initialization, dlsym() is not guaranteed to return NULL on android if it cannot find a symbol. Refer to the android documentation opposed to the posix compliant stuff, not everything is posix compliant on android.
You should use extern "C" to declare you function aaa()