wdkl-broadcast.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. #include <string.h>
  2. #include <jni.h>
  3. #include <android/log.h>
  4. #include <gst/gst.h>
  5. #include <pthread.h>
  6. GST_DEBUG_CATEGORY_STATIC (debug_category);
  7. #define GST_CAT_DEFAULT debug_category
  8. /*
  9. * These macros provide a way to store the native pointer to CustomData, which might be 32 or 64 bits, into
  10. * a jlong, which is always 64 bits, without warnings.
  11. */
  12. #if GLIB_SIZEOF_VOID_P == 8
  13. # define GET_CUSTOM_DATA(env, thiz, fieldID) (CustomData *)(*env)->GetLongField (env, thiz, fieldID)
  14. # define SET_CUSTOM_DATA(env, thiz, fieldID, data) (*env)->SetLongField (env, thiz, fieldID, (jlong)data)
  15. #else
  16. # define GET_CUSTOM_DATA(env, thiz, fieldID) (CustomData *)(jint)(*env)->GetLongField (env, thiz, fieldID)
  17. # define SET_CUSTOM_DATA(env, thiz, fieldID, data) (*env)->SetLongField (env, thiz, fieldID, (jlong)(jint)data)
  18. #endif
  19. /* Structure to contain all our information, so we can pass it to callbacks */
  20. typedef struct _CustomData
  21. {
  22. jobject app; /* Application instance, used to call its methods. A global reference is kept. */
  23. GstElement *pipeline; /* The running pipeline */
  24. GMainContext *context; /* GLib context used to run the main loop */
  25. GMainLoop *main_loop; /* GLib main loop */
  26. gboolean initialized; /* To avoid informing the UI multiple times about the initialization */
  27. const gchar *server_str; //udp server string
  28. } CustomData;
  29. /* These global variables cache values which are not changing during execution */
  30. static pthread_t gst_app_thread;
  31. static pthread_key_t current_jni_env;
  32. static JavaVM *java_vm;
  33. static jfieldID custom_data_field_id;
  34. static jmethodID set_message_method_id;
  35. static jmethodID on_gstreamer_initialized_method_id;
  36. /*
  37. * Private methods
  38. */
  39. /* Register this thread with the VM */
  40. static JNIEnv *
  41. attach_current_thread (void)
  42. {
  43. JNIEnv *env;
  44. JavaVMAttachArgs args;
  45. GST_DEBUG ("Attaching thread %p", g_thread_self ());
  46. args.version = JNI_VERSION_1_4;
  47. args.name = NULL;
  48. args.group = NULL;
  49. if ((*java_vm)->AttachCurrentThread (java_vm, &env, &args) < 0) {
  50. GST_ERROR ("Failed to attach current thread");
  51. return NULL;
  52. }
  53. return env;
  54. }
  55. /* Unregister this thread from the VM */
  56. static void
  57. detach_current_thread (void *env)
  58. {
  59. GST_DEBUG ("Detaching thread %p", g_thread_self ());
  60. (*java_vm)->DetachCurrentThread (java_vm);
  61. }
  62. /* Retrieve the JNI environment for this thread */
  63. static JNIEnv *
  64. get_jni_env (void)
  65. {
  66. JNIEnv *env;
  67. if ((env = pthread_getspecific (current_jni_env)) == NULL) {
  68. env = attach_current_thread ();
  69. pthread_setspecific (current_jni_env, env);
  70. }
  71. return env;
  72. }
  73. /* Change the content of the UI's TextView */
  74. static void
  75. set_ui_message (const gchar * message, CustomData * data)
  76. {
  77. JNIEnv *env = get_jni_env ();
  78. GST_DEBUG ("Setting message to: %s", message);
  79. jstring jmessage = (*env)->NewStringUTF (env, message);
  80. (*env)->CallVoidMethod (env, data->app, set_message_method_id, jmessage);
  81. if ((*env)->ExceptionCheck (env)) {
  82. GST_ERROR ("Failed to call Java method");
  83. (*env)->ExceptionClear (env);
  84. }
  85. (*env)->DeleteLocalRef (env, jmessage);
  86. }
  87. /* Retrieve errors from the bus and show them on the UI */
  88. static void
  89. error_cb (GstBus * bus, GstMessage * msg, CustomData * data)
  90. {
  91. GError *err;
  92. gchar *debug_info;
  93. gchar *message_string;
  94. gst_message_parse_error (msg, &err, &debug_info);
  95. message_string =
  96. g_strdup_printf ("Error received from element %s: %s",
  97. GST_OBJECT_NAME (msg->src), err->message);
  98. g_clear_error (&err);
  99. g_free (debug_info);
  100. set_ui_message (message_string, data);
  101. g_free (message_string);
  102. gst_element_set_state (data->pipeline, GST_STATE_NULL);
  103. }
  104. /* Notify UI about pipeline state changes */
  105. static void
  106. state_changed_cb (GstBus * bus, GstMessage * msg, CustomData * data)
  107. {
  108. GstState old_state, new_state, pending_state;
  109. gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
  110. /* Only pay attention to messages coming from the pipeline, not its children */
  111. if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data->pipeline)) {
  112. gchar *message = g_strdup_printf ("State changed to %s",
  113. gst_element_state_get_name (new_state));
  114. set_ui_message (message, data);
  115. g_free (message);
  116. }
  117. }
  118. /* Check if all conditions are met to report GStreamer as initialized.
  119. * These conditions will change depending on the application */
  120. static void
  121. check_initialization_complete (CustomData * data)
  122. {
  123. JNIEnv *env = get_jni_env ();
  124. if (!data->initialized && data->main_loop) {
  125. GST_DEBUG (" 装载完成 Initialization complete, notifying application. main_loop:%p",
  126. data->main_loop);
  127. (*env)->CallVoidMethod (env, data->app, on_gstreamer_initialized_method_id);
  128. if ((*env)->ExceptionCheck (env)) {
  129. GST_ERROR ("装载失败 Failed to call Java method");
  130. (*env)->ExceptionClear (env);
  131. }
  132. data->initialized = TRUE;
  133. }
  134. }
  135. /* Main method for the native code. This is executed on its own thread. */
  136. static void *
  137. app_function (void *userdata)
  138. {
  139. JavaVMAttachArgs args;
  140. GstBus *bus;
  141. CustomData *data = (CustomData *) userdata;
  142. GSource *bus_source;
  143. GError *error = NULL;
  144. GST_DEBUG ("Creating pipeline in CustomData at %p", data);
  145. /* Create our own GLib Main Context and make it the default one */
  146. data->context = g_main_context_new ();
  147. g_main_context_push_thread_default (data->context);
  148. //char* cmd_str = "autoaudiosrc name=\"audiosrc\" ! decodebin ! queue ! audioresample ! audioconvert ! opusenc ! rtpopuspay ! udpsink ";
  149. GST_DEBUG (">>>>>>>>>>>>>>>>> %s", data->server_str);
  150. gchar *cmd =
  151. g_strdup_printf ("autoaudiosrc name=\"audiosrc\" ! decodebin ! queue ! audioresample ! audioconvert ! opusenc ! rtpopuspay ! udpsink %s", data->server_str);
  152. //char cmd[100];
  153. //strcpy(cmd,cmd_str);
  154. //strcat(cmd,data->server_str);
  155. GST_DEBUG (">>>>>>>>>>>>>>>>> %s", cmd);
  156. /* Build pipeline */
  157. // playbin uri=file:
  158. // filesrc location=/sdcard/leg.flac ! decodebin ! queue !
  159. data->pipeline =
  160. gst_parse_launch
  161. // ("audiotestsrc ! audioconvert ! audioresample ! autoaudiosink", &error);
  162. // ("audiotestsrc ! audioresample ! audioconvert ! opusenc ! rtpopuspay ! udpsink host=192.168.1.55 port=5004", &error);
  163. // ("playbin uri=file:/sdcard/leg.flac", &error);
  164. // ("filesrc location=/sdcard/leg.flac ! decodebin ! queue ! audioresample ! audioconvert ! opusenc ! rtpopuspay ! udpsink host=192.168.1.55 port=5004", &error);
  165. // ("autoaudiosrc name=\"audiosrc\" ! decodebin ! queue ! audioresample ! audioconvert ! opusenc ! rtpopuspay ! udpsink host=192.168.1.55 port=5004", &error);
  166. (cmd, &error);
  167. if (error) {
  168. gchar *message =
  169. g_strdup_printf ("Unable to build pipeline: %s", error->message);
  170. g_clear_error (&error);
  171. set_ui_message (message, data);
  172. g_free (message);
  173. return NULL;
  174. }
  175. /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */
  176. bus = gst_element_get_bus (data->pipeline);
  177. bus_source = gst_bus_create_watch (bus);
  178. g_source_set_callback (bus_source, (GSourceFunc) gst_bus_async_signal_func,
  179. NULL, NULL);
  180. g_source_attach (bus_source, data->context);
  181. g_source_unref (bus_source);
  182. g_signal_connect (G_OBJECT (bus), "message::error", (GCallback) error_cb,
  183. data);
  184. g_signal_connect (G_OBJECT (bus), "message::state-changed",
  185. (GCallback) state_changed_cb, data);
  186. 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;
  195. /* Free resources */
  196. g_main_context_pop_thread_default (data->context);
  197. g_main_context_unref (data->context);
  198. gst_element_set_state (data->pipeline, GST_STATE_NULL);
  199. gst_object_unref (data->pipeline);
  200. g_free(cmd);
  201. //g_free(cmd_str);
  202. return NULL;
  203. }
  204. /*
  205. * Java Bindings
  206. */
  207. /* Instruct the native code to create its internal data structure, pipeline and thread */
  208. static void
  209. gst_native_init (JNIEnv * env, jobject thiz, jstring server_uri)
  210. {
  211. CustomData *data = g_new0 (CustomData, 1);
  212. SET_CUSTOM_DATA (env, thiz, custom_data_field_id, data);
  213. GST_DEBUG_CATEGORY_INIT (debug_category, "tutorial-2", 0,
  214. "Android tutorial 2");
  215. gst_debug_set_threshold_for_name ("tutorial-2", 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. const gchar *char_uri = (*env)->GetStringUTFChars (env, server_uri, NULL);
  220. // GST_DEBUG (">>>>>>>>>>>>>>>>> %s", char_uri);
  221. data->server_str = char_uri;
  222. // GST_DEBUG (">>>>>>>>>>>>>>>>> %s", data->server_str);
  223. pthread_create (&gst_app_thread, NULL, &app_function, data);
  224. }
  225. /* Quit the main loop, remove the native thread and free resources */
  226. static void
  227. gst_native_finalize (JNIEnv * env, jobject thiz)
  228. {
  229. CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
  230. if (!data)
  231. return;
  232. GST_DEBUG ("Quitting main loop...");
  233. g_main_loop_quit (data->main_loop);
  234. GST_DEBUG ("Waiting for thread to finish...");
  235. pthread_join (gst_app_thread, NULL);
  236. GST_DEBUG ("Deleting GlobalRef for app object at %p", data->app);
  237. (*env)->DeleteGlobalRef (env, data->app);
  238. GST_DEBUG ("Freeing CustomData at %p", data);
  239. g_free (data);
  240. SET_CUSTOM_DATA (env, thiz, custom_data_field_id, NULL);
  241. GST_DEBUG ("Done finalizing");
  242. }
  243. /* Set pipeline to PLAYING state */
  244. static void
  245. gst_native_play (JNIEnv * env, jobject thiz)
  246. {
  247. CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
  248. if (!data)
  249. return;
  250. GST_DEBUG ("Setting state to PLAYING");
  251. gst_element_set_state (data->pipeline, GST_STATE_PLAYING);
  252. }
  253. /* Set pipeline to PAUSED state */
  254. static void
  255. gst_native_pause (JNIEnv * env, jobject thiz)
  256. {
  257. CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
  258. if (!data)
  259. return;
  260. GST_DEBUG ("Setting state to PAUSED");
  261. gst_element_set_state (data->pipeline, GST_STATE_PAUSED);
  262. }
  263. /* Static class initializer: retrieve method and field IDs */
  264. static jboolean
  265. gst_native_class_init (JNIEnv * env, jclass klass)
  266. {
  267. custom_data_field_id =
  268. (*env)->GetFieldID (env, klass, "native_custom_data", "J");
  269. set_message_method_id =
  270. (*env)->GetMethodID (env, klass, "setMessage", "(Ljava/lang/String;)V");
  271. on_gstreamer_initialized_method_id =
  272. (*env)->GetMethodID (env, klass, "onGStreamerInitialized", "()V");
  273. if (!custom_data_field_id || !set_message_method_id
  274. || !on_gstreamer_initialized_method_id) {
  275. /* We emit this message through the Android log instead of the GStreamer log because the later
  276. * has not been initialized yet.
  277. */
  278. __android_log_print (ANDROID_LOG_ERROR, "tutorial-2",
  279. "The calling class does not implement all necessary interface methods");
  280. return JNI_FALSE;
  281. }
  282. return JNI_TRUE;
  283. }
  284. /* List of implemented native methods */
  285. static JNINativeMethod native_methods[] = {
  286. {"nativeInit", "(Ljava/lang/String;)V", (void *) gst_native_init},
  287. {"nativeFinalize", "()V", (void *) gst_native_finalize},
  288. {"nativePlay", "()V", (void *) gst_native_play},
  289. {"nativePause", "()V", (void *) gst_native_pause},
  290. {"nativeClassInit", "()Z", (void *) gst_native_class_init}
  291. };
  292. /* Library initializer */
  293. jint
  294. JNI_OnLoad (JavaVM * vm, void *reserved)
  295. {
  296. JNIEnv *env = NULL;
  297. java_vm = vm;
  298. if ((*vm)->GetEnv (vm, (void **) &env, JNI_VERSION_1_4) != JNI_OK) {
  299. __android_log_print (ANDROID_LOG_ERROR, "wdkl-broadcast",
  300. "Could not retrieve JNIEnv");
  301. return 0;
  302. }
  303. //jclass klass = (*env)->FindClass (env,
  304. // "com/wdkl/gstreamer/demo/MainActivity");
  305. jclass klass = (*env)->FindClass (env, "com/wdkl/gstreamer/demo/MyGstream");
  306. (*env)->RegisterNatives (env, klass, native_methods,
  307. G_N_ELEMENTS (native_methods));
  308. pthread_key_create (&current_jni_env, detach_current_thread);
  309. return JNI_VERSION_1_4;
  310. }