4 #include <android/log.h>
5 #include <android/native_window.h>
6 #include <android/native_window_jni.h>
8 #include <gst/video/video.h>
11 GST_DEBUG_CATEGORY_STATIC (debug_category);
12 #define GST_CAT_DEFAULT debug_category
15 * These macros provide a way to store the native pointer to CustomData, which might be 32 or 64 bits, into
16 * a jlong, which is always 64 bits, without warnings.
18 #if GLIB_SIZEOF_VOID_P == 8
19 # define GET_CUSTOM_DATA(env, thiz, fieldID) (CustomData *)(*env)->GetLongField (env, thiz, fieldID)
20 # define SET_CUSTOM_DATA(env, thiz, fieldID, data) (*env)->SetLongField (env, thiz, fieldID, (jlong)data)
22 # define GET_CUSTOM_DATA(env, thiz, fieldID) (CustomData *)(jint)(*env)->GetLongField (env, thiz, fieldID)
23 # define SET_CUSTOM_DATA(env, thiz, fieldID, data) (*env)->SetLongField (env, thiz, fieldID, (jlong)(jint)data)
26 /* Structure to contain all our information, so we can pass it to callbacks */
27 typedef struct _CustomData {
28 jobject app; /* Application instance, used to call its methods. A global reference is kept. */
29 GstElement *pipeline; /* The running pipeline */
30 GMainContext *context; /* GLib context used to run the main loop */
31 GMainLoop *main_loop; /* GLib main loop */
32 gboolean initialized; /* To avoid informing the UI multiple times about the initialization */
33 GstElement *video_sink; /* The video sink element which receives XOverlay commands */
34 ANativeWindow *native_window; /* The Android native window where video will be rendered */
37 /* These global variables cache values which are not changing during execution */
38 static pthread_t gst_app_thread;
39 static pthread_key_t current_jni_env;
40 static JavaVM *java_vm;
41 static jfieldID custom_data_field_id;
42 static jmethodID set_message_method_id;
43 static jmethodID on_gstreamer_initialized_method_id;
49 /* Register this thread with the VM */
50 static JNIEnv *attach_current_thread (void) {
52 JavaVMAttachArgs args;
54 GST_DEBUG ("Attaching thread %p", g_thread_self ());
55 args.version = JNI_VERSION_1_4;
59 if ((*java_vm)->AttachCurrentThread (java_vm, &env, &args) < 0) {
60 GST_ERROR ("Failed to attach current thread");
67 /* Unregister this thread from the VM */
68 static void detach_current_thread (void *env) {
69 GST_DEBUG ("Detaching thread %p", g_thread_self ());
70 (*java_vm)->DetachCurrentThread (java_vm);
73 /* Retrieve the JNI environment for this thread */
74 static JNIEnv *get_jni_env (void) {
77 if ((env = pthread_getspecific (current_jni_env)) == NULL) {
78 env = attach_current_thread ();
79 pthread_setspecific (current_jni_env, env);
85 /* Change the content of the UI's TextView */
86 static void set_ui_message (const gchar *message, CustomData *data) {
87 JNIEnv *env = get_jni_env ();
88 GST_DEBUG ("Setting message to: %s", message);
89 jstring jmessage = (*env)->NewStringUTF(env, message);
90 (*env)->CallVoidMethod (env, data->app, set_message_method_id, jmessage);
91 if ((*env)->ExceptionCheck (env)) {
92 GST_ERROR ("Failed to call Java method");
93 (*env)->ExceptionClear (env);
95 (*env)->DeleteLocalRef (env, jmessage);
98 /* Retrieve errors from the bus and show them on the UI */
99 static void error_cb (GstBus *bus, GstMessage *msg, CustomData *data) {
102 gchar *message_string;
104 gst_message_parse_error (msg, &err, &debug_info);
105 message_string = g_strdup_printf ("Error received from element %s: %s", GST_OBJECT_NAME (msg->src), err->message);
106 g_clear_error (&err);
108 set_ui_message (message_string, data);
109 g_free (message_string);
110 gst_element_set_state (data->pipeline, GST_STATE_NULL);
113 /* Notify UI about pipeline state changes */
114 static void state_changed_cb (GstBus *bus, GstMessage *msg, CustomData *data) {
115 GstState old_state, new_state, pending_state;
116 gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
117 /* Only pay attention to messages coming from the pipeline, not its children */
118 if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data->pipeline)) {
119 gchar *message = g_strdup_printf("State changed to %s", gst_element_state_get_name(new_state));
120 set_ui_message(message, data);
125 /* Check if all conditions are met to report GStreamer as initialized.
126 * These conditions will change depending on the application */
127 static void check_initialization_complete (CustomData *data) {
128 JNIEnv *env = get_jni_env ();
129 if (!data->initialized && data->native_window && data->main_loop) {
130 GST_DEBUG ("Initialization complete, notifying application. native_window:%p main_loop:%p", data->native_window, data->main_loop);
132 /* The main loop is running and we received a native window, inform the sink about it */
133 gst_video_overlay_set_window_handle (GST_VIDEO_OVERLAY (data->video_sink), (guintptr)data->native_window);
135 (*env)->CallVoidMethod (env, data->app, on_gstreamer_initialized_method_id);
136 if ((*env)->ExceptionCheck (env)) {
137 GST_ERROR ("Failed to call Java method");
138 (*env)->ExceptionClear (env);
140 data->initialized = TRUE;
144 /* Main method for the native code. This is executed on its own thread. */
145 static void *app_function (void *userdata) {
146 JavaVMAttachArgs args;
148 CustomData *data = (CustomData *)userdata;
150 GError *error = NULL;
152 GST_DEBUG ("Creating pipeline in CustomData at %p", data);
154 /* Create our own GLib Main Context and make it the default one */
155 data->context = g_main_context_new ();
156 g_main_context_push_thread_default(data->context);
159 data->pipeline = gst_parse_launch("videotestsrc ! warptv ! videoconvert ! autovideosink", &error);
161 gchar *message = g_strdup_printf("Unable to build pipeline: %s", error->message);
162 g_clear_error (&error);
163 set_ui_message(message, data);
168 /* Set the pipeline to READY, so it can already accept a window handle, if we have one */
169 gst_element_set_state(data->pipeline, GST_STATE_READY);
171 data->video_sink = gst_bin_get_by_interface(GST_BIN(data->pipeline), GST_TYPE_VIDEO_OVERLAY);
172 if (!data->video_sink) {
173 GST_ERROR ("Could not retrieve video sink");
177 /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */
178 bus = gst_element_get_bus (data->pipeline);
179 bus_source = gst_bus_create_watch (bus);
180 g_source_set_callback (bus_source, (GSourceFunc) gst_bus_async_signal_func, NULL, NULL);
181 g_source_attach (bus_source, data->context);
182 g_source_unref (bus_source);
183 g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, data);
184 g_signal_connect (G_OBJECT (bus), "message::state-changed", (GCallback)state_changed_cb, data);
185 gst_object_unref (bus);
187 /* Create a GLib Main Loop and set it to run */
188 GST_DEBUG ("Entering main loop... (CustomData:%p)", data);
189 data->main_loop = g_main_loop_new (data->context, FALSE);
190 check_initialization_complete (data);
191 g_main_loop_run (data->main_loop);
192 GST_DEBUG ("Exited main loop");
193 g_main_loop_unref (data->main_loop);
194 data->main_loop = NULL;
197 g_main_context_pop_thread_default(data->context);
198 g_main_context_unref (data->context);
199 gst_element_set_state (data->pipeline, GST_STATE_NULL);
200 gst_object_unref (data->video_sink);
201 gst_object_unref (data->pipeline);
210 /* Instruct the native code to create its internal data structure, pipeline and thread */
211 static void gst_native_init (JNIEnv* env, jobject thiz) {
212 CustomData *data = g_new0 (CustomData, 1);
213 SET_CUSTOM_DATA (env, thiz, custom_data_field_id, data);
214 GST_DEBUG_CATEGORY_INIT (debug_category, "tutorial-3", 0, "Android tutorial 3");
215 gst_debug_set_threshold_for_name("tutorial-3", GST_LEVEL_DEBUG);
216 GST_DEBUG ("Created CustomData at %p", data);
217 data->app = (*env)->NewGlobalRef (env, thiz);
218 GST_DEBUG ("Created GlobalRef for app object at %p", data->app);
219 pthread_create (&gst_app_thread, NULL, &app_function, data);
222 /* Quit the main loop, remove the native thread and free resources */
223 static void gst_native_finalize (JNIEnv* env, jobject thiz) {
224 CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
226 GST_DEBUG ("Quitting main loop...");
227 g_main_loop_quit (data->main_loop);
228 GST_DEBUG ("Waiting for thread to finish...");
229 pthread_join (gst_app_thread, NULL);
230 GST_DEBUG ("Deleting GlobalRef for app object at %p", data->app);
231 (*env)->DeleteGlobalRef (env, data->app);
232 GST_DEBUG ("Freeing CustomData at %p", data);
234 SET_CUSTOM_DATA (env, thiz, custom_data_field_id, NULL);
235 GST_DEBUG ("Done finalizing");
238 /* Set pipeline to PLAYING state */
239 static void gst_native_play (JNIEnv* env, jobject thiz) {
240 CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
242 GST_DEBUG ("Setting state to PLAYING");
243 gst_element_set_state (data->pipeline, GST_STATE_PLAYING);
246 /* Set pipeline to PAUSED state */
247 static void gst_native_pause (JNIEnv* env, jobject thiz) {
248 CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
250 GST_DEBUG ("Setting state to PAUSED");
251 gst_element_set_state (data->pipeline, GST_STATE_PAUSED);
254 /* Static class initializer: retrieve method and field IDs */
255 static jboolean gst_native_class_init (JNIEnv* env, jclass klass) {
256 custom_data_field_id = (*env)->GetFieldID (env, klass, "native_custom_data", "J");
257 set_message_method_id = (*env)->GetMethodID (env, klass, "setMessage", "(Ljava/lang/String;)V");
258 on_gstreamer_initialized_method_id = (*env)->GetMethodID (env, klass, "onGStreamerInitialized", "()V");
260 if (!custom_data_field_id || !set_message_method_id || !on_gstreamer_initialized_method_id) {
261 /* We emit this message through the Android log instead of the GStreamer log because the later
262 * has not been initialized yet.
264 __android_log_print (ANDROID_LOG_ERROR, "tutorial-3", "The calling class does not implement all necessary interface methods");
270 static void gst_native_surface_init (JNIEnv *env, jobject thiz, jobject surface) {
271 CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
273 ANativeWindow *new_native_window = ANativeWindow_fromSurface(env, surface);
274 GST_DEBUG ("Received surface %p (native window %p)", surface, new_native_window);
276 if (data->native_window) {
277 ANativeWindow_release (data->native_window);
278 if (data->native_window == new_native_window) {
279 GST_DEBUG ("New native window is the same as the previous one %p", data->native_window);
280 if (data->video_sink) {
281 gst_video_overlay_expose(GST_VIDEO_OVERLAY (data->video_sink));
282 gst_video_overlay_expose(GST_VIDEO_OVERLAY (data->video_sink));
286 GST_DEBUG ("Released previous native window %p", data->native_window);
287 data->initialized = FALSE;
290 data->native_window = new_native_window;
292 check_initialization_complete (data);
295 static void gst_native_surface_finalize (JNIEnv *env, jobject thiz) {
296 CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
298 GST_DEBUG ("Releasing Native Window %p", data->native_window);
300 if (data->video_sink) {
301 gst_video_overlay_set_window_handle (GST_VIDEO_OVERLAY (data->video_sink), (guintptr)NULL);
302 gst_element_set_state (data->pipeline, GST_STATE_READY);
305 ANativeWindow_release (data->native_window);
306 data->native_window = NULL;
307 data->initialized = FALSE;
310 /* List of implemented native methods */
311 static JNINativeMethod native_methods[] = {
312 { "nativeInit", "()V", (void *) gst_native_init},
313 { "nativeFinalize", "()V", (void *) gst_native_finalize},
314 { "nativePlay", "()V", (void *) gst_native_play},
315 { "nativePause", "()V", (void *) gst_native_pause},
316 { "nativeSurfaceInit", "(Ljava/lang/Object;)V", (void *) gst_native_surface_init},
317 { "nativeSurfaceFinalize", "()V", (void *) gst_native_surface_finalize},
318 { "nativeClassInit", "()Z", (void *) gst_native_class_init}
321 /* Library initializer */
322 jint JNI_OnLoad(JavaVM *vm, void *reserved) {
327 if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_4) != JNI_OK) {
328 __android_log_print (ANDROID_LOG_ERROR, "tutorial-3", "Could not retrieve JNIEnv");
331 jclass klass = (*env)->FindClass (env, "org/freedesktop/gstreamer/tutorials/tutorial_3/Tutorial3");
332 (*env)->RegisterNatives (env, klass, native_methods, G_N_ELEMENTS(native_methods));
334 pthread_key_create (¤t_jni_env, detach_current_thread);
336 return JNI_VERSION_1_4;