commit 49c51cce5def305c549dca8fe02852f433e9f1a1 Author: Chenglin.Ye Date: Fri Jul 21 19:06:00 2017 +0800 some sample with gstreamer diff --git a/MusicPlayer/Makefile b/MusicPlayer/Makefile new file mode 100644 index 0000000..984a85e --- /dev/null +++ b/MusicPlayer/Makefile @@ -0,0 +1,5 @@ +all: + gcc mplayer.c -o mplayer `pkg-config --cflags --libs gstreamer-1.0` + +clean: + rm -f mplayer diff --git a/MusicPlayer/mplayer.c b/MusicPlayer/mplayer.c new file mode 100644 index 0000000..06f2137 --- /dev/null +++ b/MusicPlayer/mplayer.c @@ -0,0 +1,248 @@ +#include +#include + +typedef struct _MusicPlayer { + GstElement *Mpipeline; + GstElement *Msource; + GstElement *Mconvert; + GstElement *Msink; + GstBus *Mbus; + GMainLoop *Mloop; + gboolean Malive; /* Whether playing status. */ + gint64 Mduration; /* Music duration time. */ + gdouble Mrate; /* Playing speed. */ + gint64 Mcurrent; /* Current position. */ + GstState Mstate; /* Playing state. */ +} MusicPlayer; + +static void send_seek_event(MusicPlayer *Mdata) { + GstEvent *seek_event; + + /* Create the seek event */ + if(Mdata->Mrate > 0) { + seek_event = gst_event_new_seek(Mdata->Mrate, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | + GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, Mdata->Mcurrent, GST_SEEK_TYPE_NONE, 0); + } + else { + seek_event = gst_event_new_seek(Mdata->Mrate, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | + GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_SET, Mdata->Mcurrent); + } + + if(Mdata->Msink == NULL) { + /* If we have not done so, obtain the sink through which we will send the seek events */ + g_object_get(Mdata->Mpipeline, "music-sink", &Mdata->Msink, NULL); + } + + /* Send the event */ + gst_element_send_event(Mdata->Msink, seek_event); + + g_print(" Rate: %0.1f\n", Mdata->Mrate); + + return ; +} + +static void pad_added_handler(GstElement *src, GstPad *new_pad, MusicPlayer *Mdata) { + GstPadLinkReturn ret; + GstCaps *new_pad_caps = NULL; + GstStructure *new_pad_struct = NULL; + const gchar *new_pad_type = NULL; + guint caps_size; + + /* Get music-convert element sink pad. */ + GstPad *sink_pad = gst_element_get_static_pad(Mdata->Mconvert, "sink"); + if(gst_pad_is_linked(sink_pad)) { + g_print(" We are already linked. Ignoring.\n"); + goto exit; + } + + new_pad_caps = gst_pad_query_caps(new_pad, NULL); + new_pad_struct = gst_caps_get_structure(new_pad_caps, 0); + caps_size = gst_caps_get_size(new_pad_caps); + new_pad_type = gst_structure_get_name(new_pad_struct); + if(!g_str_has_prefix(new_pad_type, "audio/x-raw")) { + g_print(" It has type '%s' which is not raw audio. Ignoring.\n", new_pad_type); + goto exit; + } + + /* Link "music-source" to "music-convert". */ + ret = gst_pad_link(new_pad, sink_pad); + if(GST_PAD_LINK_FAILED(ret)) { + g_printerr("Error: link pad '%s' to '%s' failed.\n", + GST_PAD_NAME(new_pad), GST_PAD_NAME(sink_pad)); + g_main_loop_quit(Mdata->Mloop); + } + else { + g_print(" Type: %s\n", new_pad_type); + g_print(" Size: %d\n", caps_size); + g_print(" Rate: 1.0\n"); + } + + if(!gst_element_query_duration(Mdata->Msink, GST_FORMAT_TIME, &Mdata->Mduration)) + g_printerr("Could'nt query duration.\n"); + else + g_print(" Duration: %" GST_TIME_FORMAT "\n", GST_TIME_ARGS(Mdata->Mduration)); + + return ; + +exit: + if(new_pad_caps != NULL) + gst_caps_unref(new_pad_caps); + gst_object_unref(sink_pad); +} + +static void message_handler(GstBus *bus, GstMessage *msg, MusicPlayer *Mdata) { + switch(GST_MESSAGE_TYPE(msg)) { + case GST_MESSAGE_ERROR: { + GError *err; + gchar *debug; + + gst_message_parse_error(msg, &err, &debug); + g_printerr("Error: %s\n", err->message); + g_error_free(err); + g_free(debug); + + gst_element_set_state(Mdata->Mpipeline, GST_STATE_READY); + Mdata->Malive = FALSE; + g_print(" Status: %s > READY\n", gst_element_state_get_name(Mdata->Mstate)); + g_main_loop_quit(Mdata->Mloop); + break; + } + case GST_MESSAGE_EOS: { + gst_element_set_state(Mdata->Mpipeline, GST_STATE_READY); + Mdata->Malive = FALSE; + g_print(" Status: %s > READY\n", gst_element_state_get_name(Mdata->Mstate)); + g_main_loop_quit(Mdata->Mloop); + break; + } + case GST_MESSAGE_STATE_CHANGED: { + if(GST_MESSAGE_SRC(msg) == GST_OBJECT(Mdata->Msink)) { + GstState old_state, new_state, pending_state; + + gst_message_parse_state_changed(msg, &old_state, &new_state, &pending_state); + Mdata->Malive = (new_state == GST_STATE_PLAYING); + if(old_state == GST_STATE_PLAYING) + g_print("\n"); + Mdata->Mstate = new_state; + g_print(" Status: %s > %s\n", gst_element_state_get_name(old_state), + gst_element_state_get_name(new_state)); + } + } + } + + return ; +} + +static gboolean refresh_handler(MusicPlayer *Mdata) { + static gboolean flag = FALSE; + + if(!Mdata->Malive) + return TRUE; + + /* Get current position. */ + if(!gst_element_query_position(Mdata->Msource, GST_FORMAT_TIME, &Mdata->Mcurrent)) { + g_printerr("Could'nt query current position.\n"); + } + + if(Mdata->Mcurrent < Mdata->Mduration) { + g_print(" Position: %" GST_TIME_FORMAT "\r", GST_TIME_ARGS(Mdata->Mcurrent)); + } + else { + g_print("\n"); + return FALSE; + } + + if(Mdata->Mcurrent > (Mdata->Mduration / 6) && Mdata->Mcurrent < (Mdata->Mduration/3)) { + gst_element_seek_simple(Mdata->Msink, GST_FORMAT_TIME, + GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, Mdata->Mduration / 3); + g_print("\n"); + flag = TRUE; + } + + if(Mdata->Mcurrent > (Mdata->Mduration / 2) && flag) { + g_print("\n"); + flag = FALSE; + Mdata->Mrate = 2.0; + send_seek_event(Mdata); + } + + return TRUE; +} + +int main(int argc, char *argv[]) { + MusicPlayer Mdata; + GstStateChangeReturn ret; + + if(argc < 2) { + g_print("Usage: %s '(uri)resource'.\n", argv[0]); + return -1; + } + + /* Initialization. */ + gst_init(&argc, &argv); + memset(&Mdata, 0, sizeof(Mdata)); + Mdata.Malive = FALSE; + Mdata.Mrate = 1.0; + Mdata.Mstate = GST_STATE_NULL; + + /* Create element and pipeline. */ + Mdata.Msource = gst_element_factory_make("uridecodebin", "music-source"); + Mdata.Mconvert = gst_element_factory_make("audioconvert", "music-convert"); + Mdata.Msink = gst_element_factory_make("autoaudiosink", "music-sink"); + Mdata.Mpipeline = gst_pipeline_new("music-pipeline"); + + if(!Mdata.Mpipeline || !Mdata.Msource || !Mdata.Mconvert || !Mdata.Msink) { + g_printerr("One or more elements could'nt be created.\n"); + return -1; + } + + /* Add all element into bin. */ + gst_bin_add_many(GST_BIN(Mdata.Mpipeline), Mdata.Msource, Mdata.Mconvert, Mdata.Msink, NULL); + /* Link 'music-convert' to 'music-sink'. */ + if(!gst_element_link(Mdata.Mconvert, Mdata.Msink)) { + g_printerr("'music-convert' could'nt link with 'music-sink\n'"); + gst_object_unref(Mdata.Mpipeline); + return -1; + } + + /* Set the uri to play. */ + g_object_set(Mdata.Msource, "uri", argv[1], NULL); + + /* Handler event of "pad-added". */ + g_signal_connect(Mdata.Msource, "pad-added", G_CALLBACK(pad_added_handler), &Mdata); + + /* Set playing state. Start playing. */ + ret = gst_element_set_state(Mdata.Mpipeline, GST_STATE_PLAYING); + if(ret == GST_STATE_CHANGE_FAILURE) { + g_printerr("Unable to set pipeline to the playing state.\n"); + gst_object_unref(Mdata.Mpipeline); + return -1; + } + + /* Listen to the bus. */ + Mdata.Mbus = gst_element_get_bus(Mdata.Mpipeline); + gst_bus_add_signal_watch(Mdata.Mbus); + + /* Handler 'message' signal. */ + g_signal_connect(Mdata.Mbus, "message", G_CALLBACK(message_handler), &Mdata); + + /* Main loop. */ + Mdata.Mloop = g_main_loop_new(NULL, FALSE); + + g_print("Runing...\n"); + g_print("\n"); + g_print("Information\n"); + + g_timeout_add(1, (GSourceFunc)refresh_handler, &Mdata); + g_main_loop_run(Mdata.Mloop); + + /* Free resources. */ + g_main_loop_unref(Mdata.Mloop); + gst_element_set_state(Mdata.Mpipeline, GST_STATE_NULL); + gst_object_unref(Mdata.Mbus); + gst_object_unref(Mdata.Mpipeline); + + g_print("\n"); + g_print("Ending...\n"); + + return 0; +} diff --git a/README b/README new file mode 100644 index 0000000..dc720e3 --- /dev/null +++ b/README @@ -0,0 +1,4 @@ + +---- + Some sample with gstreamer. +---- diff --git a/RecordCamera/Makefile b/RecordCamera/Makefile new file mode 100644 index 0000000..34faf08 --- /dev/null +++ b/RecordCamera/Makefile @@ -0,0 +1,5 @@ +all: + gcc record.c -o record `pkg-config --cflags --libs gstreamer-1.0` + +clean: + rm -f record diff --git a/RecordCamera/record.c b/RecordCamera/record.c new file mode 100644 index 0000000..8d61e31 --- /dev/null +++ b/RecordCamera/record.c @@ -0,0 +1,85 @@ +#include +#include + +typedef struct _RecordCamera { + GstElement *Rpipeline; + GstElement *Raudiosource; + GstElement *Rvideosource; + GstElement *Raudioenc; + GstElement *Rvideoenc; + GstElement *Rmux; + GstElement *Rqueue; + GstElement *Rsink; + GstBus *Rbus; + GMainLoop *Rloop; + GstState Rstate; + gint64 Rcurrent; +} RecordCamera; + +static gboolean refresh_handler(RecordCamera *Rdata) { + if(!Rdata->Rstate == GST_STATE_PLAYING) + return TRUE; + + if(!gst_element_query_position(Rdata->Rvideosource, GST_FORMAT_TIME, &Rdata->Rcurrent)) { + g_printerr("Error: could not query current position.\n"); + } + + g_print("Duration: %" GST_TIME_FORMAT "\r", GST_TIME_ARGS(Rdata->Rcurrent)); + + return TRUE; +} + +int main(int argc, char *argv[]) { + RecordCamera Rdata; + GstStateChangeReturn ret; + + gst_init(&argc, &argv); + memset(&Rdata, 0, sizeof(Rdata)); + Rdata.Rstate = GST_STATE_NULL; + + Rdata.Raudiosource = gst_element_factory_make("alsasrc", "audio-source"); + Rdata.Rvideosource = gst_element_factory_make("v4l2src", "video-source"); + Rdata.Raudioenc = gst_element_factory_make("voaacenc", "audio-enc"); + Rdata.Rvideoenc = gst_element_factory_make("jpegenc", "video-enc"); + Rdata.Rqueue = gst_element_factory_make("queue", "audio-queue"); + Rdata.Rmux = gst_element_factory_make("avimux", "record-mux"); + Rdata.Rsink = gst_element_factory_make("filesink", "record-sink"); + Rdata.Rpipeline = gst_pipeline_new("record-pipeline"); + + if(!Rdata.Rpipeline || !Rdata.Raudiosource || !Rdata.Rvideosource || !Rdata.Rqueue || + !Rdata.Raudioenc || !Rdata.Rvideoenc || !Rdata.Rmux || !Rdata.Rsink) { + g_printerr("Error: One or more element could't be created.\n"); + return -1; + } + + gst_bin_add_many(GST_BIN(Rdata.Rpipeline), Rdata.Rvideosource, Rdata.Raudiosource, + Rdata.Rqueue, Rdata.Raudioenc, Rdata.Rvideoenc, Rdata.Rmux, Rdata.Rsink, NULL); + if(!gst_element_link_many(Rdata.Raudiosource, Rdata.Raudioenc, Rdata.Rqueue, Rdata.Rmux, NULL)) { + g_printerr("Error(audio): Element could't be lined.\n"); + return -1; + } + if(!gst_element_link_many(Rdata.Rvideosource, Rdata.Rvideoenc, Rdata.Rmux, Rdata.Rsink, NULL)) { + g_printerr("Error(video): Element could't be lined.\n"); + return -1; + } + + g_object_set(Rdata.Rsink, "location", argv[1], NULL); + g_object_set(Rdata.Raudiosource, "device", "hw:1,0", NULL); + g_object_set(Rdata.Rvideosource, "device", "/dev/video0", NULL); + + ret = gst_element_set_state(Rdata.Rpipeline, GST_STATE_PLAYING); + + Rdata.Rloop = g_main_loop_new(NULL, FALSE); + + g_print("Recording...\n"); + g_print("\n"); + + g_timeout_add(1, (GSourceFunc)refresh_handler, &Rdata); + g_main_loop_run(Rdata.Rloop); + + g_main_loop_unref(Rdata.Rloop); + gst_element_set_state(Rdata.Rpipeline, GST_STATE_NULL); + gst_object_unref(Rdata.Rpipeline); + + return 0; +} diff --git a/playback/4/Makefile b/playback/4/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/playback/4/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/playback/4/network.c b/playback/4/network.c new file mode 100644 index 0000000..e44ed92 --- /dev/null +++ b/playback/4/network.c @@ -0,0 +1,172 @@ +#include +#include + +#define GRAPH_LENGTH 78 + +/* playbin flags */ +typedef enum { + GST_PLAY_FLAG_DOWNLOAD = (1 << 7) /* Enable progressive download (on selected formats) */ +} GstPlayFlags; + +typedef struct _CustomData { + gboolean is_live; + GstElement *pipeline; + GMainLoop *loop; + gint buffering_level; +} CustomData; + +static void got_location (GstObject *gstobject, GstObject *prop_object, GParamSpec *prop, gpointer data) { + gchar *location; + g_object_get (G_OBJECT (prop_object), "temp-location", &location, NULL); + g_print ("Temporary file: %s\n", location); + g_free (location); + /* Uncomment this line to keep the temporary file after the program exits */ + /* g_object_set (G_OBJECT (prop_object), "temp-remove", FALSE, NULL); */ +} + +static void cb_message (GstBus *bus, GstMessage *msg, CustomData *data) { + + switch (GST_MESSAGE_TYPE (msg)) { + case GST_MESSAGE_ERROR: { + GError *err; + gchar *debug; + + gst_message_parse_error (msg, &err, &debug); + g_print ("Error: %s\n", err->message); + g_error_free (err); + g_free (debug); + + gst_element_set_state (data->pipeline, GST_STATE_READY); + g_main_loop_quit (data->loop); + break; + } + case GST_MESSAGE_EOS: + /* end-of-stream */ + gst_element_set_state (data->pipeline, GST_STATE_READY); + g_main_loop_quit (data->loop); + break; + case GST_MESSAGE_BUFFERING: + /* If the stream is live, we do not care about buffering. */ + if (data->is_live) break; + + gst_message_parse_buffering (msg, &data->buffering_level); + + /* Wait until buffering is complete before start/resume playing */ + if (data->buffering_level < 100) + gst_element_set_state (data->pipeline, GST_STATE_PAUSED); + else + gst_element_set_state (data->pipeline, GST_STATE_PLAYING); + break; + case GST_MESSAGE_CLOCK_LOST: + /* Get a new clock */ + gst_element_set_state (data->pipeline, GST_STATE_PAUSED); + gst_element_set_state (data->pipeline, GST_STATE_PLAYING); + break; + default: + /* Unhandled message */ + break; + } +} + +static gboolean refresh_ui (CustomData *data) { + GstQuery *query; + gboolean result; + + query = gst_query_new_buffering (GST_FORMAT_PERCENT); + result = gst_element_query (data->pipeline, query); + if (result) { + gint n_ranges, range, i; + gchar graph[GRAPH_LENGTH + 1]; + gint64 position = 0, duration = 0; + + memset (graph, ' ', GRAPH_LENGTH); + graph[GRAPH_LENGTH] = '\0'; + + n_ranges = gst_query_get_n_buffering_ranges (query); + for (range = 0; range < n_ranges; range++) { + gint64 start, stop; + gst_query_parse_nth_buffering_range (query, range, &start, &stop); + start = start * GRAPH_LENGTH / (stop - start); + stop = stop * GRAPH_LENGTH / (stop - start); + for (i = (gint)start; i < stop; i++) + graph [i] = '-'; + } + if (gst_element_query_position (data->pipeline, GST_FORMAT_TIME, &position) && + GST_CLOCK_TIME_IS_VALID (position) && + gst_element_query_duration (data->pipeline, GST_FORMAT_TIME, &duration) && + GST_CLOCK_TIME_IS_VALID (duration)) { + i = (gint)(GRAPH_LENGTH * (double)position / (double)(duration + 1)); + graph [i] = data->buffering_level < 100 ? 'X' : '>'; + } + g_print ("[%s]", graph); + if (data->buffering_level < 100) { + g_print (" Buffering: %3d%%", data->buffering_level); + } else { + g_print (" "); + } + g_print ("\r"); + } + + return TRUE; + +} + +int main(int argc, char *argv[]) { + GstElement *pipeline; + GstBus *bus; + GstStateChangeReturn ret; + GMainLoop *main_loop; + CustomData data; + guint flags; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Initialize our data structure */ + memset (&data, 0, sizeof (data)); + data.buffering_level = 100; + + /* Build the pipeline */ + pipeline = gst_parse_launch ("playbin uri=file:///home/ye/Music/1.wav", NULL); + bus = gst_element_get_bus (pipeline); + + /* Set the download flag */ + g_object_get (pipeline, "flags", &flags, NULL); + flags |= GST_PLAY_FLAG_DOWNLOAD; + g_object_set (pipeline, "flags", flags, NULL); + + /* Uncomment this line to limit the amount of downloaded data */ + /* g_object_set (pipeline, "ring-buffer-max-size", (guint64)4000000, NULL); */ + + /* Start playing */ + ret = gst_element_set_state (pipeline, GST_STATE_PLAYING); + if (ret == GST_STATE_CHANGE_FAILURE) { + g_printerr ("Unable to set the pipeline to the playing state.\n"); + gst_object_unref (pipeline); + return -1; + } else if (ret == GST_STATE_CHANGE_NO_PREROLL) { + data.is_live = TRUE; + } + + main_loop = g_main_loop_new (NULL, FALSE); + data.loop = main_loop; + data.pipeline = pipeline; + + gst_bus_add_signal_watch (bus); + g_signal_connect (bus, "message", G_CALLBACK (cb_message), &data); + g_signal_connect (pipeline, "deep-notify::temp-location", G_CALLBACK (got_location), NULL); + + /* Register a function that GLib will call every second */ + g_timeout_add_seconds (1, (GSourceFunc)refresh_ui, &data); + + g_main_loop_run (main_loop); + + /* Free resources */ + g_main_loop_unref (main_loop); + gst_object_unref (bus); + gst_element_set_state (pipeline, GST_STATE_NULL); + gst_object_unref (pipeline); + g_print ("\n"); + return 0; +} + diff --git a/playback/5/Makefile b/playback/5/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/playback/5/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/playback/5/color.c b/playback/5/color.c new file mode 100644 index 0000000..4c32635 --- /dev/null +++ b/playback/5/color.c @@ -0,0 +1,147 @@ +#include +#include +#include +#include + +typedef struct _CustomData { + GstElement *pipeline; + GMainLoop *loop; +} CustomData; + +/* Process a color balance command */ +static void update_color_channel (const gchar *channel_name, gboolean increase, GstColorBalance *cb) { + gdouble step; + gint value; + GstColorBalanceChannel *channel = NULL; + const GList *channels, *l; + + /* Retrieve the list of channels and locate the requested one */ + channels = gst_color_balance_list_channels (cb); + for (l = channels; l != NULL; l = l->next) { + GstColorBalanceChannel *tmp = (GstColorBalanceChannel *)l->data; + + if (g_strrstr (tmp->label, channel_name)) { + channel = tmp; + break; + } + } + if (!channel) + return; + + /* Change the channel's value */ + step = 0.1 * (channel->max_value - channel->min_value); + value = gst_color_balance_get_value (cb, channel); + if (increase) { + value = (gint)(value + step); + if (value > channel->max_value) + value = channel->max_value; + } else { + value = (gint)(value - step); + if (value < channel->min_value) + value = channel->min_value; + } + gst_color_balance_set_value (cb, channel, value); +} + +/* Output the current values of all Color Balance channels */ +static void print_current_values (GstElement *pipeline) { + const GList *channels, *l; + + /* Output Color Balance values */ + channels = gst_color_balance_list_channels (GST_COLOR_BALANCE (pipeline)); + for (l = channels; l != NULL; l = l->next) { + GstColorBalanceChannel *channel = (GstColorBalanceChannel *)l->data; + gint value = gst_color_balance_get_value (GST_COLOR_BALANCE (pipeline), channel); + g_print ("%s: %3d%% ", channel->label, + 100 * (value - channel->min_value) / (channel->max_value - channel->min_value)); + } + g_print ("\n"); +} + +/* Process keyboard input */ +static gboolean handle_keyboard (GIOChannel *source, GIOCondition cond, CustomData *data) { + gchar *str = NULL; + + if (g_io_channel_read_line (source, &str, NULL, NULL, NULL) != G_IO_STATUS_NORMAL) { + return TRUE; + } + + switch (g_ascii_tolower (str[0])) { + case 'c': + update_color_channel ("CONTRAST", g_ascii_isupper (str[0]), GST_COLOR_BALANCE (data->pipeline)); + break; + case 'b': + update_color_channel ("BRIGHTNESS", g_ascii_isupper (str[0]), GST_COLOR_BALANCE (data->pipeline)); + break; + case 'h': + update_color_channel ("HUE", g_ascii_isupper (str[0]), GST_COLOR_BALANCE (data->pipeline)); + break; + case 's': + update_color_channel ("SATURATION", g_ascii_isupper (str[0]), GST_COLOR_BALANCE (data->pipeline)); + break; + case 'q': + g_main_loop_quit (data->loop); + break; + default: + break; + } + + g_free (str); + + print_current_values (data->pipeline); + + return TRUE; +} + +int main(int argc, char *argv[]) { + CustomData data; + GstStateChangeReturn ret; + GIOChannel *io_stdin; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Initialize our data structure */ + memset (&data, 0, sizeof (data)); + + /* Print usage map */ + g_print ( + "USAGE: Choose one of the following options, then press enter:\n" + " 'C' to increase contrast, 'c' to decrease contrast\n" + " 'B' to increase brightness, 'b' to decrease brightness\n" + " 'H' to increase hue, 'h' to decrease hue\n" + " 'S' to increase saturation, 's' to decrease saturation\n" + " 'Q' to quit\n"); + + /* Build the pipeline */ + data.pipeline = gst_parse_launch ("playbin uri=file:///home/ye/Music/1.wav", NULL); + + /* Add a keyboard watch so we get notified of keystrokes */ +#ifdef G_OS_WIN32 + io_stdin = g_io_channel_win32_new_fd (fileno (stdin)); +#else + io_stdin = g_io_channel_unix_new (fileno (stdin)); +#endif + g_io_add_watch (io_stdin, G_IO_IN, (GIOFunc)handle_keyboard, &data); + + /* Start playing */ + ret = gst_element_set_state (data.pipeline, GST_STATE_PLAYING); + if (ret == GST_STATE_CHANGE_FAILURE) { + g_printerr ("Unable to set the pipeline to the playing state.\n"); + gst_object_unref (data.pipeline); + return -1; + } + print_current_values (data.pipeline); + + /* Create a GLib Main Loop and set it to run */ + data.loop = g_main_loop_new (NULL, FALSE); + g_main_loop_run (data.loop); + + /* Free resources */ + g_main_loop_unref (data.loop); + g_io_channel_unref (io_stdin); + gst_element_set_state (data.pipeline, GST_STATE_NULL); + gst_object_unref (data.pipeline); + return 0; +} + diff --git a/playback/6/Makefile b/playback/6/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/playback/6/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/playback/6/audio.c b/playback/6/audio.c new file mode 100644 index 0000000..6c2d763 --- /dev/null +++ b/playback/6/audio.c @@ -0,0 +1,90 @@ +#include + +/* playbin flags */ +typedef enum { + GST_PLAY_FLAG_VIS = (1 << 3) /* Enable rendering of visualizations when there is no video stream. */ +} GstPlayFlags; + +/* Return TRUE if this is a Visualization element */ +static gboolean filter_vis_features (GstPluginFeature *feature, gpointer data) { + GstElementFactory *factory; + + if (!GST_IS_ELEMENT_FACTORY (feature)) + return FALSE; + factory = GST_ELEMENT_FACTORY (feature); + if (!g_strrstr (gst_element_factory_get_klass (factory), "Visualization")) + return FALSE; + + return TRUE; +} + +int main(int argc, char *argv[]) { + GstElement *pipeline, *vis_plugin; + GstBus *bus; + GstMessage *msg; + GList *list, *walk; + GstElementFactory *selected_factory = NULL; + guint flags; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Get a list of all visualization plugins */ + list = gst_registry_feature_filter (gst_registry_get (), filter_vis_features, FALSE, NULL); + + /* Print their names */ + g_print("Available visualization plugins:\n"); + for (walk = list; walk != NULL; walk = g_list_next (walk)) { + const gchar *name; + GstElementFactory *factory; + + factory = GST_ELEMENT_FACTORY (walk->data); + name = gst_element_factory_get_longname (factory); + g_print(" %s\n", name); + + if (selected_factory == NULL || g_str_has_prefix (name, "GOOM")) { + selected_factory = factory; + } + } + + /* Don't use the factory if it's still empty */ + /* e.g. no visualization plugins found */ + if (!selected_factory) { + g_print ("No visualization plugins found!\n"); + return -1; + } + + /* We have now selected a factory for the visualization element */ + g_print ("Selected '%s'\n", gst_element_factory_get_longname (selected_factory)); + vis_plugin = gst_element_factory_create (selected_factory, NULL); + if (!vis_plugin) + return -1; + + /* Build the pipeline */ + pipeline = gst_parse_launch ("playbin uri=file:///home/ye/Music/1.wav", NULL); + + /* Set the visualization flag */ + g_object_get (pipeline, "flags", &flags, NULL); + flags |= GST_PLAY_FLAG_VIS; + g_object_set (pipeline, "flags", flags, NULL); + + /* set vis plugin for playbin */ + g_object_set (pipeline, "vis-plugin", vis_plugin, NULL); + + /* Start playing */ + gst_element_set_state (pipeline, GST_STATE_PLAYING); + + /* Wait until error or EOS */ + bus = gst_element_get_bus (pipeline); + msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS); + + /* Free resources */ + if (msg != NULL) + gst_message_unref (msg); + gst_plugin_feature_list_free (list); + gst_object_unref (bus); + gst_element_set_state (pipeline, GST_STATE_NULL); + gst_object_unref (pipeline); + return 0; +} + diff --git a/playback/7/Makefile b/playback/7/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/playback/7/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/playback/7/custom b/playback/7/custom new file mode 100755 index 0000000..31d9e2b Binary files /dev/null and b/playback/7/custom differ diff --git a/playback/7/custom.c b/playback/7/custom.c new file mode 100644 index 0000000..8505555 --- /dev/null +++ b/playback/7/custom.c @@ -0,0 +1,56 @@ +#include + +int main(int argc, char *argv[]) { + GstElement *pipeline, *bin, *equalizer, *convert, *sink; + GstPad *pad, *ghost_pad; + GstBus *bus; + GstMessage *msg; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Build the pipeline */ + pipeline = gst_parse_launch ("playbin uri=file:///home/ye/Music/6.wav", NULL); + + /* Create the elements inside the sink bin */ + equalizer = gst_element_factory_make ("equalizer-3bands", "equalizer"); + convert = gst_element_factory_make ("audioconvert", "convert"); + sink = gst_element_factory_make ("autoaudiosink", "audio_sink"); + if (!equalizer || !convert || !sink) { + g_printerr ("Not all elements could be created.\n"); + return -1; + } + + /* Create the sink bin, add the elements and link them */ + bin = gst_bin_new ("audio_sink_bin"); + gst_bin_add_many (GST_BIN (bin), equalizer, convert, sink, NULL); + gst_element_link_many (equalizer, convert, sink, NULL); + pad = gst_element_get_static_pad (equalizer, "sink"); + ghost_pad = gst_ghost_pad_new ("sink", pad); + gst_pad_set_active (ghost_pad, TRUE); + gst_element_add_pad (bin, ghost_pad); + gst_object_unref (pad); + + /* Configure the equalizer */ + g_object_set (G_OBJECT (equalizer), "band1", (gdouble)-24.0, NULL); + g_object_set (G_OBJECT (equalizer), "band2", (gdouble)-24.0, NULL); + + /* Set playbin's audio sink to be our sink bin */ + g_object_set (GST_OBJECT (pipeline), "audio-sink", bin, NULL); + + /* Start playing */ + gst_element_set_state (pipeline, GST_STATE_PLAYING); + + /* Wait until error or EOS */ + bus = gst_element_get_bus (pipeline); + msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS); + + /* Free resources */ + if (msg != NULL) + gst_message_unref (msg); + gst_object_unref (bus); + gst_element_set_state (pipeline, GST_STATE_NULL); + gst_object_unref (pipeline); + return 0; +} + diff --git a/playback/readme b/playback/readme new file mode 100644 index 0000000..c596d16 --- /dev/null +++ b/playback/readme @@ -0,0 +1,5 @@ +Abstract: + *4: rate of progress we can see. + 5: color balance manually. + *6: audio visualization. + 7: custom playbin sinks. diff --git a/tutorial/1/Makefile b/tutorial/1/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/tutorial/1/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/tutorial/1/hello b/tutorial/1/hello new file mode 100644 index 0000000..b5ae24a Binary files /dev/null and b/tutorial/1/hello differ diff --git a/tutorial/1/hello.c b/tutorial/1/hello.c new file mode 100644 index 0000000..cd3e6f5 --- /dev/null +++ b/tutorial/1/hello.c @@ -0,0 +1,30 @@ +#include + +int main(int argc, char *argv[]) { + GstElement *pipeline; + GstBus *bus; + GstMessage *msg; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Build the pipeline */ + pipeline = gst_parse_launch ("playbin uri=file:///home/charley/Music/5.wav", NULL); + + /* Start playing */ + gst_element_set_state (pipeline, GST_STATE_PLAYING); + + /* Wait until error or EOS */ + bus = gst_element_get_bus (pipeline); + msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS); + + /* Free resources */ + if (msg != NULL) + gst_message_unref (msg); + gst_object_unref (bus); + gst_element_set_state (pipeline, GST_STATE_NULL); + gst_object_unref (pipeline); + return 0; +} + + diff --git a/tutorial/12/Makefile b/tutorial/12/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/tutorial/12/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/tutorial/12/stream b/tutorial/12/stream new file mode 100644 index 0000000..ffdc8f9 Binary files /dev/null and b/tutorial/12/stream differ diff --git a/tutorial/12/stream.c b/tutorial/12/stream.c new file mode 100644 index 0000000..2e53f50 --- /dev/null +++ b/tutorial/12/stream.c @@ -0,0 +1,100 @@ +#include +#include + +typedef struct _CustomData { + gboolean is_live; + GstElement *pipeline; + GMainLoop *loop; +} CustomData; + +static void cb_message (GstBus *bus, GstMessage *msg, CustomData *data) { + + switch (GST_MESSAGE_TYPE (msg)) { + case GST_MESSAGE_ERROR: { + GError *err; + gchar *debug; + + gst_message_parse_error (msg, &err, &debug); + g_print ("Error: %s\n", err->message); + g_error_free (err); + g_free (debug); + + gst_element_set_state (data->pipeline, GST_STATE_READY); + g_main_loop_quit (data->loop); + break; + } + case GST_MESSAGE_EOS: + /* end-of-stream */ + gst_element_set_state (data->pipeline, GST_STATE_READY); + g_main_loop_quit (data->loop); + break; + case GST_MESSAGE_BUFFERING: { + gint percent = 0; + + /* If the stream is live, we do not care about buffering. */ + if (data->is_live) break; + + gst_message_parse_buffering (msg, &percent); + g_print ("Buffering (%3d%%)\r", percent); + /* Wait until buffering is complete before start/resume playing */ + if (percent < 100) + gst_element_set_state (data->pipeline, GST_STATE_PAUSED); + else + gst_element_set_state (data->pipeline, GST_STATE_PLAYING); + break; + } + case GST_MESSAGE_CLOCK_LOST: + /* Get a new clock */ + gst_element_set_state (data->pipeline, GST_STATE_PAUSED); + gst_element_set_state (data->pipeline, GST_STATE_PLAYING); + break; + default: + /* Unhandled message */ + break; + } +} + +int main(int argc, char *argv[]) { + GstElement *pipeline; + GstBus *bus; + GstStateChangeReturn ret; + GMainLoop *main_loop; + CustomData data; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Initialize our data structure */ + memset (&data, 0, sizeof (data)); + + /* Build the pipeline */ + pipeline = gst_parse_launch ("playbin uri=file:///home/charley/Music/7.wav", NULL); + bus = gst_element_get_bus (pipeline); + + /* Start playing */ + ret = gst_element_set_state (pipeline, GST_STATE_PLAYING); + if (ret == GST_STATE_CHANGE_FAILURE) { + g_printerr ("Unable to set the pipeline to the playing state.\n"); + gst_object_unref (pipeline); + return -1; + } else if (ret == GST_STATE_CHANGE_NO_PREROLL) { + data.is_live = TRUE; + } + + main_loop = g_main_loop_new (NULL, FALSE); + data.loop = main_loop; + data.pipeline = pipeline; + + gst_bus_add_signal_watch (bus); + g_signal_connect (bus, "message", G_CALLBACK (cb_message), &data); + + g_main_loop_run (main_loop); + + /* Free resources */ + g_main_loop_unref (main_loop); + gst_object_unref (bus); + gst_element_set_state (pipeline, GST_STATE_NULL); + gst_object_unref (pipeline); + return 0; +} + diff --git a/tutorial/13/Makefile b/tutorial/13/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/tutorial/13/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/tutorial/13/trick.c b/tutorial/13/trick.c new file mode 100644 index 0000000..42816fe --- /dev/null +++ b/tutorial/13/trick.c @@ -0,0 +1,148 @@ +#include +#include +#include + +typedef struct _CustomData { + GstElement *pipeline; + GstElement *video_sink; + GMainLoop *loop; + + gboolean playing; /* Playing or Paused */ + gdouble rate; /* Current playback rate (can be negative) */ +} CustomData; + +/* Send seek event to change rate */ +static void send_seek_event (CustomData *data) { + gint64 position; + GstFormat format = GST_FORMAT_TIME; + GstEvent *seek_event; + + /* Obtain the current position, needed for the seek event */ + if (!gst_element_query_position (data->pipeline, format, &position)) { + g_printerr ("Unable to retrieve current position.\n"); + return; + } + + /* Create the seek event */ + if (data->rate > 0) { + seek_event = gst_event_new_seek (data->rate, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, + GST_SEEK_TYPE_SET, position, GST_SEEK_TYPE_NONE, 0); + } else { + seek_event = gst_event_new_seek (data->rate, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, + GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_SET, position); + } + + if (data->video_sink == NULL) { + /* If we have not done so, obtain the sink through which we will send the seek events */ + g_object_get (data->pipeline, "video-sink", &data->video_sink, NULL); + } + + /* Send the event */ + gst_element_send_event (data->video_sink, seek_event); + + g_print ("Current rate: %g\n", data->rate); +} + +/* Process keyboard input */ +static gboolean handle_keyboard (GIOChannel *source, GIOCondition cond, CustomData *data) { + gchar *str = NULL; + + if (g_io_channel_read_line (source, &str, NULL, NULL, NULL) != G_IO_STATUS_NORMAL) { + return TRUE; + } + + switch (g_ascii_tolower (str[0])) { + case 'p': + data->playing = !data->playing; + gst_element_set_state (data->pipeline, data->playing ? GST_STATE_PLAYING : GST_STATE_PAUSED); + g_print ("Setting state to %s\n", data->playing ? "PLAYING" : "PAUSE"); + break; + case 's': + if (g_ascii_isupper (str[0])) { + data->rate *= 2.0; + } else { + data->rate /= 2.0; + } + send_seek_event (data); + break; + case 'd': + data->rate *= -1.0; + send_seek_event (data); + break; + case 'n': + if (data->video_sink == NULL) { + /* If we have not done so, obtain the sink through which we will send the step events */ + g_object_get (data->pipeline, "video-sink", &data->video_sink, NULL); + } + + gst_element_send_event (data->video_sink, + gst_event_new_step (GST_FORMAT_BUFFERS, 1, data->rate, TRUE, FALSE)); + g_print ("Stepping one frame\n"); + break; + case 'q': + g_main_loop_quit (data->loop); + break; + default: + break; + } + + g_free (str); + + return TRUE; +} + +int main(int argc, char *argv[]) { + CustomData data; + GstStateChangeReturn ret; + GIOChannel *io_stdin; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Initialize our data structure */ + memset (&data, 0, sizeof (data)); + + /* Print usage map */ + g_print ( + "USAGE: Choose one of the following options, then press enter:\n" + " 'P' to toggle between PAUSE and PLAY\n" + " 'S' to increase playback speed, 's' to decrease playback speed\n" + " 'D' to toggle playback direction\n" + " 'N' to move to next frame (in the current direction, better in PAUSE)\n" + " 'Q' to quit\n"); + + /* Build the pipeline */ + data.pipeline = gst_parse_launch ("playbin uri=file:///home/ye/Music/ifyou.mp3", NULL); + + /* Add a keyboard watch so we get notified of keystrokes */ +#ifdef G_OS_WIN32 + io_stdin = g_io_channel_win32_new_fd (fileno (stdin)); +#else + io_stdin = g_io_channel_unix_new (fileno (stdin)); +#endif + g_io_add_watch (io_stdin, G_IO_IN, (GIOFunc)handle_keyboard, &data); + + /* Start playing */ + ret = gst_element_set_state (data.pipeline, GST_STATE_PLAYING); + if (ret == GST_STATE_CHANGE_FAILURE) { + g_printerr ("Unable to set the pipeline to the playing state.\n"); + gst_object_unref (data.pipeline); + return -1; + } + data.playing = TRUE; + data.rate = 1.0; + + /* Create a GLib Main Loop and set it to run */ + data.loop = g_main_loop_new (NULL, FALSE); + g_main_loop_run (data.loop); + + /* Free resources */ + g_main_loop_unref (data.loop); + g_io_channel_unref (io_stdin); + gst_element_set_state (data.pipeline, GST_STATE_NULL); + if (data.video_sink != NULL) + gst_object_unref (data.video_sink); + gst_object_unref (data.pipeline); + return 0; +} + diff --git a/tutorial/2/Makefile b/tutorial/2/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/tutorial/2/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/tutorial/2/concept.c b/tutorial/2/concept.c new file mode 100644 index 0000000..e824a1e --- /dev/null +++ b/tutorial/2/concept.c @@ -0,0 +1,77 @@ +#include + +int main(int argc, char *argv[]) { + GstElement *pipeline, *source, *sink; + GstBus *bus; + GstMessage *msg; + GstStateChangeReturn ret; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Create the elements */ + source = gst_element_factory_make ("videotestsrc", "source"); + sink = gst_element_factory_make ("autovideosink", "sink"); + + /* Create the empty pipeline */ + pipeline = gst_pipeline_new ("test-pipeline"); + + if (!pipeline || !source || !sink) { + g_printerr ("Not all elements could be created.\n"); + return -1; + } + + /* Build the pipeline */ + gst_bin_add_many (GST_BIN (pipeline), source, sink, NULL); + if (gst_element_link (source, sink) != TRUE) { + g_printerr ("Elements could not be linked.\n"); + gst_object_unref (pipeline); + return -1; + } + + /* Modify the source's properties */ + g_object_set (source, "pattern", 1, NULL); + + /* Start playing */ + ret = gst_element_set_state (pipeline, GST_STATE_PLAYING); + if (ret == GST_STATE_CHANGE_FAILURE) { + g_printerr ("Unable to set the pipeline to the playing state.\n"); + gst_object_unref (pipeline); + return -1; + } + + /* Wait until error or EOS */ + bus = gst_element_get_bus (pipeline); + msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS); + + /* Parse message */ + if (msg != NULL) { + GError *err; + gchar *debug_info; + + switch (GST_MESSAGE_TYPE (msg)) { + case GST_MESSAGE_ERROR: + gst_message_parse_error (msg, &err, &debug_info); + g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message); + g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none"); + g_clear_error (&err); + g_free (debug_info); + break; + case GST_MESSAGE_EOS: + g_print ("End-Of-Stream reached.\n"); + break; + default: + /* We should not reach here because we only asked for ERRORs and EOS */ + g_printerr ("Unexpected message received.\n"); + break; + } + gst_message_unref (msg); + } + + /* Free resources */ + gst_object_unref (bus); + gst_element_set_state (pipeline, GST_STATE_NULL); + gst_object_unref (pipeline); + return 0; +} + diff --git a/tutorial/3/Makefile b/tutorial/3/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/tutorial/3/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/tutorial/3/dynamic.c b/tutorial/3/dynamic.c new file mode 100644 index 0000000..9099769 --- /dev/null +++ b/tutorial/3/dynamic.c @@ -0,0 +1,151 @@ +#include + +/* Structure to contain all our information, so we can pass it to callbacks */ +typedef struct _CustomData { + GstElement *pipeline; + GstElement *source; + GstElement *convert; + GstElement *sink; +} CustomData; + +/* Handler for the pad-added signal */ +static void pad_added_handler (GstElement *src, GstPad *pad, CustomData *data); + +int main(int argc, char *argv[]) { + CustomData data; + GstBus *bus; + GstMessage *msg; + GstStateChangeReturn ret; + gboolean terminate = FALSE; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Create the elements */ + data.source = gst_element_factory_make ("uridecodebin", "source"); + data.convert = gst_element_factory_make ("audioconvert", "convert"); + data.sink = gst_element_factory_make ("autoaudiosink", "sink"); + + /* Create the empty pipeline */ + data.pipeline = gst_pipeline_new ("test-pipeline"); + + if (!data.pipeline || !data.source || !data.convert || !data.sink) { + g_printerr ("Not all elements could be created.\n"); + return -1; + } + + /* Build the pipeline. Note that we are NOT linking the source at this + * point. We will do it later. */ + gst_bin_add_many (GST_BIN (data.pipeline), data.source, data.convert , data.sink, NULL); + if (!gst_element_link (data.convert, data.sink)) { +// if (!gst_element_link_many (data.source, data.convert, data.sink, NULL)) { + g_printerr ("Elements could not be linked.\n"); + gst_object_unref (data.pipeline); + return -1; + } + + /* Set the URI to play */ + g_object_set (data.source, "uri", argv[1], NULL); + + /* Connect to the pad-added signal */ + g_signal_connect (data.source, "pad-added", G_CALLBACK (pad_added_handler), &data); + + /* Start playing */ + ret = gst_element_set_state (data.pipeline, GST_STATE_PLAYING); + if (ret == GST_STATE_CHANGE_FAILURE) { + g_printerr ("Unable to set the pipeline to the playing state.\n"); + gst_object_unref (data.pipeline); + return -1; + } + + /* Listen to the bus */ + bus = gst_element_get_bus (data.pipeline); + do { +/* msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, + GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS); +*/ + /* Parse message */ + if (msg != NULL) { + GError *err; + gchar *debug_info; + + switch (GST_MESSAGE_TYPE (msg)) { + case GST_MESSAGE_ERROR: + gst_message_parse_error (msg, &err, &debug_info); + g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message); + g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none"); + g_clear_error (&err); + g_free (debug_info); + terminate = TRUE; + break; + case GST_MESSAGE_EOS: + g_print ("End-Of-Stream reached.\n"); + terminate = TRUE; + break; + case GST_MESSAGE_STATE_CHANGED: + /* We are only interested in state-changed messages from the pipeline */ + if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data.pipeline)) { + GstState old_state, new_state, pending_state; + gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state); + g_print ("Pipeline state changed from %s to %s:\n", + gst_element_state_get_name (old_state), gst_element_state_get_name (new_state)); + } + break; + default: + /* We should not reach here */ + g_printerr ("Unexpected message received.\n"); + break; + } + gst_message_unref (msg); + } + } while (!terminate); + + /* Free resources */ + gst_object_unref (bus); + gst_element_set_state (data.pipeline, GST_STATE_NULL); + gst_object_unref (data.pipeline); + return 0; +} + +/* This function will be called by the pad-added signal */ +static void pad_added_handler (GstElement *src, GstPad *new_pad, CustomData *data) { + GstPad *sink_pad = gst_element_get_static_pad (data->convert, "sink"); + GstPadLinkReturn ret; + GstCaps *new_pad_caps = NULL; + GstStructure *new_pad_struct = NULL; + const gchar *new_pad_type = NULL; + + g_print ("Received new pad '%s' from '%s':\n", GST_PAD_NAME (new_pad), GST_ELEMENT_NAME (src)); + + /* If our converter is already linked, we have nothing to do here */ + if (gst_pad_is_linked (sink_pad)) { + g_print (" We are already linked. Ignoring.\n"); + goto exit; + } + + /* Check the new pad's type */ + new_pad_caps = gst_pad_query_caps (new_pad, NULL); + new_pad_struct = gst_caps_get_structure (new_pad_caps, 0); + new_pad_type = gst_structure_get_name (new_pad_struct); + if (!g_str_has_prefix (new_pad_type, "audio/x-raw")) { + g_print (" It has type '%s' which is not raw audio. Ignoring.\n", new_pad_type); + goto exit; + } + + /* Attempt the link */ + ret = gst_pad_link (new_pad, sink_pad); + if (GST_PAD_LINK_FAILED (ret)) { + g_print (" Type is '%s' but link failed.\n", new_pad_type); + } else { + g_print (" Link succeeded (type '%s').\n", new_pad_type); + } + +exit: + /* Unreference the new pad's caps, if we got them */ + if (new_pad_caps != NULL) + gst_caps_unref (new_pad_caps); + + /* Unreference the sink pad */ + gst_object_unref (sink_pad); +} + diff --git a/tutorial/4/Makefile b/tutorial/4/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/tutorial/4/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/tutorial/4/time.c b/tutorial/4/time.c new file mode 100644 index 0000000..06cfc83 --- /dev/null +++ b/tutorial/4/time.c @@ -0,0 +1,160 @@ +#include + +/* Structure to contain all our information, so we can pass it around */ +typedef struct _CustomData { + GstElement *playbin; /* Our one and only element */ + gboolean playing; /* Are we in the PLAYING state? */ + gboolean terminate; /* Should we terminate execution? */ + gboolean seek_enabled; /* Is seeking enabled for this media? */ + gboolean seek_done; /* Have we performed the seek already? */ + gint64 duration; /* How long does this media last, in nanoseconds */ +} CustomData; + +/* Forward definition of the message processing function */ +static void handle_message (CustomData *data, GstMessage *msg); + +int main(int argc, char *argv[]) { + CustomData data; + GstBus *bus; + GstMessage *msg; + GstStateChangeReturn ret; + + data.playing = FALSE; + data.terminate = FALSE; + data.seek_enabled = FALSE; + data.seek_done = FALSE; + data.duration = GST_CLOCK_TIME_NONE; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Create the elements */ + data.playbin = gst_element_factory_make ("playbin", "playbin"); + + if (!data.playbin) { + g_printerr ("Not all elements could be created.\n"); + return -1; + } + + /* Set the URI to play */ + g_object_set (data.playbin, "uri", argv[1], NULL); + + /* Start playing */ + ret = gst_element_set_state (data.playbin, GST_STATE_PLAYING); + if (ret == GST_STATE_CHANGE_FAILURE) { + g_printerr ("Unable to set the pipeline to the playing state.\n"); + gst_object_unref (data.playbin); + return -1; + } + + /* Listen to the bus */ + bus = gst_element_get_bus (data.playbin); + do { + msg = gst_bus_timed_pop_filtered (bus, 100 * GST_MSECOND, + GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS | GST_MESSAGE_DURATION); + + /* Parse message */ + if (msg != NULL) { + handle_message (&data, msg); + } else { + /* We got no message, this means the timeout expired */ + if (data.playing) { + gint64 current = -1; + + /* Query the current position of the stream */ + if (!gst_element_query_position (data.playbin, GST_FORMAT_TIME, ¤t)) { + g_printerr ("Could not query current position.\n"); + } + + /* 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.playbin, GST_FORMAT_TIME, &data.duration)) { + g_printerr ("Could not query current duration.\n"); + } + } + + /* Print current position and total duration */ + g_print ("Position %" GST_TIME_FORMAT " / %" GST_TIME_FORMAT "\r", + GST_TIME_ARGS (current), GST_TIME_ARGS (data.duration)); + +// g_print ("Position %" GST_TIME_FORMAT" \r", +// GST_TIME_ARGS (current)); + + /* If seeking is enabled, we have not done it yet, and the time is right, seek */ + if (data.seek_enabled && !data.seek_done && current > 10 * GST_SECOND) { + g_print ("\nReached 10s, performing seek...\n"); + gst_element_seek_simple (data.playbin, GST_FORMAT_TIME, + GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, 30 * GST_SECOND); + data.seek_done = TRUE; + } + } + } + } while (!data.terminate); + + /* Free resources */ + gst_object_unref (bus); + gst_element_set_state (data.playbin, GST_STATE_NULL); + gst_object_unref (data.playbin); + return 0; +} + +static void handle_message (CustomData *data, GstMessage *msg) { + GError *err; + gchar *debug_info; + + switch (GST_MESSAGE_TYPE (msg)) { + case GST_MESSAGE_ERROR: + gst_message_parse_error (msg, &err, &debug_info); + g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message); + g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none"); + g_clear_error (&err); + g_free (debug_info); + data->terminate = TRUE; + break; + case GST_MESSAGE_EOS: + g_print ("End-Of-Stream reached.\n"); + data->terminate = TRUE; + break; + case GST_MESSAGE_DURATION: + /* The duration has changed, mark the current one as invalid */ + data->duration = GST_CLOCK_TIME_NONE; + break; + case GST_MESSAGE_STATE_CHANGED: { + GstState old_state, new_state, pending_state; + gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state); + if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data->playbin)) { + g_print ("Pipeline state changed from %s to %s:\n", + gst_element_state_get_name (old_state), gst_element_state_get_name (new_state)); + + /* Remember whether we are in the PLAYING state or not */ + data->playing = (new_state == GST_STATE_PLAYING); + + if (data->playing) { + /* We just moved to PLAYING. Check if seeking is possible */ + GstQuery *query; + gint64 start, end; + query = gst_query_new_seeking (GST_FORMAT_TIME); + if (gst_element_query (data->playbin, query)) { + gst_query_parse_seeking (query, NULL, &data->seek_enabled, &start, &end); + if (data->seek_enabled) { + g_print ("Seeking is ENABLED from %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT "\n", + GST_TIME_ARGS (start), GST_TIME_ARGS (end)); + } else { + g_print ("Seeking is DISABLED for this stream.\n"); + } + } + else { + g_printerr ("Seeking query failed."); + } + gst_query_unref (query); + } + } + } break; + default: + /* We should not reach here */ + g_printerr ("Unexpected message received.\n"); + break; + } + gst_message_unref (msg); +} + diff --git a/tutorial/5/Makefile b/tutorial/5/Makefile new file mode 100644 index 0000000..b9a5b56 --- /dev/null +++ b/tutorial/5/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-video-1.0 gtk+-3.0 gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/tutorial/5/gui.c b/tutorial/5/gui.c new file mode 100644 index 0000000..4281fa6 --- /dev/null +++ b/tutorial/5/gui.c @@ -0,0 +1,381 @@ +#include + +#include +#include +#include + +#include +#if defined (GDK_WINDOWING_X11) +#include +#elif defined (GDK_WINDOWING_WIN32) +#include +#elif defined (GDK_WINDOWING_QUARTZ) +#include +#endif + +/* Structure to contain all our information, so we can pass it around */ +typedef struct _CustomData { + GstElement *playbin; /* Our one and only pipeline */ + + GtkWidget *slider; /* Slider widget to keep track of current position */ + GtkWidget *streams_list; /* Text widget to display info about the streams */ + gulong slider_update_signal_id; /* Signal ID for the slider update signal */ + + GstState state; /* Current state of the pipeline */ + gint64 duration; /* Duration of the clip, in nanoseconds */ +} CustomData; + +/* This function is called when the GUI toolkit creates the physical window that will hold the video. + * At this point we can retrieve its handler (which has a different meaning depending on the windowing system) + * and pass it to GStreamer through the VideoOverlay interface. */ +static void realize_cb (GtkWidget *widget, CustomData *data) { + GdkWindow *window = gtk_widget_get_window (widget); + guintptr window_handle; + + if (!gdk_window_ensure_native (window)) + g_error ("Couldn't create native window needed for GstVideoOverlay!"); + + /* Retrieve window handler from GDK */ +#if defined (GDK_WINDOWING_WIN32) + window_handle = (guintptr)GDK_WINDOW_HWND (window); +#elif defined (GDK_WINDOWING_QUARTZ) + window_handle = gdk_quartz_window_get_nsview (window); +#elif defined (GDK_WINDOWING_X11) + window_handle = GDK_WINDOW_XID (window); +#endif + /* Pass it to playbin, which implements VideoOverlay and will forward it to the video sink */ + gst_video_overlay_set_window_handle (GST_VIDEO_OVERLAY (data->playbin), window_handle); +} + +/* This function is called when the PLAY button is clicked */ +static void play_cb (GtkButton *button, CustomData *data) { + gst_element_set_state (data->playbin, GST_STATE_PLAYING); +} + +/* This function is called when the PAUSE button is clicked */ +static void pause_cb (GtkButton *button, CustomData *data) { + gst_element_set_state (data->playbin, GST_STATE_PAUSED); +} + +/* This function is called when the STOP button is clicked */ +static void stop_cb (GtkButton *button, CustomData *data) { + gst_element_set_state (data->playbin, GST_STATE_READY); +} + +/* This function is called when the main window is closed */ +static void delete_event_cb (GtkWidget *widget, GdkEvent *event, CustomData *data) { + stop_cb (NULL, data); + gtk_main_quit (); +} + +/* This function is called everytime the video window needs to be redrawn (due to damage/exposure, + * rescaling, etc). GStreamer takes care of this in the PAUSED and PLAYING states, otherwise, + * we simply draw a black rectangle to avoid garbage showing up. */ +static gboolean draw_cb (GtkWidget *widget, cairo_t *cr, CustomData *data) { + if (data->state < GST_STATE_PAUSED) { + GtkAllocation allocation; + + /* Cairo is a 2D graphics library which we use here to clean the video window. + * It is used by GStreamer for other reasons, so it will always be available to us. */ + gtk_widget_get_allocation (widget, &allocation); + cairo_set_source_rgb (cr, 0, 0, 0); + cairo_rectangle (cr, 0, 0, allocation.width, allocation.height); + cairo_fill (cr); + } + + return FALSE; +} + +/* This function is called when the slider changes its position. We perform a seek to the + * new position here. */ +static void slider_cb (GtkRange *range, CustomData *data) { + gdouble value = gtk_range_get_value (GTK_RANGE (data->slider)); + gst_element_seek_simple (data->playbin, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, + (gint64)(value * GST_SECOND)); +} + +/* This creates all the GTK+ widgets that compose our application, and registers the callbacks */ +static void create_ui (CustomData *data) { + GtkWidget *main_window; /* The uppermost window, containing all other windows */ + GtkWidget *video_window; /* The drawing area where the video will be shown */ + GtkWidget *main_box; /* VBox to hold main_hbox and the controls */ + GtkWidget *main_hbox; /* HBox to hold the video_window and the stream info text widget */ + GtkWidget *controls; /* HBox to hold the buttons and the slider */ + GtkWidget *play_button, *pause_button, *stop_button; /* Buttons */ + + main_window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + g_signal_connect (G_OBJECT (main_window), "delete-event", G_CALLBACK (delete_event_cb), data); + + video_window = gtk_drawing_area_new (); + gtk_widget_set_double_buffered (video_window, FALSE); + g_signal_connect (video_window, "realize", G_CALLBACK (realize_cb), data); + g_signal_connect (video_window, "draw", G_CALLBACK (draw_cb), data); + + play_button = gtk_button_new_from_stock (GTK_STOCK_MEDIA_PLAY); + g_signal_connect (G_OBJECT (play_button), "clicked", G_CALLBACK (play_cb), data); + + pause_button = gtk_button_new_from_stock (GTK_STOCK_MEDIA_PAUSE); + g_signal_connect (G_OBJECT (pause_button), "clicked", G_CALLBACK (pause_cb), data); + + stop_button = gtk_button_new_from_stock (GTK_STOCK_MEDIA_STOP); + g_signal_connect (G_OBJECT (stop_button), "clicked", G_CALLBACK (stop_cb), data); + + data->slider = gtk_scale_new_with_range (GTK_ORIENTATION_HORIZONTAL, 0, 100, 1); + gtk_scale_set_draw_value (GTK_SCALE (data->slider), 0); + data->slider_update_signal_id = g_signal_connect (G_OBJECT (data->slider), "value-changed", G_CALLBACK (slider_cb), data); + + data->streams_list = gtk_text_view_new (); + gtk_text_view_set_editable (GTK_TEXT_VIEW (data->streams_list), FALSE); + + controls = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); + gtk_box_pack_start (GTK_BOX (controls), play_button, FALSE, FALSE, 2); + gtk_box_pack_start (GTK_BOX (controls), pause_button, FALSE, FALSE, 2); + gtk_box_pack_start (GTK_BOX (controls), stop_button, FALSE, FALSE, 2); + gtk_box_pack_start (GTK_BOX (controls), data->slider, TRUE, TRUE, 2); + + main_hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); + gtk_box_pack_start (GTK_BOX (main_hbox), video_window, TRUE, TRUE, 0); + gtk_box_pack_start (GTK_BOX (main_hbox), data->streams_list, FALSE, FALSE, 2); + + main_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); + gtk_box_pack_start (GTK_BOX (main_box), main_hbox, TRUE, TRUE, 0); + gtk_box_pack_start (GTK_BOX (main_box), controls, FALSE, FALSE, 0); + gtk_container_add (GTK_CONTAINER (main_window), main_box); + gtk_window_set_default_size (GTK_WINDOW (main_window), 640, 480); + + gtk_widget_show_all (main_window); +} + +/* This function is called periodically to refresh the GUI */ +static gboolean refresh_ui (CustomData *data) { + gint64 current = -1; + + /* We do not want to update anything unless we are in the PAUSED or PLAYING states */ + if (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->playbin, GST_FORMAT_TIME, &data->duration)) { + g_printerr ("Could not query current duration.\n"); + } else { + /* Set the range of the slider to the clip duration, in SECONDS */ + gtk_range_set_range (GTK_RANGE (data->slider), 0, (gdouble)data->duration / GST_SECOND); + } + } + + if (gst_element_query_position (data->playbin, GST_FORMAT_TIME, ¤t)) { + /* Block the "value-changed" signal, so the slider_cb function is not called + * (which would trigger a seek the user has not requested) */ + g_signal_handler_block (data->slider, data->slider_update_signal_id); + /* Set the position of the slider to the current pipeline positoin, in SECONDS */ + gtk_range_set_value (GTK_RANGE (data->slider), (gdouble)current / GST_SECOND); + /* Re-enable the signal */ + g_signal_handler_unblock (data->slider, data->slider_update_signal_id); + } + return TRUE; +} + +/* This function is called when new metadata is discovered in the stream */ +static void tags_cb (GstElement *playbin, gint stream, CustomData *data) { + /* We are possibly in a GStreamer working thread, so we notify the main + * thread of this event through a message in the bus */ + gst_element_post_message (playbin, + gst_message_new_application (GST_OBJECT (playbin), + gst_structure_new_empty ("tags-changed"))); +} + +/* This function is called when an error message is posted on the bus */ +static void error_cb (GstBus *bus, GstMessage *msg, CustomData *data) { + GError *err; + gchar *debug_info; + + /* Print error details on the screen */ + gst_message_parse_error (msg, &err, &debug_info); + g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message); + g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none"); + g_clear_error (&err); + g_free (debug_info); + + /* Set the pipeline to READY (which stops playback) */ + gst_element_set_state (data->playbin, GST_STATE_READY); +} + +/* This function is called when an End-Of-Stream message is posted on the bus. + * We just set the pipeline to READY (which stops playback) */ +static void eos_cb (GstBus *bus, GstMessage *msg, CustomData *data) { + g_print ("End-Of-Stream reached.\n"); + gst_element_set_state (data->playbin, GST_STATE_READY); +} + +/* This function is called when the pipeline changes states. We use it to + * keep track of the current state. */ +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); + if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data->playbin)) { + data->state = new_state; + g_print ("State set to %s\n", gst_element_state_get_name (new_state)); + if (old_state == GST_STATE_READY && new_state == GST_STATE_PAUSED) { + /* For extra responsiveness, we refresh the GUI as soon as we reach the PAUSED state */ + refresh_ui (data); + } + } +} + +/* Extract metadata from all the streams and write it to the text widget in the GUI */ +static void analyze_streams (CustomData *data) { + gint i; + GstTagList *tags; + gchar *str, *total_str; + guint rate; + gint n_video, n_audio, n_text; + GtkTextBuffer *text; + + /* Clean current contents of the widget */ + text = gtk_text_view_get_buffer (GTK_TEXT_VIEW (data->streams_list)); + gtk_text_buffer_set_text (text, "", -1); + + /* Read some properties */ + g_object_get (data->playbin, "n-video", &n_video, NULL); + g_object_get (data->playbin, "n-audio", &n_audio, NULL); + g_object_get (data->playbin, "n-text", &n_text, NULL); + + for (i = 0; i < n_video; i++) { + tags = NULL; + /* Retrieve the stream's video tags */ + g_signal_emit_by_name (data->playbin, "get-video-tags", i, &tags); + if (tags) { + total_str = g_strdup_printf ("video stream %d:\n", i); + gtk_text_buffer_insert_at_cursor (text, total_str, -1); + g_free (total_str); + gst_tag_list_get_string (tags, GST_TAG_VIDEO_CODEC, &str); + total_str = g_strdup_printf (" codec: %s\n", str ? str : "unknown"); + gtk_text_buffer_insert_at_cursor (text, total_str, -1); + g_free (total_str); + g_free (str); + gst_tag_list_free (tags); + } + } + + for (i = 0; i < n_audio; i++) { + tags = NULL; + /* Retrieve the stream's audio tags */ + g_signal_emit_by_name (data->playbin, "get-audio-tags", i, &tags); + if (tags) { + total_str = g_strdup_printf ("\naudio stream %d:\n", i); + gtk_text_buffer_insert_at_cursor (text, total_str, -1); + g_free (total_str); + if (gst_tag_list_get_string (tags, GST_TAG_AUDIO_CODEC, &str)) { + total_str = g_strdup_printf (" codec: %s\n", str); + gtk_text_buffer_insert_at_cursor (text, total_str, -1); + g_free (total_str); + g_free (str); + } + if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_CODE, &str)) { + total_str = g_strdup_printf (" language: %s\n", str); + gtk_text_buffer_insert_at_cursor (text, total_str, -1); + g_free (total_str); + g_free (str); + } + if (gst_tag_list_get_uint (tags, GST_TAG_BITRATE, &rate)) { + total_str = g_strdup_printf (" bitrate: %d\n", rate); + gtk_text_buffer_insert_at_cursor (text, total_str, -1); + g_free (total_str); + } + gst_tag_list_free (tags); + } + } + + for (i = 0; i < n_text; i++) { + tags = NULL; + /* Retrieve the stream's subtitle tags */ + g_signal_emit_by_name (data->playbin, "get-text-tags", i, &tags); + if (tags) { + total_str = g_strdup_printf ("\nsubtitle stream %d:\n", i); + gtk_text_buffer_insert_at_cursor (text, total_str, -1); + g_free (total_str); + if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_CODE, &str)) { + total_str = g_strdup_printf (" language: %s\n", str); + gtk_text_buffer_insert_at_cursor (text, total_str, -1); + g_free (total_str); + g_free (str); + } + gst_tag_list_free (tags); + } + } +} + +/* This function is called when an "application" message is posted on the bus. + * Here we retrieve the message posted by the tags_cb callback */ +static void application_cb (GstBus *bus, GstMessage *msg, CustomData *data) { + if (g_strcmp0 (gst_structure_get_name (gst_message_get_structure (msg)), "tags-changed") == 0) { + /* If the message is the "tags-changed" (only one we are currently issuing), update + * the stream info GUI */ + analyze_streams (data); + } +} + +int main(int argc, char *argv[]) { + CustomData data; + GstStateChangeReturn ret; + GstBus *bus; + + /* Initialize GTK */ + gtk_init (&argc, &argv); + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Initialize our data structure */ + memset (&data, 0, sizeof (data)); + data.duration = GST_CLOCK_TIME_NONE; + + /* Create the elements */ + data.playbin = gst_element_factory_make ("playbin", "playbin"); + + if (!data.playbin) { + g_printerr ("Not all elements could be created.\n"); + return -1; + } + + /* Set the URI to play */ + g_object_set (data.playbin, "uri", argv[1], NULL); + + /* Connect to interesting signals in playbin */ + g_signal_connect (G_OBJECT (data.playbin), "video-tags-changed", (GCallback) tags_cb, &data); + g_signal_connect (G_OBJECT (data.playbin), "audio-tags-changed", (GCallback) tags_cb, &data); + g_signal_connect (G_OBJECT (data.playbin), "text-tags-changed", (GCallback) tags_cb, &data); + + /* Create the GUI */ + create_ui (&data); + + /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */ + bus = gst_element_get_bus (data.playbin); + gst_bus_add_signal_watch (bus); + 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::application", (GCallback)application_cb, &data); + gst_object_unref (bus); + + /* Start playing */ + ret = gst_element_set_state (data.playbin, GST_STATE_PLAYING); + if (ret == GST_STATE_CHANGE_FAILURE) { + g_printerr ("Unable to set the pipeline to the playing state.\n"); + gst_object_unref (data.playbin); + return -1; + } + + /* Register a function that GLib will call every second */ + g_timeout_add_seconds (1, (GSourceFunc)refresh_ui, &data); + + /* Start the GTK main loop. We will not regain control until gtk_main_quit is called. */ + gtk_main (); + + /* Free resources */ + gst_element_set_state (data.playbin, GST_STATE_NULL); + gst_object_unref (data.playbin); + return 0; +} + diff --git a/tutorial/6/Makefile b/tutorial/6/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/tutorial/6/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/tutorial/6/media.c b/tutorial/6/media.c new file mode 100644 index 0000000..95b487f --- /dev/null +++ b/tutorial/6/media.c @@ -0,0 +1,208 @@ +#include + +/* Functions below print the Capabilities in a human-friendly format */ +static gboolean print_field (GQuark field, const GValue * value, gpointer pfx) { + gchar *str = gst_value_serialize (value); + + g_print ("%s %15s: %s\n", (gchar *) pfx, g_quark_to_string (field), str); + g_free (str); + return TRUE; +} + +static void print_caps (const GstCaps * caps, const gchar * pfx) { + guint i; + + g_return_if_fail (caps != NULL); + + if (gst_caps_is_any (caps)) { + g_print ("%sANY\n", pfx); + return; + } + if (gst_caps_is_empty (caps)) { + g_print ("%sEMPTY\n", pfx); + return; + } + + for (i = 0; i < gst_caps_get_size (caps); i++) { + GstStructure *structure = gst_caps_get_structure (caps, i); + + g_print ("%s%s\n", pfx, gst_structure_get_name (structure)); + gst_structure_foreach (structure, print_field, (gpointer) pfx); + } +} + +/* Prints information about a Pad Template, including its Capabilities */ +static void print_pad_templates_information (GstElementFactory * factory) { + const GList *pads; + GstStaticPadTemplate *padtemplate; + + g_print ("Pad Templates for %s:\n", gst_element_factory_get_longname (factory)); + if (!gst_element_factory_get_num_pad_templates (factory)) { + g_print (" none\n"); + return; + } + + pads = gst_element_factory_get_static_pad_templates (factory); + while (pads) { + padtemplate = pads->data; + pads = g_list_next (pads); + + if (padtemplate->direction == GST_PAD_SRC) + g_print (" SRC template: '%s'\n", padtemplate->name_template); + else if (padtemplate->direction == GST_PAD_SINK) + g_print (" SINK template: '%s'\n", padtemplate->name_template); + else + g_print (" UNKNOWN!!! template: '%s'\n", padtemplate->name_template); + + if (padtemplate->presence == GST_PAD_ALWAYS) + g_print (" Availability: Always\n"); + else if (padtemplate->presence == GST_PAD_SOMETIMES) + g_print (" Availability: Sometimes\n"); + else if (padtemplate->presence == GST_PAD_REQUEST) { + g_print (" Availability: On request\n"); + } else + g_print (" Availability: UNKNOWN!!!\n"); + + if (padtemplate->static_caps.string) { + GstCaps *caps; + g_print (" Capabilities:\n"); + caps = gst_static_caps_get (&padtemplate->static_caps); + print_caps (caps, " "); + gst_caps_unref (caps); + + } + + g_print ("\n"); + } +} + +/* Shows the CURRENT capabilities of the requested pad in the given element */ +static void print_pad_capabilities (GstElement *element, gchar *pad_name) { + GstPad *pad = NULL; + GstCaps *caps = NULL; + + /* Retrieve pad */ + pad = gst_element_get_static_pad (element, pad_name); + if (!pad) { + g_printerr ("Could not retrieve pad '%s'\n", pad_name); + return; + } + + /* Retrieve negotiated caps (or acceptable caps if negotiation is not finished yet) */ + caps = gst_pad_get_current_caps (pad); + if (!caps) + caps = gst_pad_query_caps (pad, NULL); + + /* Print and free */ + g_print ("Caps for the %s pad:\n", pad_name); + print_caps (caps, " "); + gst_caps_unref (caps); + gst_object_unref (pad); +} + +int main(int argc, char *argv[]) { + GstElement *pipeline, *source, *sink; + GstElementFactory *source_factory, *sink_factory; + GstBus *bus; + GstMessage *msg; + GstStateChangeReturn ret; + gboolean terminate = FALSE; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Create the element factories */ + source_factory = gst_element_factory_find ("audiotestsrc"); + sink_factory = gst_element_factory_find ("autoaudiosink"); + if (!source_factory || !sink_factory) { + g_printerr ("Not all element factories could be created.\n"); + return -1; + } + + /* Print information about the pad templates of these factories */ + print_pad_templates_information (source_factory); + print_pad_templates_information (sink_factory); + + /* Ask the factories to instantiate actual elements */ + source = gst_element_factory_create (source_factory, "source"); + sink = gst_element_factory_create (sink_factory, "sink"); + + /* Create the empty pipeline */ + pipeline = gst_pipeline_new ("test-pipeline"); + + if (!pipeline || !source || !sink) { + g_printerr ("Not all elements could be created.\n"); + return -1; + } + + /* Build the pipeline */ + gst_bin_add_many (GST_BIN (pipeline), source, sink, NULL); + if (gst_element_link (source, sink) != TRUE) { + g_printerr ("Elements could not be linked.\n"); + gst_object_unref (pipeline); + return -1; + } + + /* Print initial negotiated caps (in NULL state) */ + g_print ("In NULL state:\n"); + print_pad_capabilities (sink, "sink"); + + /* Start playing */ + ret = gst_element_set_state (pipeline, GST_STATE_PLAYING); + if (ret == GST_STATE_CHANGE_FAILURE) { + g_printerr ("Unable to set the pipeline to the playing state (check the bus for error messages).\n"); + } + + /* Wait until error, EOS or State Change */ + bus = gst_element_get_bus (pipeline); + do { + msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS | + GST_MESSAGE_STATE_CHANGED); + + /* Parse message */ + if (msg != NULL) { + GError *err; + gchar *debug_info; + + switch (GST_MESSAGE_TYPE (msg)) { + case GST_MESSAGE_ERROR: + gst_message_parse_error (msg, &err, &debug_info); + g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message); + g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none"); + g_clear_error (&err); + g_free (debug_info); + terminate = TRUE; + break; + case GST_MESSAGE_EOS: + g_print ("End-Of-Stream reached.\n"); + terminate = TRUE; + break; + case GST_MESSAGE_STATE_CHANGED: + /* We are only interested in state-changed messages from the pipeline */ + if (GST_MESSAGE_SRC (msg) == GST_OBJECT (pipeline)) { + GstState old_state, new_state, pending_state; + gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state); + g_print ("\nPipeline state changed from %s to %s:\n", + gst_element_state_get_name (old_state), gst_element_state_get_name (new_state)); + /* Print the current capabilities of the sink element */ + print_pad_capabilities (sink, "sink"); + } + break; + default: + /* We should not reach here because we only asked for ERRORs, EOS and STATE_CHANGED */ + g_printerr ("Unexpected message received.\n"); + break; + } + gst_message_unref (msg); + } + } while (!terminate); + + /* Free resources */ + gst_object_unref (bus); + gst_element_set_state (pipeline, GST_STATE_NULL); + gst_object_unref (pipeline); + gst_object_unref (source_factory); + gst_object_unref (sink_factory); + return 0; +} + diff --git a/tutorial/7/Makefile b/tutorial/7/Makefile new file mode 100644 index 0000000..edd584b --- /dev/null +++ b/tutorial/7/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/tutorial/7/multithread.c b/tutorial/7/multithread.c new file mode 100644 index 0000000..8801ee1 --- /dev/null +++ b/tutorial/7/multithread.c @@ -0,0 +1,90 @@ +#include + +int main(int argc, char *argv[]) { + GstElement *pipeline, *audio_source, *tee, *audio_queue, *audio_convert, *audio_resample, *audio_sink; + GstElement *video_queue, *visual, *video_convert, *video_sink; + GstBus *bus; + GstMessage *msg; + GstPadTemplate *tee_src_pad_template; + GstPad *tee_audio_pad, *tee_video_pad; + GstPad *queue_audio_pad, *queue_video_pad; + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + /* Create the elements */ + audio_source = gst_element_factory_make ("audiotestsrc", "audio_source"); + tee = gst_element_factory_make ("tee", "tee"); + audio_queue = gst_element_factory_make ("queue", "audio_queue"); + audio_convert = gst_element_factory_make ("audioconvert", "audio_convert"); + audio_resample = gst_element_factory_make ("audioresample", "audio_resample"); + audio_sink = gst_element_factory_make ("autoaudiosink", "audio_sink"); + video_queue = gst_element_factory_make ("queue", "video_queue"); + visual = gst_element_factory_make ("wavescope", "visual"); + video_convert = gst_element_factory_make ("videoconvert", "csp"); + video_sink = gst_element_factory_make ("autovideosink", "video_sink"); + + /* Create the empty pipeline */ + pipeline = gst_pipeline_new ("test-pipeline"); + + if (!pipeline || !audio_source || !tee || !audio_queue || !audio_convert || !audio_resample || !audio_sink || + !video_queue || !visual || !video_convert || !video_sink) { + g_printerr ("Not all elements could be created.\n"); + return -1; + } + + /* Configure elements */ + g_object_set (audio_source, "freq", 215.0f, NULL); + g_object_set (visual, "shader", 0, "style", 1, NULL); + + /* Link all elements that can be automatically linked because they have "Always" pads */ + gst_bin_add_many (GST_BIN (pipeline), audio_source, tee, audio_queue, audio_convert, audio_resample, audio_sink, + video_queue, visual, video_convert, video_sink, NULL); + if (gst_element_link_many (audio_source, tee, NULL) != TRUE || + gst_element_link_many (audio_queue, audio_convert, audio_resample, audio_sink, NULL) != TRUE || + gst_element_link_many (video_queue, visual, video_convert, video_sink, NULL) != TRUE) { + g_printerr ("Elements could not be linked.\n"); + gst_object_unref (pipeline); + return -1; + } + + /* Manually link the Tee, which has "Request" pads */ + tee_src_pad_template = gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS (tee), "src_%d"); + tee_audio_pad = gst_element_request_pad (tee, tee_src_pad_template, NULL, NULL); + g_print ("Obtained request pad %s for audio branch.\n", gst_pad_get_name (tee_audio_pad)); + queue_audio_pad = gst_element_get_static_pad (audio_queue, "sink"); + tee_video_pad = gst_element_request_pad (tee, tee_src_pad_template, NULL, NULL); + g_print ("Obtained request pad %s for video branch.\n", gst_pad_get_name (tee_video_pad)); + queue_video_pad = gst_element_get_static_pad (video_queue, "sink"); + if (gst_pad_link (tee_audio_pad, queue_audio_pad) != GST_PAD_LINK_OK || + gst_pad_link (tee_video_pad, queue_video_pad) != GST_PAD_LINK_OK) { + g_printerr ("Tee could not be linked.\n"); + gst_object_unref (pipeline); + return -1; + } + gst_object_unref (queue_audio_pad); + gst_object_unref (queue_video_pad); + + /* Start playing the pipeline */ + gst_element_set_state (pipeline, GST_STATE_PLAYING); + + /* Wait until error or EOS */ + bus = gst_element_get_bus (pipeline); + msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS); + + /* Release the request pads from the Tee, and unref them */ + gst_element_release_request_pad (tee, tee_audio_pad); + gst_element_release_request_pad (tee, tee_video_pad); + gst_object_unref (tee_audio_pad); + gst_object_unref (tee_video_pad); + + /* Free resources */ + if (msg != NULL) + gst_message_unref (msg); + gst_object_unref (bus); + gst_element_set_state (pipeline, GST_STATE_NULL); + + gst_object_unref (pipeline); + return 0; +} + diff --git a/tutorial/9/Makefile b/tutorial/9/Makefile new file mode 100644 index 0000000..8759d09 --- /dev/null +++ b/tutorial/9/Makefile @@ -0,0 +1,9 @@ +SRC = $(wildcard *.c) +TARGET = $(patsubst %.c, %, $(SRC)) +all: $(TARGET) + +%:%.c + gcc -o $@ $< `pkg-config --libs --cflags gstreamer-pbutils-1.0 gstreamer-1.0` + +clean: + rm -f $(TARGET) diff --git a/tutorial/9/information.c b/tutorial/9/information.c new file mode 100644 index 0000000..afbb5ea --- /dev/null +++ b/tutorial/9/information.c @@ -0,0 +1,217 @@ +#include +#include +#include + +/* Structure to contain all our information, so we can pass it around */ +typedef struct _CustomData { + GstDiscoverer *discoverer; + GMainLoop *loop; +} CustomData; + +/* Print a tag in a human-readable format (name: value) */ +static void print_tag_foreach (const GstTagList *tags, const gchar *tag, gpointer user_data) { + GValue val = { 0, }; + gchar *str; + gint depth = GPOINTER_TO_INT (user_data); + + gst_tag_list_copy_value (&val, tags, tag); + + if (G_VALUE_HOLDS_STRING (&val)) + str = g_value_dup_string (&val); + else + str = gst_value_serialize (&val); + + g_print ("%*s%s: %s\n", 2 * depth, " ", gst_tag_get_nick (tag), str); + g_free (str); + + g_value_unset (&val); +} + +/* Print information regarding a stream */ +static void print_stream_info (GstDiscovererStreamInfo *info, gint depth) { + gchar *desc = NULL; + GstCaps *caps; + const GstTagList *tags; + + caps = gst_discoverer_stream_info_get_caps (info); + + if (caps) { + if (gst_caps_is_fixed (caps)) + desc = gst_pb_utils_get_codec_description (caps); + else + desc = gst_caps_to_string (caps); + gst_caps_unref (caps); + } + + g_print ("%*s%s: %s\n", 2 * depth, " ", gst_discoverer_stream_info_get_stream_type_nick (info), (desc ? desc : "")); + + if (desc) { + g_free (desc); + desc = NULL; + } + + tags = gst_discoverer_stream_info_get_tags (info); + if (tags) { + g_print ("%*sTags:\n", 2 * (depth + 1), " "); + gst_tag_list_foreach (tags, print_tag_foreach, GINT_TO_POINTER (depth + 2)); + } +} + +/* Print information regarding a stream and its substreams, if any */ +static void print_topology (GstDiscovererStreamInfo *info, gint depth) { + GstDiscovererStreamInfo *next; + + if (!info) + return; + + print_stream_info (info, depth); + + next = gst_discoverer_stream_info_get_next (info); + if (next) { + print_topology (next, depth + 1); + gst_discoverer_stream_info_unref (next); + } else if (GST_IS_DISCOVERER_CONTAINER_INFO (info)) { + GList *tmp, *streams; + + streams = gst_discoverer_container_info_get_streams (GST_DISCOVERER_CONTAINER_INFO (info)); + for (tmp = streams; tmp; tmp = tmp->next) { + GstDiscovererStreamInfo *tmpinf = (GstDiscovererStreamInfo *) tmp->data; + print_topology (tmpinf, depth + 1); + } + gst_discoverer_stream_info_list_free (streams); + } +} + +/* This function is called every time the discoverer has information regarding + * one of the URIs we provided.*/ +static void on_discovered_cb (GstDiscoverer *discoverer, GstDiscovererInfo *info, GError *err, CustomData *data) { + GstDiscovererResult result; + const gchar *uri; + const GstTagList *tags; + GstDiscovererStreamInfo *sinfo; + + uri = gst_discoverer_info_get_uri (info); + result = gst_discoverer_info_get_result (info); + switch (result) { + case GST_DISCOVERER_URI_INVALID: + g_print ("Invalid URI '%s'\n", uri); + break; + case GST_DISCOVERER_ERROR: + g_print ("Discoverer error: %s\n", err->message); + break; + case GST_DISCOVERER_TIMEOUT: + g_print ("Timeout\n"); + break; + case GST_DISCOVERER_BUSY: + g_print ("Busy\n"); + break; + case GST_DISCOVERER_MISSING_PLUGINS:{ + const GstStructure *s; + gchar *str; + + s = gst_discoverer_info_get_misc (info); + str = gst_structure_to_string (s); + + g_print ("Missing plugins: %s\n", str); + g_free (str); + break; + } + case GST_DISCOVERER_OK: + g_print ("Discovered '%s'\n", uri); + break; + } + + if (result != GST_DISCOVERER_OK) { + g_printerr ("This URI cannot be played\n"); + return; + } + + /* If we got no error, show the retrieved information */ + + g_print ("\nDuration: %" GST_TIME_FORMAT "\n", GST_TIME_ARGS (gst_discoverer_info_get_duration (info))); + + tags = gst_discoverer_info_get_tags (info); + if (tags) { + g_print ("Tags:\n"); + gst_tag_list_foreach (tags, print_tag_foreach, GINT_TO_POINTER (1)); + } + + g_print ("Seekable: %s\n", (gst_discoverer_info_get_seekable (info) ? "yes" : "no")); + + g_print ("\n"); + + sinfo = gst_discoverer_info_get_stream_info (info); + if (!sinfo) + return; + + g_print ("Stream information:\n"); + + print_topology (sinfo, 1); + + gst_discoverer_stream_info_unref (sinfo); + + g_print ("\n"); +} + +/* This function is called when the discoverer has finished examining + * all the URIs we provided.*/ +static void on_finished_cb (GstDiscoverer *discoverer, CustomData *data) { + g_print ("Finished discovering\n"); + + g_main_loop_quit (data->loop); +} + +int main (int argc, char **argv) { + CustomData data; + GError *err = NULL; + gchar *uri = "file:///home/ye/Music/4.wav"; + + /* if a URI was provided, use it instead of the default one */ + if (argc > 1) { + uri = argv[1]; + } + + /* Initialize cumstom data structure */ + memset (&data, 0, sizeof (data)); + + /* Initialize GStreamer */ + gst_init (&argc, &argv); + + g_print ("Discovering '%s'\n", uri); + + /* Instantiate the Discoverer */ + data.discoverer = gst_discoverer_new (5 * GST_SECOND, &err); + if (!data.discoverer) { + g_print ("Error creating discoverer instance: %s\n", err->message); + g_clear_error (&err); + return -1; + } + + /* Connect to the interesting signals */ + g_signal_connect (data.discoverer, "discovered", G_CALLBACK (on_discovered_cb), &data); + g_signal_connect (data.discoverer, "finished", G_CALLBACK (on_finished_cb), &data); + + /* Start the discoverer process (nothing to do yet) */ + gst_discoverer_start (data.discoverer); + + /* Add a request to process asynchronously the URI passed through the command line */ + if (!gst_discoverer_discover_uri_async (data.discoverer, uri)) { + g_print ("Failed to start discovering URI '%s'\n", uri); + g_object_unref (data.discoverer); + return -1; + } + + /* Create a GLib Main Loop and set it to run, so we can wait for the signals */ + data.loop = g_main_loop_new (NULL, FALSE); + g_main_loop_run (data.loop); + + /* Stop the discoverer process */ + gst_discoverer_stop (data.discoverer); + + /* Free resources */ + g_object_unref (data.discoverer); + g_main_loop_unref (data.loop); + + return 0; +} + diff --git a/tutorial/readme b/tutorial/readme new file mode 100644 index 0000000..1920eb5 --- /dev/null +++ b/tutorial/readme @@ -0,0 +1,9 @@ +Abstract: + 2: insualization. + 3: A simple player we can get media status. + *4: A simple player that displaying rate of progress. + *5: GUI toolkit integrate. + 9: gather informations about media. + 12: A simple player nothing information and insualization. + *13: A simple player that we can control by command. +