This commit is contained in:
Akkariin Meiko
2022-03-12 03:16:09 +08:00
Unverified
parent 12b76e0c7a
commit 27c4ec74a1
10075 changed files with 5122287 additions and 1 deletions
@@ -0,0 +1,4 @@
.externalNativeBuild/
assets/
gst-build-*/
src/org/
@@ -0,0 +1,91 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.freedesktop.gstreamer.tutorials.tutorial_5"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-feature android:glEsVersion="0x00020000" />
<application
android:icon="@drawable/gstreamer_logo_5"
android:label="@string/app_name" >
<activity
android:name=".Tutorial5"
android:label="@string/app_name"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Local files whose MIME type is known to Android -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:mimeType="audio/*" />
<data android:mimeType="video/*" />
<data android:mimeType="image/*" />
</intent-filter>
<!-- Local files with unknown MIME type.
The list of extensions and supported protocols can certainly be extended. -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="file" />
<data android:mimeType="*/*" />
<data android:pathPattern=".*\\.avi" />
<data android:pathPattern=".*\\.AVI" />
<data android:pathPattern=".*\\.mkv" />
<data android:pathPattern=".*\\.MKV" />
<data android:pathPattern=".*\\.webm" />
<data android:pathPattern=".*\\.WEBM" />
<data android:pathPattern=".*\\.ogv" />
<data android:pathPattern=".*\\.OGV" />
<data android:pathPattern=".*\\.mp4" />
<data android:pathPattern=".*\\.MP4" />
<data android:pathPattern=".*\\.mov" />
<data android:pathPattern=".*\\.MOV" />
</intent-filter>
<!-- Remote files. These typically have unknown MIME type.
The list of extensions and supported protocols can certainly be extended. -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:pathPattern=".*\\.avi" />
<data android:pathPattern=".*\\.AVI" />
<data android:pathPattern=".*\\.mkv" />
<data android:pathPattern=".*\\.MKV" />
<data android:pathPattern=".*\\.webm" />
<data android:pathPattern=".*\\.WEBM" />
<data android:pathPattern=".*\\.ogv" />
<data android:pathPattern=".*\\.OGV" />
<data android:pathPattern=".*\\.mp4" />
<data android:pathPattern=".*\\.MP4" />
<data android:pathPattern=".*\\.mov" />
<data android:pathPattern=".*\\.MOV" />
</intent-filter>
</activity>
<activity
android:name="com.lamerman.FileDialog"
android:label="@string/filechooser_name" >
</activity>
</application>
</manifest>
@@ -0,0 +1,72 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion 32
defaultConfig {
applicationId "org.freedesktop.gstreamer.tutorials.tutorial_5"
minSdkVersion 15
targetSdkVersion 32
versionCode 1
versionName "1.0"
externalNativeBuild {
ndkBuild {
def gstRoot
if (project.hasProperty('gstAndroidRoot'))
gstRoot = project.gstAndroidRoot
else
gstRoot = System.env.GSTREAMER_ROOT_ANDROID
if (gstRoot == null)
throw new GradleException('GSTREAMER_ROOT_ANDROID must be set, or "gstAndroidRoot" must be defined in your gradle.properties in the top level directory of the unpacked universal GStreamer Android binaries')
arguments "NDK_APPLICATION_MK=jni/Application.mk", "GSTREAMER_JAVA_SRC_DIR=src", "GSTREAMER_ROOT_ANDROID=$gstRoot", "GSTREAMER_ASSETS_DIR=src/assets"
targets "tutorial-5"
// All archs except MIPS and MIPS64 are supported
abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
}
}
externalNativeBuild {
ndkBuild {
path 'jni/Android.mk'
}
}
}
afterEvaluate {
if (project.hasProperty('compileDebugJavaWithJavac'))
project.compileDebugJavaWithJavac.dependsOn 'externalNativeBuildDebug'
if (project.hasProperty('compileReleaseJavaWithJavac'))
project.compileReleaseJavaWithJavac.dependsOn 'externalNativeBuildRelease'
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:appcompat-v7:23.1.1'
}
@@ -0,0 +1,34 @@
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := tutorial-5
LOCAL_SRC_FILES := tutorial-5.c dummy.cpp
LOCAL_SHARED_LIBRARIES := gstreamer_android
LOCAL_LDLIBS := -llog -landroid
include $(BUILD_SHARED_LIBRARY)
ifndef GSTREAMER_ROOT_ANDROID
$(error GSTREAMER_ROOT_ANDROID is not defined!)
endif
ifeq ($(TARGET_ARCH_ABI),armeabi)
GSTREAMER_ROOT := $(GSTREAMER_ROOT_ANDROID)/arm
else ifeq ($(TARGET_ARCH_ABI),armeabi-v7a)
GSTREAMER_ROOT := $(GSTREAMER_ROOT_ANDROID)/armv7
else ifeq ($(TARGET_ARCH_ABI),arm64-v8a)
GSTREAMER_ROOT := $(GSTREAMER_ROOT_ANDROID)/arm64
else ifeq ($(TARGET_ARCH_ABI),x86)
GSTREAMER_ROOT := $(GSTREAMER_ROOT_ANDROID)/x86
else ifeq ($(TARGET_ARCH_ABI),x86_64)
GSTREAMER_ROOT := $(GSTREAMER_ROOT_ANDROID)/x86_64
else
$(error Target arch ABI not supported: $(TARGET_ARCH_ABI))
endif
GSTREAMER_NDK_BUILD_PATH := $(GSTREAMER_ROOT)/share/gst-android/ndk-build/
include $(GSTREAMER_NDK_BUILD_PATH)/plugins.mk
GSTREAMER_PLUGINS := $(GSTREAMER_PLUGINS_CORE) $(GSTREAMER_PLUGINS_PLAYBACK) $(GSTREAMER_PLUGINS_CODECS) $(GSTREAMER_PLUGINS_NET) $(GSTREAMER_PLUGINS_SYS)
G_IO_MODULES := openssl
GSTREAMER_EXTRA_DEPS := gstreamer-video-1.0
include $(GSTREAMER_NDK_BUILD_PATH)/gstreamer-1.0.mk
@@ -0,0 +1,2 @@
APP_ABI = armeabi armeabi-v7a arm64-v8a x86 x86_64
APP_STL = c++_shared
@@ -0,0 +1,683 @@
#include <string.h>
#include <stdint.h>
#include <jni.h>
#include <android/log.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <gst/gst.h>
#include <gst/video/video.h>
#include <gst/video/videooverlay.h>
#include <pthread.h>
GST_DEBUG_CATEGORY_STATIC (debug_category);
#define GST_CAT_DEFAULT debug_category
/*
* These macros provide a way to store the native pointer to CustomData, which might be 32 or 64 bits, into
* a jlong, which is always 64 bits, without warnings.
*/
#if GLIB_SIZEOF_VOID_P == 8
# define GET_CUSTOM_DATA(env, thiz, fieldID) (CustomData *)(*env)->GetLongField (env, thiz, fieldID)
# define SET_CUSTOM_DATA(env, thiz, fieldID, data) (*env)->SetLongField (env, thiz, fieldID, (jlong)data)
#else
# define GET_CUSTOM_DATA(env, thiz, fieldID) (CustomData *)(jint)(*env)->GetLongField (env, thiz, fieldID)
# define SET_CUSTOM_DATA(env, thiz, fieldID, data) (*env)->SetLongField (env, thiz, fieldID, (jlong)(jint)data)
#endif
/* Do not allow seeks to be performed closer than this distance. It is visually useless, and will probably
* confuse some demuxers. */
#define SEEK_MIN_DELAY (500 * GST_MSECOND)
/* Structure to contain all our information, so we can pass it to callbacks */
typedef struct _CustomData
{
jobject app; /* Application instance, used to call its methods. A global reference is kept. */
GstElement *pipeline; /* The running pipeline */
GMainContext *context; /* GLib context used to run the main loop */
GMainLoop *main_loop; /* GLib main loop */
gboolean initialized; /* To avoid informing the UI multiple times about the initialization */
ANativeWindow *native_window; /* The Android native window where video will be rendered */
GstState state; /* Current pipeline state */
GstState target_state; /* Desired pipeline state, to be set once buffering is complete */
gint64 duration; /* Cached clip duration */
gint64 desired_position; /* Position to seek to, once the pipeline is running */
GstClockTime last_seek_time; /* For seeking overflow prevention (throttling) */
gboolean is_live; /* Live streams do not use buffering */
} CustomData;
/* playbin2 flags */
typedef enum
{
GST_PLAY_FLAG_TEXT = (1 << 2) /* We want subtitle output */
} GstPlayFlags;
/* These global variables cache values which are not changing during execution */
static pthread_t gst_app_thread;
static pthread_key_t current_jni_env;
static JavaVM *java_vm;
static jfieldID custom_data_field_id;
static jmethodID set_message_method_id;
static jmethodID set_current_position_method_id;
static jmethodID on_gstreamer_initialized_method_id;
static jmethodID on_media_size_changed_method_id;
/*
* Private methods
*/
/* Register this thread with the VM */
static JNIEnv *
attach_current_thread (void)
{
JNIEnv *env;
JavaVMAttachArgs args;
GST_DEBUG ("Attaching thread %p", g_thread_self ());
args.version = JNI_VERSION_1_4;
args.name = NULL;
args.group = NULL;
if ((*java_vm)->AttachCurrentThread (java_vm, &env, &args) < 0) {
GST_ERROR ("Failed to attach current thread");
return NULL;
}
return env;
}
/* Unregister this thread from the VM */
static void
detach_current_thread (void *env)
{
GST_DEBUG ("Detaching thread %p", g_thread_self ());
(*java_vm)->DetachCurrentThread (java_vm);
}
/* Retrieve the JNI environment for this thread */
static JNIEnv *
get_jni_env (void)
{
JNIEnv *env;
if ((env = pthread_getspecific (current_jni_env)) == NULL) {
env = attach_current_thread ();
pthread_setspecific (current_jni_env, env);
}
return env;
}
/* Change the content of the UI's TextView */
static void
set_ui_message (const gchar * message, CustomData * data)
{
JNIEnv *env = get_jni_env ();
GST_DEBUG ("Setting message to: %s", message);
jstring jmessage = (*env)->NewStringUTF (env, message);
(*env)->CallVoidMethod (env, data->app, set_message_method_id, jmessage);
if ((*env)->ExceptionCheck (env)) {
GST_ERROR ("Failed to call Java method");
(*env)->ExceptionClear (env);
}
(*env)->DeleteLocalRef (env, jmessage);
}
/* Tell the application what is the current position and clip duration */
static void
set_current_ui_position (gint position, gint duration, CustomData * data)
{
JNIEnv *env = get_jni_env ();
(*env)->CallVoidMethod (env, data->app, set_current_position_method_id,
position, duration);
if ((*env)->ExceptionCheck (env)) {
GST_ERROR ("Failed to call Java method");
(*env)->ExceptionClear (env);
}
}
/* If we have pipeline and it is running, query the current position and clip duration and inform
* the application */
static gboolean
refresh_ui (CustomData * data)
{
gint64 current = -1;
gint64 position;
/* We do not want to update anything unless we have a working pipeline in the PAUSED or PLAYING state */
if (!data || !data->pipeline || data->state < GST_STATE_PAUSED)
return TRUE;
/* If we didn't know it yet, query the stream duration */
if (!GST_CLOCK_TIME_IS_VALID (data->duration)) {
if (!gst_element_query_duration (data->pipeline, GST_FORMAT_TIME,
&data->duration)) {
GST_WARNING
("Could not query current duration (normal for still pictures)");
data->duration = 0;
}
}
if (!gst_element_query_position (data->pipeline, GST_FORMAT_TIME, &position)) {
GST_WARNING
("Could not query current position (normal for still pictures)");
position = 0;
}
/* Java expects these values in milliseconds, and GStreamer provides nanoseconds */
set_current_ui_position (position / GST_MSECOND, data->duration / GST_MSECOND,
data);
return TRUE;
}
/* Forward declaration for the delayed seek callback */
static gboolean delayed_seek_cb (CustomData * data);
/* Perform seek, if we are not too close to the previous seek. Otherwise, schedule the seek for
* some time in the future. */
static void
execute_seek (gint64 desired_position, CustomData * data)
{
gint64 diff;
if (desired_position == GST_CLOCK_TIME_NONE)
return;
diff = gst_util_get_timestamp () - data->last_seek_time;
if (GST_CLOCK_TIME_IS_VALID (data->last_seek_time) && diff < SEEK_MIN_DELAY) {
/* The previous seek was too close, delay this one */
GSource *timeout_source;
if (data->desired_position == GST_CLOCK_TIME_NONE) {
/* There was no previous seek scheduled. Setup a timer for some time in the future */
timeout_source =
g_timeout_source_new ((SEEK_MIN_DELAY - diff) / GST_MSECOND);
g_source_set_callback (timeout_source, (GSourceFunc) delayed_seek_cb,
data, NULL);
g_source_attach (timeout_source, data->context);
g_source_unref (timeout_source);
}
/* Update the desired seek position. If multiple petitions are received before it is time
* to perform a seek, only the last one is remembered. */
data->desired_position = desired_position;
GST_DEBUG ("Throttling seek to %" GST_TIME_FORMAT ", will be in %"
GST_TIME_FORMAT, GST_TIME_ARGS (desired_position),
GST_TIME_ARGS (SEEK_MIN_DELAY - diff));
} else {
/* Perform the seek now */
GST_DEBUG ("Seeking to %" GST_TIME_FORMAT,
GST_TIME_ARGS (desired_position));
data->last_seek_time = gst_util_get_timestamp ();
gst_element_seek_simple (data->pipeline, GST_FORMAT_TIME,
GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, desired_position);
data->desired_position = GST_CLOCK_TIME_NONE;
}
}
/* Delayed seek callback. This gets called by the timer setup in the above function. */
static gboolean
delayed_seek_cb (CustomData * data)
{
GST_DEBUG ("Doing delayed seek to %" GST_TIME_FORMAT,
GST_TIME_ARGS (data->desired_position));
execute_seek (data->desired_position, data);
return FALSE;
}
/* Retrieve errors from the bus and show them on the UI */
static void
error_cb (GstBus * bus, GstMessage * msg, CustomData * data)
{
GError *err;
gchar *debug_info;
gchar *message_string;
gst_message_parse_error (msg, &err, &debug_info);
message_string =
g_strdup_printf ("Error received from element %s: %s",
GST_OBJECT_NAME (msg->src), err->message);
g_clear_error (&err);
g_free (debug_info);
set_ui_message (message_string, data);
g_free (message_string);
data->target_state = GST_STATE_NULL;
gst_element_set_state (data->pipeline, GST_STATE_NULL);
}
/* Called when the End Of the Stream is reached. Just move to the beginning of the media and pause. */
static void
eos_cb (GstBus * bus, GstMessage * msg, CustomData * data)
{
data->target_state = GST_STATE_PAUSED;
data->is_live |=
(gst_element_set_state (data->pipeline,
GST_STATE_PAUSED) == GST_STATE_CHANGE_NO_PREROLL);
execute_seek (0, data);
}
/* Called when the duration of the media changes. Just mark it as unknown, so we re-query it in the next UI refresh. */
static void
duration_cb (GstBus * bus, GstMessage * msg, CustomData * data)
{
data->duration = GST_CLOCK_TIME_NONE;
}
/* Called when buffering messages are received. We inform the UI about the current buffering level and
* keep the pipeline paused until 100% buffering is reached. At that point, set the desired state. */
static void
buffering_cb (GstBus * bus, GstMessage * msg, CustomData * data)
{
gint percent;
if (data->is_live)
return;
gst_message_parse_buffering (msg, &percent);
if (percent < 100 && data->target_state >= GST_STATE_PAUSED) {
gchar *message_string = g_strdup_printf ("Buffering %d%%", percent);
gst_element_set_state (data->pipeline, GST_STATE_PAUSED);
set_ui_message (message_string, data);
g_free (message_string);
} else if (data->target_state >= GST_STATE_PLAYING) {
gst_element_set_state (data->pipeline, GST_STATE_PLAYING);
} else if (data->target_state >= GST_STATE_PAUSED) {
set_ui_message ("Buffering complete", data);
}
}
/* Called when the clock is lost */
static void
clock_lost_cb (GstBus * bus, GstMessage * msg, CustomData * data)
{
if (data->target_state >= GST_STATE_PLAYING) {
gst_element_set_state (data->pipeline, GST_STATE_PAUSED);
gst_element_set_state (data->pipeline, GST_STATE_PLAYING);
}
}
/* Retrieve the video sink's Caps and tell the application about the media size */
static void
check_media_size (CustomData * data)
{
JNIEnv *env = get_jni_env ();
GstElement *video_sink;
GstPad *video_sink_pad;
GstCaps *caps;
GstVideoInfo info;
/* Retrieve the Caps at the entrance of the video sink */
g_object_get (data->pipeline, "video-sink", &video_sink, NULL);
video_sink_pad = gst_element_get_static_pad (video_sink, "sink");
caps = gst_pad_get_current_caps (video_sink_pad);
if (gst_video_info_from_caps (&info, caps)) {
info.width = info.width * info.par_n / info.par_d;
GST_DEBUG ("Media size is %dx%d, notifying application", info.width,
info.height);
(*env)->CallVoidMethod (env, data->app, on_media_size_changed_method_id,
(jint) info.width, (jint) info.height);
if ((*env)->ExceptionCheck (env)) {
GST_ERROR ("Failed to call Java method");
(*env)->ExceptionClear (env);
}
}
gst_caps_unref (caps);
gst_object_unref (video_sink_pad);
gst_object_unref (video_sink);
}
/* Notify UI about pipeline state changes */
static void
state_changed_cb (GstBus * bus, GstMessage * msg, CustomData * data)
{
GstState old_state, new_state, pending_state;
gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
/* Only pay attention to messages coming from the pipeline, not its children */
if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data->pipeline)) {
data->state = new_state;
gchar *message = g_strdup_printf ("State changed to %s",
gst_element_state_get_name (new_state));
set_ui_message (message, data);
g_free (message);
if (new_state == GST_STATE_NULL || new_state == GST_STATE_READY)
data->is_live = FALSE;
/* The Ready to Paused state change is particularly interesting: */
if (old_state == GST_STATE_READY && new_state == GST_STATE_PAUSED) {
/* By now the sink already knows the media size */
check_media_size (data);
/* If there was a scheduled seek, perform it now that we have moved to the Paused state */
if (GST_CLOCK_TIME_IS_VALID (data->desired_position))
execute_seek (data->desired_position, data);
}
}
}
/* Check if all conditions are met to report GStreamer as initialized.
* These conditions will change depending on the application */
static void
check_initialization_complete (CustomData * data)
{
JNIEnv *env = get_jni_env ();
if (!data->initialized && data->native_window && data->main_loop) {
GST_DEBUG
("Initialization complete, notifying application. native_window:%p main_loop:%p",
data->native_window, data->main_loop);
/* The main loop is running and we received a native window, inform the sink about it */
gst_video_overlay_set_window_handle (GST_VIDEO_OVERLAY (data->pipeline),
(guintptr) data->native_window);
(*env)->CallVoidMethod (env, data->app, on_gstreamer_initialized_method_id);
if ((*env)->ExceptionCheck (env)) {
GST_ERROR ("Failed to call Java method");
(*env)->ExceptionClear (env);
}
data->initialized = TRUE;
}
}
/* Main method for the native code. This is executed on its own thread. */
static void *
app_function (void *userdata)
{
JavaVMAttachArgs args;
GstBus *bus;
CustomData *data = (CustomData *) userdata;
GSource *timeout_source;
GSource *bus_source;
GError *error = NULL;
guint flags;
GST_DEBUG ("Creating pipeline in CustomData at %p", data);
/* Create our own GLib Main Context and make it the default one */
data->context = g_main_context_new ();
g_main_context_push_thread_default (data->context);
/* Build pipeline */
data->pipeline = gst_parse_launch ("playbin", &error);
if (error) {
gchar *message =
g_strdup_printf ("Unable to build pipeline: %s", error->message);
g_clear_error (&error);
set_ui_message (message, data);
g_free (message);
return NULL;
}
/* Disable subtitles */
g_object_get (data->pipeline, "flags", &flags, NULL);
flags &= ~GST_PLAY_FLAG_TEXT;
g_object_set (data->pipeline, "flags", flags, NULL);
/* Set the pipeline to READY, so it can already accept a window handle, if we have one */
data->target_state = GST_STATE_READY;
gst_element_set_state (data->pipeline, GST_STATE_READY);
/* Instruct the bus to emit signals for each received message, and connect to the interesting signals */
bus = gst_element_get_bus (data->pipeline);
bus_source = gst_bus_create_watch (bus);
g_source_set_callback (bus_source, (GSourceFunc) gst_bus_async_signal_func,
NULL, NULL);
g_source_attach (bus_source, data->context);
g_source_unref (bus_source);
g_signal_connect (G_OBJECT (bus), "message::error", (GCallback) error_cb,
data);
g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback) eos_cb, data);
g_signal_connect (G_OBJECT (bus), "message::state-changed",
(GCallback) state_changed_cb, data);
g_signal_connect (G_OBJECT (bus), "message::duration",
(GCallback) duration_cb, data);
g_signal_connect (G_OBJECT (bus), "message::buffering",
(GCallback) buffering_cb, data);
g_signal_connect (G_OBJECT (bus), "message::clock-lost",
(GCallback) clock_lost_cb, data);
gst_object_unref (bus);
/* Register a function that GLib will call 4 times per second */
timeout_source = g_timeout_source_new (250);
g_source_set_callback (timeout_source, (GSourceFunc) refresh_ui, data, NULL);
g_source_attach (timeout_source, data->context);
g_source_unref (timeout_source);
/* Create a GLib Main Loop and set it to run */
GST_DEBUG ("Entering main loop... (CustomData:%p)", data);
data->main_loop = g_main_loop_new (data->context, FALSE);
check_initialization_complete (data);
g_main_loop_run (data->main_loop);
GST_DEBUG ("Exited main loop");
g_main_loop_unref (data->main_loop);
data->main_loop = NULL;
/* Free resources */
g_main_context_pop_thread_default (data->context);
g_main_context_unref (data->context);
data->target_state = GST_STATE_NULL;
gst_element_set_state (data->pipeline, GST_STATE_NULL);
gst_object_unref (data->pipeline);
return NULL;
}
/*
* Java Bindings
*/
/* Instruct the native code to create its internal data structure, pipeline and thread */
static void
gst_native_init (JNIEnv * env, jobject thiz)
{
CustomData *data = g_new0 (CustomData, 1);
data->desired_position = GST_CLOCK_TIME_NONE;
data->last_seek_time = GST_CLOCK_TIME_NONE;
SET_CUSTOM_DATA (env, thiz, custom_data_field_id, data);
GST_DEBUG_CATEGORY_INIT (debug_category, "tutorial-5", 0,
"Android tutorial 5");
gst_debug_set_threshold_for_name ("tutorial-5", GST_LEVEL_DEBUG);
GST_DEBUG ("Created CustomData at %p", data);
data->app = (*env)->NewGlobalRef (env, thiz);
GST_DEBUG ("Created GlobalRef for app object at %p", data->app);
pthread_create (&gst_app_thread, NULL, &app_function, data);
}
/* Quit the main loop, remove the native thread and free resources */
static void
gst_native_finalize (JNIEnv * env, jobject thiz)
{
CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
if (!data)
return;
GST_DEBUG ("Quitting main loop...");
g_main_loop_quit (data->main_loop);
GST_DEBUG ("Waiting for thread to finish...");
pthread_join (gst_app_thread, NULL);
GST_DEBUG ("Deleting GlobalRef for app object at %p", data->app);
(*env)->DeleteGlobalRef (env, data->app);
GST_DEBUG ("Freeing CustomData at %p", data);
g_free (data);
SET_CUSTOM_DATA (env, thiz, custom_data_field_id, NULL);
GST_DEBUG ("Done finalizing");
}
/* Set playbin2's URI */
void
gst_native_set_uri (JNIEnv * env, jobject thiz, jstring uri)
{
CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
if (!data || !data->pipeline)
return;
const gchar *char_uri = (*env)->GetStringUTFChars (env, uri, NULL);
GST_DEBUG ("Setting URI to %s", char_uri);
if (data->target_state >= GST_STATE_READY)
gst_element_set_state (data->pipeline, GST_STATE_READY);
g_object_set (data->pipeline, "uri", char_uri, NULL);
(*env)->ReleaseStringUTFChars (env, uri, char_uri);
data->duration = GST_CLOCK_TIME_NONE;
data->is_live |=
(gst_element_set_state (data->pipeline,
data->target_state) == GST_STATE_CHANGE_NO_PREROLL);
}
/* Set pipeline to PLAYING state */
static void
gst_native_play (JNIEnv * env, jobject thiz)
{
CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
if (!data)
return;
GST_DEBUG ("Setting state to PLAYING");
data->target_state = GST_STATE_PLAYING;
data->is_live |=
(gst_element_set_state (data->pipeline,
GST_STATE_PLAYING) == GST_STATE_CHANGE_NO_PREROLL);
}
/* Set pipeline to PAUSED state */
static void
gst_native_pause (JNIEnv * env, jobject thiz)
{
CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
if (!data)
return;
GST_DEBUG ("Setting state to PAUSED");
data->target_state = GST_STATE_PAUSED;
data->is_live |=
(gst_element_set_state (data->pipeline,
GST_STATE_PAUSED) == GST_STATE_CHANGE_NO_PREROLL);
}
/* Instruct the pipeline to seek to a different position */
void
gst_native_set_position (JNIEnv * env, jobject thiz, int milliseconds)
{
CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
if (!data)
return;
gint64 desired_position = (gint64) (milliseconds * GST_MSECOND);
if (data->state >= GST_STATE_PAUSED) {
execute_seek (desired_position, data);
} else {
GST_DEBUG ("Scheduling seek to %" GST_TIME_FORMAT " for later",
GST_TIME_ARGS (desired_position));
data->desired_position = desired_position;
}
}
/* Static class initializer: retrieve method and field IDs */
static jboolean
gst_native_class_init (JNIEnv * env, jclass klass)
{
custom_data_field_id =
(*env)->GetFieldID (env, klass, "native_custom_data", "J");
set_message_method_id =
(*env)->GetMethodID (env, klass, "setMessage", "(Ljava/lang/String;)V");
set_current_position_method_id =
(*env)->GetMethodID (env, klass, "setCurrentPosition", "(II)V");
on_gstreamer_initialized_method_id =
(*env)->GetMethodID (env, klass, "onGStreamerInitialized", "()V");
on_media_size_changed_method_id =
(*env)->GetMethodID (env, klass, "onMediaSizeChanged", "(II)V");
if (!custom_data_field_id || !set_message_method_id
|| !on_gstreamer_initialized_method_id || !on_media_size_changed_method_id
|| !set_current_position_method_id) {
/* We emit this message through the Android log instead of the GStreamer log because the later
* has not been initialized yet.
*/
__android_log_print (ANDROID_LOG_ERROR, "tutorial-4",
"The calling class does not implement all necessary interface methods");
return JNI_FALSE;
}
return JNI_TRUE;
}
static void
gst_native_surface_init (JNIEnv * env, jobject thiz, jobject surface)
{
CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
if (!data)
return;
ANativeWindow *new_native_window = ANativeWindow_fromSurface (env, surface);
GST_DEBUG ("Received surface %p (native window %p)", surface,
new_native_window);
if (data->native_window) {
ANativeWindow_release (data->native_window);
if (data->native_window == new_native_window) {
GST_DEBUG ("New native window is the same as the previous one %p",
data->native_window);
if (data->pipeline) {
gst_video_overlay_expose (GST_VIDEO_OVERLAY (data->pipeline));
gst_video_overlay_expose (GST_VIDEO_OVERLAY (data->pipeline));
}
return;
} else {
GST_DEBUG ("Released previous native window %p", data->native_window);
data->initialized = FALSE;
}
}
data->native_window = new_native_window;
check_initialization_complete (data);
}
static void
gst_native_surface_finalize (JNIEnv * env, jobject thiz)
{
CustomData *data = GET_CUSTOM_DATA (env, thiz, custom_data_field_id);
if (!data)
return;
GST_DEBUG ("Releasing Native Window %p", data->native_window);
if (data->pipeline) {
gst_video_overlay_set_window_handle (GST_VIDEO_OVERLAY (data->pipeline),
(guintptr) NULL);
gst_element_set_state (data->pipeline, GST_STATE_READY);
}
ANativeWindow_release (data->native_window);
data->native_window = NULL;
data->initialized = FALSE;
}
/* List of implemented native methods */
static JNINativeMethod native_methods[] = {
{"nativeInit", "()V", (void *) gst_native_init},
{"nativeFinalize", "()V", (void *) gst_native_finalize},
{"nativeSetUri", "(Ljava/lang/String;)V", (void *) gst_native_set_uri},
{"nativePlay", "()V", (void *) gst_native_play},
{"nativePause", "()V", (void *) gst_native_pause},
{"nativeSetPosition", "(I)V", (void *) gst_native_set_position},
{"nativeSurfaceInit", "(Ljava/lang/Object;)V",
(void *) gst_native_surface_init},
{"nativeSurfaceFinalize", "()V", (void *) gst_native_surface_finalize},
{"nativeClassInit", "()Z", (void *) gst_native_class_init}
};
/* Library initializer */
jint
JNI_OnLoad (JavaVM * vm, void *reserved)
{
JNIEnv *env = NULL;
java_vm = vm;
if ((*vm)->GetEnv (vm, (void **) &env, JNI_VERSION_1_4) != JNI_OK) {
__android_log_print (ANDROID_LOG_ERROR, "tutorial-5",
"Could not retrieve JNIEnv");
return 0;
}
jclass klass = (*env)->FindClass (env,
"org/freedesktop/gstreamer/tutorials/tutorial_5/Tutorial5");
(*env)->RegisterNatives (env, klass, native_methods,
G_N_ELEMENTS (native_methods));
pthread_key_create (&current_jni_env, detach_current_thread);
return JNI_VERSION_1_4;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/fdLinearLayoutList"
android:orientation="vertical" >
<TextView
android:id="@+id/path"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/fdButtonCancel"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight=".3"
android:text="@string/button_cancel" />
<Button
android:id="@+id/fdButtonSelect"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight=".7"
android:text="@string/button_select" />
</LinearLayout>
</LinearLayout>
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/fdrowimage"
android:layout_width="wrap_content"
android:layout_height="36dp"
android:contentDescription="@string/icon" />
<TextView
android:id="@+id/fdrowtext"
android:layout_width="0dip"
android:layout_height="36dp"
android:layout_weight="1"
android:ellipsize="marquee"
android:gravity="center_vertical"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:textSize="23dp" />
</LinearLayout>
@@ -0,0 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="@+id/textview_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dip"
android:gravity="center_horizontal" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dip"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ImageButton
android:id="@+id/button_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/button_play"
android:src="@android:drawable/ic_media_play"
android:text="@string/button_play" />
<ImageButton
android:id="@+id/button_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/button_stop"
android:src="@android:drawable/ic_media_pause"
android:text="@string/button_stop" />
<ImageButton
android:id="@+id/button_select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/button_select"
android:src="@android:drawable/ic_media_next"
android:text="@string/button_select" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dip"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<TextView
android:id="@+id/textview_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip" />
<SeekBar
android:id="@+id/seek_bar"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:indeterminate="false" />
</LinearLayout>
<org.freedesktop.gstreamer.tutorials.tutorial_5.GStreamerSurfaceView
android:id="@+id/surface_video"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
</LinearLayout>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">GStreamer tutorial 5</string>
<string name="button_play">Play</string>
<string name="button_stop">Stop</string>
<string name="button_select">Select</string>
<string name="button_cancel">Cancel</string>
<string name="filechooser_name">Select a file</string>
<string name="location">Location</string>
<string name="cant_read_folder">folder cannot be read</string>
<string name="icon">Icon</string>
</resources>
@@ -0,0 +1,334 @@
// Based on http://code.google.com/p/android-file-dialog/
//
// Copyright (c) 2011, 2012, Alexander Ponomarev <alexander.ponomarev.1@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer. Redistributions in binary form must
// reproduce the above copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of the <ORGANIZATION> nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
package com.lamerman;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.freedesktop.gstreamer.tutorials.tutorial_5.R;
/**
* Activity para escolha de arquivos/diretorios.
*
* @author android
*
*/
public class FileDialog extends ListActivity {
/**
* Chave de um item da lista de paths.
*/
private static final String ITEM_KEY = "key";
/**
* Imagem de um item da lista de paths (diretorio ou arquivo).
*/
private static final String ITEM_IMAGE = "image";
/**
* Diretorio raiz.
*/
private static final String ROOT = "/";
/**
* Parametro de entrada da Activity: path inicial. Padrao: ROOT.
*/
public static final String START_PATH = "START_PATH";
/**
* Parametro de entrada da Activity: filtro de formatos de arquivos. Padrao:
* null.
*/
public static final String FORMAT_FILTER = "FORMAT_FILTER";
/**
* Parametro de saida da Activity: path escolhido. Padrao: null.
*/
public static final String RESULT_PATH = "RESULT_PATH";
private List<String> path = null;
private TextView myPath;
private ArrayList<HashMap<String, Object>> mList;
private Button selectButton;
private String parentPath;
private String currentPath = ROOT;
private String[] formatFilter = null;
private File selectedFile;
private HashMap<String, Integer> lastPositions = new HashMap<String, Integer>();
/**
* Called when the activity is first created. Configura todos os parametros
* de entrada e das VIEWS..
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setResult(RESULT_CANCELED, getIntent());
setContentView(R.layout.file_dialog_main);
myPath = (TextView) findViewById(R.id.path);
selectButton = (Button) findViewById(R.id.fdButtonSelect);
selectButton.setEnabled(false);
selectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (selectedFile != null) {
getIntent().putExtra(RESULT_PATH, selectedFile.getPath());
setResult(RESULT_OK, getIntent());
finish();
}
}
});
formatFilter = getIntent().getStringArrayExtra(FORMAT_FILTER);
final Button cancelButton = (Button) findViewById(R.id.fdButtonCancel);
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_CANCELED);
finish();
}
});
String startPath;
if (savedInstanceState != null) {
startPath = savedInstanceState.getString("currentPath");
} else {
startPath = getIntent().getStringExtra(START_PATH);
}
startPath = startPath != null ? startPath : ROOT;
getDir(startPath);
ListView lv = (ListView) findViewById(android.R.id.list);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
private void getDir(String dirPath) {
boolean useAutoSelection = dirPath.length() < currentPath.length();
Integer position = lastPositions.get(parentPath);
getDirImpl(dirPath);
if (position != null && useAutoSelection) {
getListView().setSelection(position);
}
}
/**
* Monta a estrutura de arquivos e diretorios filhos do diretorio fornecido.
*
* @param dirPath
* Diretorio pai.
*/
private void getDirImpl(final String dirPath) {
currentPath = dirPath;
final List<String> item = new ArrayList<String>();
path = new ArrayList<String>();
mList = new ArrayList<HashMap<String, Object>>();
File f = new File(currentPath);
File[] files = f.listFiles();
if (files == null) {
currentPath = ROOT;
f = new File(currentPath);
files = f.listFiles();
}
myPath.setText(getText(R.string.location) + ": " + currentPath);
if (!currentPath.equals(ROOT)) {
item.add(ROOT);
addItem(ROOT, R.drawable.folder);
path.add(ROOT);
item.add("../");
addItem("../", R.drawable.folder);
path.add(f.getParent());
parentPath = f.getParent();
}
TreeMap<String, String> dirsMap = new TreeMap<String, String>();
TreeMap<String, String> dirsPathMap = new TreeMap<String, String>();
TreeMap<String, String> filesMap = new TreeMap<String, String>();
TreeMap<String, String> filesPathMap = new TreeMap<String, String>();
for (File file : files) {
if (file.isDirectory()) {
String dirName = file.getName();
dirsMap.put(dirName, dirName);
dirsPathMap.put(dirName, file.getPath());
} else {
final String fileName = file.getName();
final String fileNameLwr = fileName.toLowerCase();
// se ha um filtro de formatos, utiliza-o
if (formatFilter != null) {
boolean contains = false;
for (int i = 0; i < formatFilter.length; i++) {
final String formatLwr = formatFilter[i].toLowerCase();
if (fileNameLwr.endsWith(formatLwr)) {
contains = true;
break;
}
}
if (contains) {
filesMap.put(fileName, fileName);
filesPathMap.put(fileName, file.getPath());
}
// senao, adiciona todos os arquivos
} else {
filesMap.put(fileName, fileName);
filesPathMap.put(fileName, file.getPath());
}
}
}
item.addAll(dirsMap.tailMap("").values());
item.addAll(filesMap.tailMap("").values());
path.addAll(dirsPathMap.tailMap("").values());
path.addAll(filesPathMap.tailMap("").values());
SimpleAdapter fileList = new SimpleAdapter(this, mList,
R.layout.file_dialog_row,
new String[] { ITEM_KEY, ITEM_IMAGE }, new int[] {
R.id.fdrowtext, R.id.fdrowimage });
for (String dir : dirsMap.tailMap("").values()) {
addItem(dir, R.drawable.folder);
}
for (String file : filesMap.tailMap("").values()) {
addItem(file, R.drawable.file);
}
fileList.notifyDataSetChanged();
setListAdapter(fileList);
}
private void addItem(String fileName, int imageId) {
HashMap<String, Object> item = new HashMap<String, Object>();
item.put(ITEM_KEY, fileName);
item.put(ITEM_IMAGE, imageId);
mList.add(item);
}
/**
* Quando clica no item da lista, deve-se: 1) Se for diretorio, abre seus
* arquivos filhos; 2) Se puder escolher diretorio, define-o como sendo o
* path escolhido. 3) Se for arquivo, define-o como path escolhido. 4) Ativa
* botao de selecao.
*/
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory()) {
selectButton.setEnabled(false);
if (file.canRead()) {
lastPositions.put(currentPath, position);
getDir(path.get(position));
} else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.stat_sys_warning)
.setTitle(
"[" + file.getName() + "] "
+ getText(R.string.cant_read_folder))
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
} else {
if (selectedFile != null
&& selectedFile.getPath().equals(file.getPath())) {
getIntent().putExtra(RESULT_PATH, selectedFile.getPath());
setResult(RESULT_OK, getIntent());
finish();
}
selectedFile = file;
l.setItemChecked(position, true);
selectButton.setEnabled(true);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
selectButton.setEnabled(false);
if (!currentPath.equals(ROOT)) {
getDir(parentPath);
} else {
return super.onKeyDown(keyCode, event);
}
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("currentPath", currentPath);
super.onSaveInstanceState(outState);
}
}