s/ffmpegcolorspace/videoconvert/ in a few places
[platform/upstream/gstreamer.git] / sdk-basic-tutorial-playback-speed.md
1 # Basic tutorial 13: Playback speed
2
3 ## Goal
4
5 Fast-forward, reverse-playback and slow-motion are all techniques
6 collectively known as *trick modes* and they all have in common that
7 modify the normal playback rate. This tutorial shows how to achieve
8 these effects and adds frame-stepping into the deal. In particular, it
9 shows:
10
11   - How to change the playback rate, faster and slower than normal,
12     forward and backwards.
13   - How to advance a video frame-by-frame
14
15 ## Introduction
16
17 Fast-forward is the technique that plays a media at a speed higher than
18 its normal (intended) speed; whereas slow-motion uses a speed lower than
19 the intended one. Reverse playback does the same thing but backwards,
20 from the end of the stream to the beginning.
21
22 All these techniques do is change the playback rate, which is a variable
23 equal to 1.0 for normal playback, greater than 1.0 (in absolute value)
24 for fast modes, lower than 1.0 (in absolute value) for slow modes,
25 positive for forward playback and negative for reverse playback.
26
27 GStreamer provides two mechanisms to change the playback rate: Step
28 Events and Seek Events. Step Events allow skipping a given amount of
29 media besides changing the subsequent playback rate (only to positive
30 values). Seek Events, additionally, allow jumping to any position in the
31 stream and set positive and negative playback rates.
32
33 In [](sdk-basic-tutorial-time-management.md) seek
34 events have already been shown, using a helper function to hide their
35 complexity. This tutorial explains a bit more how to use these events.
36
37 Step Events are a more convenient way of changing the playback rate, due
38 to the reduced number of parameters needed to create them; however,
39 their implementation in GStreamer still needs a bit more polishing
40 so Seek Events are used in this tutorial instead.
41 **FIXME: Is that even true ???**
42
43 To use these events, they are created and then passed onto the pipeline,
44 where they propagate upstream until they reach an element that can
45 handle them. If an event is passed onto a bin element like `playbin`,
46 it will simply feed the event to all its sinks, which will result in
47 multiple seeks being performed. The common approach is to retrieve one
48 of `playbin`’s sinks through the `video-sink` or
49 `audio-sink` properties and feed the event directly into the sink.
50
51 Frame stepping is a technique that allows playing a video frame by
52 frame. It is implemented by pausing the pipeline, and then sending Step
53 Events to skip one frame each time.
54
55 ## A trick mode player
56
57 Copy this code into a text file named `basic-tutorial-13.c`.
58
59 **basic-tutorial-13.c**
60
61 ``` c
62 #include <string.h>
63 #include <stdio.h>
64 #include <gst/gst.h>
65
66 typedef struct _CustomData {
67   GstElement *pipeline;
68   GstElement *video_sink;
69   GMainLoop *loop;
70
71   gboolean playing;  /* Playing or Paused */
72   gdouble rate;      /* Current playback rate (can be negative) */
73 } CustomData;
74
75 /* Send seek event to change rate */
76 static void send_seek_event (CustomData *data) {
77   gint64 position;
78   GstFormat format = GST_FORMAT_TIME;
79   GstEvent *seek_event;
80
81   /* Obtain the current position, needed for the seek event */
82   if (!gst_element_query_position (data->pipeline, &format, &position)) {
83     g_printerr ("Unable to retrieve current position.\n");
84     return;
85   }
86
87   /* Create the seek event */
88   if (data->rate > 0) {
89     seek_event = gst_event_new_seek (data->rate, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
90         GST_SEEK_TYPE_SET, position, GST_SEEK_TYPE_NONE, 0);
91   } else {
92     seek_event = gst_event_new_seek (data->rate, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
93         GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_SET, position);
94   }
95
96   if (data->video_sink == NULL) {
97     /* If we have not done so, obtain the sink through which we will send the seek events */
98     g_object_get (data->pipeline, "video-sink", &data->video_sink, NULL);
99   }
100
101   /* Send the event */
102   gst_element_send_event (data->video_sink, seek_event);
103
104   g_print ("Current rate: %g\n", data->rate);
105 }
106
107 /* Process keyboard input */
108 static gboolean handle_keyboard (GIOChannel *source, GIOCondition cond, CustomData *data) {
109   gchar *str = NULL;
110
111   if (g_io_channel_read_line (source, &str, NULL, NULL, NULL) != G_IO_STATUS_NORMAL) {
112     return TRUE;
113   }
114
115   switch (g_ascii_tolower (str[0])) {
116   case 'p':
117     data->playing = !data->playing;
118     gst_element_set_state (data->pipeline, data->playing ? GST_STATE_PLAYING : GST_STATE_PAUSED);
119     g_print ("Setting state to %s\n", data->playing ? "PLAYING" : "PAUSE");
120     break;
121   case 's':
122     if (g_ascii_isupper (str[0])) {
123       data->rate *= 2.0;
124     } else {
125       data->rate /= 2.0;
126     }
127     send_seek_event (data);
128     break;
129   case 'd':
130     data->rate *= -1.0;
131     send_seek_event (data);
132     break;
133   case 'n':
134     if (data->video_sink == NULL) {
135       /* If we have not done so, obtain the sink through which we will send the step events */
136       g_object_get (data->pipeline, "video-sink", &data->video_sink, NULL);
137     }
138
139     gst_element_send_event (data->video_sink,
140         gst_event_new_step (GST_FORMAT_BUFFERS, 1, data->rate, TRUE, FALSE));
141     g_print ("Stepping one frame\n");
142     break;
143   case 'q':
144     g_main_loop_quit (data->loop);
145     break;
146   default:
147     break;
148   }
149
150   g_free (str);
151
152   return TRUE;
153 }
154
155 int main(int argc, char *argv[]) {
156   CustomData data;
157   GstStateChangeReturn ret;
158   GIOChannel *io_stdin;
159
160   /* Initialize GStreamer */
161   gst_init (&argc, &argv);
162
163   /* Initialize our data structure */
164   memset (&data, 0, sizeof (data));
165
166   /* Print usage map */
167   g_print (
168     "USAGE: Choose one of the following options, then press enter:\n"
169     " 'P' to toggle between PAUSE and PLAY\n"
170     " 'S' to increase playback speed, 's' to decrease playback speed\n"
171     " 'D' to toggle playback direction\n"
172     " 'N' to move to next frame (in the current direction, better in PAUSE)\n"
173     " 'Q' to quit\n");
174
175   /* Build the pipeline */
176   data.pipeline = gst_parse_launch ("playbin uri=http://docs.gstreamer.com/media/sintel_trailer-480p.webm", NULL);
177
178   /* Add a keyboard watch so we get notified of keystrokes */
179 #ifdef G_OS_WIN32
180   io_stdin = g_io_channel_win32_new_fd (fileno (stdin));
181 #else
182   io_stdin = g_io_channel_unix_new (fileno (stdin));
183 #endif
184   g_io_add_watch (io_stdin, G_IO_IN, (GIOFunc)handle_keyboard, &data);
185
186   /* Start playing */
187   ret = gst_element_set_state (data.pipeline, GST_STATE_PLAYING);
188   if (ret == GST_STATE_CHANGE_FAILURE) {
189     g_printerr ("Unable to set the pipeline to the playing state.\n");
190     gst_object_unref (data.pipeline);
191     return -1;
192   }
193   data.playing = TRUE;
194   data.rate = 1.0;
195
196   /* Create a GLib Main Loop and set it to run */
197   data.loop = g_main_loop_new (NULL, FALSE);
198   g_main_loop_run (data.loop);
199
200   /* Free resources */
201   g_main_loop_unref (data.loop);
202   g_io_channel_unref (io_stdin);
203   gst_element_set_state (data.pipeline, GST_STATE_NULL);
204   if (data.video_sink != NULL)
205     gst_object_unref (data.video_sink);
206   gst_object_unref (data.pipeline);
207   return 0;
208 }
209 ```
210
211
212 > ![Information](images/icons/emoticons/information.png)
213 > Need help?
214 >
215 > If you need help to compile this code, refer to the **Building the tutorials**  section for your platform: [Linux](sdk-installing-on-linux.md#InstallingonLinux-Build), [Mac OS X](sdk-installing-on-mac-osx.md#InstallingonMacOSX-Build) or [Windows](sdk-installing-on-windows.mdb#InstallingonWindows-Build), or use this specific command on Linux:
216 >
217 > `` gcc basic-tutorial-13.c -o basic-tutorial-13 `pkg-config --cflags --libs gstreamer-1.0` ``
218 >
219 >If you need help to run this code, refer to the **Running the tutorials** section for your platform: [Linux](sdk-installing-on-linux.md#InstallingonLinux-Run), [Mac OS X](sdk-installing-on-mac-osx.md#InstallingonMacOSX-Run) or [Windows](sdk-installing-on-windows.md#InstallingonWindows-Run).
220 >
221 > This tutorial opens a window and displays a movie, with accompanying audio. The media is fetched from the Internet, so the window might take a few seconds to appear, depending on your connection speed. The console shows the available commands, composed of a single upper-case or lower-case letter, which you should input followed by the Enter key.
222 >
223 > Required libraries: `gstreamer-1.0`
224
225 ## Walkthrough
226
227 There is nothing new in the initialization code in the main function:  a
228 `playbin` pipeline is instantiated, an I/O watch is installed to track
229 keystrokes and a GLib main loop is executed.
230
231 Then, in the keyboard handler function:
232
233 ``` c
234 /* Process keyboard input */
235 static gboolean handle_keyboard (GIOChannel *source, GIOCondition cond, CustomData *data) {
236   gchar *str = NULL;
237
238   if (g_io_channel_read_line (source, &str, NULL, NULL, NULL) != G_IO_STATUS_NORMAL) {
239     return TRUE;
240   }
241
242   switch (g_ascii_tolower (str[0])) {
243   case 'p':
244     data->playing = !data->playing;
245     gst_element_set_state (data->pipeline, data->playing ? GST_STATE_PLAYING : GST_STATE_PAUSED);
246     g_print ("Setting state to %s\n", data->playing ? "PLAYING" : "PAUSE");
247     break;
248 ```
249
250 Pause / Playing toggle is handled with `gst_element_set_state()` as in
251 previous tutorials.
252
253 ``` c
254 case 's':
255   if (g_ascii_isupper (str[0])) {
256     data->rate *= 2.0;
257   } else {
258     data->rate /= 2.0;
259   }
260   send_seek_event (data);
261   break;
262 case 'd':
263   data->rate *= -1.0;
264   send_seek_event (data);
265   break;
266 ```
267
268 Use ‘S’ and ‘s’ to double or halve the current playback rate, and ‘d’ to
269 reverse the current playback direction. In both cases, the
270 `rate` variable is updated and `send_seek_event` is called. Let’s
271 review this function.
272
273 ``` c
274 /* Send seek event to change rate */
275 static void send_seek_event (CustomData *data) {
276   gint64 position;
277   GstEvent *seek_event;
278
279   /* Obtain the current position, needed for the seek event */
280   if (!gst_element_query_position (data->pipeline, GST_FORMAT_TIME, &position)) {
281     g_printerr ("Unable to retrieve current position.\n");
282     return;
283   }
284 ```
285
286 This function creates a new Seek Event and sends it to the pipeline to
287 update the rate. First, the current position is recovered with
288 `gst_element_query_position()`. This is needed because the Seek Event
289 jumps to another position in the stream, and, since we do not actually
290 want to move, we jump to the current position. Using a Step Event would
291 be simpler, but this event is not currently fully functional, as
292 explained in the Introduction.
293
294 ``` c
295 /* Create the seek event */
296 if (data->rate > 0) {
297   seek_event = gst_event_new_seek (data->rate, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
298       GST_SEEK_TYPE_SET, position, GST_SEEK_TYPE_NONE, 0);
299 } else {
300   seek_event = gst_event_new_seek (data->rate, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
301       GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_SET, position);
302 }
303 ```
304
305 The Seek Event is created with `gst_event_new_seek()`. Its parameters
306 are, basically, the new rate, the new start position and the new stop
307 position. Regardless of the playback direction, the start position must
308 be smaller than the stop position, so the two playback directions are
309 treated differently.
310
311 ``` c
312 if (data->video_sink == NULL) {
313   /* If we have not done so, obtain the sink through which we will send the seek events */
314   g_object_get (data->pipeline, "video-sink", &data->video_sink, NULL);
315 }
316 ```
317
318 As explained in the Introduction, to avoid performing multiple Seeks,
319 the Event is sent to only one sink, in this case, the video sink. It is
320 obtained from `playbin` through the `video-sink` property. It is read
321 at this time instead at initialization time because the actual sink may
322 change depending on the media contents, and this won’t be known until
323 the pipeline is PLAYING and some media has been read.
324
325 ``` c
326 /* Send the event */
327 gst_element_send_event (data->video_sink, seek_event);
328 ```
329
330 The new Event is finally sent to the selected sink with
331 `gst_element_send_event()`.
332
333 Back to the keyboard handler, we still miss the frame stepping code,
334 which is really simple:
335
336 ``` c
337 case 'n':
338   if (data->video_sink == NULL) {
339     /* If we have not done so, obtain the sink through which we will send the step events */
340     g_object_get (data->pipeline, "video-sink", &data->video_sink, NULL);
341   }
342
343   gst_element_send_event (data->video_sink,
344       gst_event_new_step (GST_FORMAT_BUFFERS, 1, data->rate, TRUE, FALSE));
345   g_print ("Stepping one frame\n");
346   break;
347 ```
348
349 A new Step Event is created with `gst_event_new_step()`, whose
350 parameters basically specify the amount to skip (1 frame in the example)
351 and the new rate (which we do not change).
352
353 The video sink is grabbed from `playbin` in case we didn’t have it yet,
354 just like before.
355
356 And with this we are done. When testing this tutorial, keep in mind that
357 backward playback is not optimal in many elements.
358
359 > ![Warning](images/icons/emoticons/warning.png)
360 >
361 >Changing the playback rate might only work with local files. If you cannot modify it, try changing the URI passed to `playbin` in line 114 to a local URI, starting with `file:///`
362 </table>
363
364 ## Conclusion
365
366 This tutorial has shown:
367
368   - How to change the playback rate using a Seek Event, created with
369     `gst_event_new_seek()` and fed to the pipeline
370     with `gst_element_send_event()`.
371   - How to advance a video frame-by-frame by using Step Events, created
372     with `gst_event_new_step()`.
373
374 It has been a pleasure having you here, and see you soon!