docs: link bus and tasks
[platform/upstream/gstreamer.git] / gst / gsttask.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2005 Wim Taymans <wim@fluendo.com>
4  *
5  * gsttask.c: Streaming tasks
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /**
24  * SECTION:gsttask
25  * @short_description: Abstraction of GStreamer streaming threads.
26  * @see_also: #GstElement, #GstPad
27  *
28  * #GstTask is used by #GstElement and #GstPad to provide the data passing
29  * threads in a #GstPipeline.
30  *
31  * A #GstPad will typically start a #GstTask to push or pull data to/from the
32  * peer pads. Most source elements start a #GstTask to push data. In some cases
33  * a demuxer element can start a #GstTask to pull data from a peer element. This
34  * is typically done when the demuxer can perform random access on the upstream
35  * peer element for improved performance.
36  *
37  * Although convenience functions exist on #GstPad to start/pause/stop tasks, it 
38  * might sometimes be needed to create a #GstTask manually if it is not related to
39  * a #GstPad.
40  *
41  * Before the #GstTask can be run, it needs a #GStaticRecMutex that can be set with
42  * gst_task_set_lock().
43  *
44  * The task can be started, paused and stopped with gst_task_start(), gst_task_pause()
45  * and gst_task_stop() respectively or with the gst_task_set_state() function.
46  *
47  * A #GstTask will repeatedly call the #GstTaskFunction with the user data
48  * that was provided when creating the task with gst_task_create(). While calling
49  * the function it will acquire the provided lock. The provided lock is released
50  * when the task pauses or stops.
51  *
52  * Stopping a task with gst_task_stop() will not immediately make sure the task is
53  * not running anymore. Use gst_task_join() to make sure the task is completely
54  * stopped and the thread is stopped.
55  *
56  * After creating a #GstTask, use gst_object_unref() to free its resources. This can
57  * only be done it the task is not running anymore.
58  *
59  * Task functions can send a #GstMessage to send out-of-band data to the
60  * application. The application can receive messages from the #GstBus in its
61  * mainloop.
62  *
63  * Last reviewed on 2006-02-13 (0.10.4)
64  */
65
66 #include "gst_private.h"
67
68 #include "gstinfo.h"
69 #include "gsttask.h"
70
71 GST_DEBUG_CATEGORY_STATIC (task_debug);
72 #define GST_CAT_DEFAULT (task_debug)
73
74 #define GST_TASK_GET_PRIVATE(obj)  \
75    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_TASK, GstTaskPrivate))
76
77 struct _GstTaskPrivate
78 {
79   /* callbacks for managing the thread of this task */
80   GstTaskThreadCallbacks thr_callbacks;
81   gpointer thr_user_data;
82   GDestroyNotify thr_notify;
83
84   gboolean prio_set;
85   GThreadPriority priority;
86
87   /* configured pool */
88   GstTaskPool *pool;
89
90   /* remember the pool and id that is currently running. */
91   gpointer id;
92   GstTaskPool *pool_id;
93 };
94
95 static void gst_task_class_init (GstTaskClass * klass);
96 static void gst_task_init (GstTask * task);
97 static void gst_task_finalize (GObject * object);
98
99 static void gst_task_func (GstTask * task);
100
101 static GStaticMutex pool_lock = G_STATIC_MUTEX_INIT;
102
103 #define _do_init \
104 { \
105   GST_DEBUG_CATEGORY_INIT (task_debug, "task", 0, "Processing tasks"); \
106 }
107
108 G_DEFINE_TYPE_WITH_CODE (GstTask, gst_task, GST_TYPE_OBJECT, _do_init);
109
110 static void
111 init_klass_pool (GstTaskClass * klass)
112 {
113   g_static_mutex_lock (&pool_lock);
114   if (klass->pool) {
115     gst_task_pool_cleanup (klass->pool);
116     gst_object_unref (klass->pool);
117   }
118   klass->pool = gst_task_pool_new ();
119   gst_task_pool_prepare (klass->pool, NULL);
120   g_static_mutex_unlock (&pool_lock);
121 }
122
123 static void
124 gst_task_class_init (GstTaskClass * klass)
125 {
126   GObjectClass *gobject_class;
127
128   gobject_class = (GObjectClass *) klass;
129
130   g_type_class_add_private (klass, sizeof (GstTaskPrivate));
131
132   gobject_class->finalize = gst_task_finalize;
133
134   init_klass_pool (klass);
135 }
136
137 static void
138 gst_task_init (GstTask * task)
139 {
140   GstTaskClass *klass;
141
142   klass = GST_TASK_GET_CLASS (task);
143
144   task->priv = GST_TASK_GET_PRIVATE (task);
145   task->running = FALSE;
146   task->abidata.ABI.thread = NULL;
147   task->lock = NULL;
148   task->cond = g_cond_new ();
149   task->state = GST_TASK_STOPPED;
150   task->priv->prio_set = FALSE;
151
152   /* use the default klass pool for this task, users can
153    * override this later */
154   g_static_mutex_lock (&pool_lock);
155   task->priv->pool = gst_object_ref (klass->pool);
156   g_static_mutex_unlock (&pool_lock);
157 }
158
159 static void
160 gst_task_finalize (GObject * object)
161 {
162   GstTask *task = GST_TASK (object);
163   GstTaskPrivate *priv = task->priv;
164
165   GST_DEBUG ("task %p finalize", task);
166
167   if (priv->thr_notify)
168     priv->thr_notify (priv->thr_user_data);
169   priv->thr_notify = NULL;
170   priv->thr_user_data = NULL;
171
172   gst_object_unref (priv->pool);
173
174   /* task thread cannot be running here since it holds a ref
175    * to the task so that the finalize could not have happened */
176   g_cond_free (task->cond);
177   task->cond = NULL;
178
179   G_OBJECT_CLASS (gst_task_parent_class)->finalize (object);
180 }
181
182 static void
183 gst_task_func (GstTask * task)
184 {
185   GStaticRecMutex *lock;
186   GThread *tself;
187   GstTaskPrivate *priv;
188
189   priv = task->priv;
190
191   tself = g_thread_self ();
192
193   GST_DEBUG ("Entering task %p, thread %p", task, tself);
194
195   /* we have to grab the lock to get the mutex. We also
196    * mark our state running so that nobody can mess with
197    * the mutex. */
198   GST_OBJECT_LOCK (task);
199   if (task->state == GST_TASK_STOPPED)
200     goto exit;
201   lock = GST_TASK_GET_LOCK (task);
202   if (G_UNLIKELY (lock == NULL))
203     goto no_lock;
204   task->abidata.ABI.thread = tself;
205   /* only update the priority when it was changed */
206   if (priv->prio_set)
207     g_thread_set_priority (tself, priv->priority);
208   GST_OBJECT_UNLOCK (task);
209
210   /* fire the enter_thread callback when we need to */
211   if (priv->thr_callbacks.enter_thread)
212     priv->thr_callbacks.enter_thread (task, tself, priv->thr_user_data);
213
214   /* locking order is TASK_LOCK, LOCK */
215   g_static_rec_mutex_lock (lock);
216   GST_OBJECT_LOCK (task);
217   while (G_LIKELY (task->state != GST_TASK_STOPPED)) {
218     while (G_UNLIKELY (task->state == GST_TASK_PAUSED)) {
219       gint t;
220
221       t = g_static_rec_mutex_unlock_full (lock);
222       if (t <= 0) {
223         g_warning ("wrong STREAM_LOCK count %d", t);
224       }
225       GST_TASK_SIGNAL (task);
226       GST_TASK_WAIT (task);
227       GST_OBJECT_UNLOCK (task);
228       /* locking order.. */
229       if (t > 0)
230         g_static_rec_mutex_lock_full (lock, t);
231
232       GST_OBJECT_LOCK (task);
233       if (G_UNLIKELY (task->state == GST_TASK_STOPPED))
234         goto done;
235     }
236     GST_OBJECT_UNLOCK (task);
237
238     task->func (task->data);
239
240     GST_OBJECT_LOCK (task);
241   }
242 done:
243   GST_OBJECT_UNLOCK (task);
244   g_static_rec_mutex_unlock (lock);
245
246   GST_OBJECT_LOCK (task);
247   task->abidata.ABI.thread = NULL;
248
249 exit:
250   if (priv->thr_callbacks.leave_thread) {
251     /* fire the leave_thread callback when we need to. We need to do this before
252      * we signal the task and with the task lock released. */
253     GST_OBJECT_UNLOCK (task);
254     priv->thr_callbacks.leave_thread (task, tself, priv->thr_user_data);
255     GST_OBJECT_LOCK (task);
256   } else {
257     /* restore normal priority when releasing back into the pool, we will not
258      * touch the priority when a custom callback has been installed. */
259     g_thread_set_priority (tself, G_THREAD_PRIORITY_NORMAL);
260   }
261   /* now we allow messing with the lock again by setting the running flag to
262    * FALSE. Together with the SIGNAL this is the sign for the _join() to 
263    * complete. 
264    * Note that we still have not dropped the final ref on the task. We could
265    * check here if there is a pending join() going on and drop the last ref
266    * before releasing the lock as we can be sure that a ref is held by the
267    * caller of the join(). */
268   task->running = FALSE;
269   GST_TASK_SIGNAL (task);
270   GST_OBJECT_UNLOCK (task);
271
272   GST_DEBUG ("Exit task %p, thread %p", task, g_thread_self ());
273
274   gst_object_unref (task);
275   return;
276
277 no_lock:
278   {
279     g_warning ("starting task without a lock");
280     goto exit;
281   }
282 }
283
284 /**
285  * gst_task_cleanup_all:
286  *
287  * Wait for all tasks to be stopped. This is mainly used internally
288  * to ensure proper cleanup of internal data structures in test suites.
289  *
290  * MT safe.
291  */
292 void
293 gst_task_cleanup_all (void)
294 {
295   GstTaskClass *klass;
296
297   if ((klass = g_type_class_peek (GST_TYPE_TASK))) {
298     init_klass_pool (klass);
299   }
300 }
301
302 /**
303  * gst_task_create:
304  * @func: The #GstTaskFunction to use
305  * @data: User data to pass to @func
306  *
307  * Create a new Task that will repeatedly call the provided @func
308  * with @data as a parameter. Typically the task will run in
309  * a new thread.
310  *
311  * The function cannot be changed after the task has been created. You
312  * must create a new #GstTask to change the function.
313  *
314  * This function will not yet create and start a thread. Use gst_task_start() or
315  * gst_task_pause() to create and start the GThread.
316  *
317  * Before the task can be used, a #GStaticRecMutex must be configured using the
318  * gst_task_set_lock() function. This lock will always be acquired while
319  * @func is called.
320  *
321  * Returns: A new #GstTask.
322  *
323  * MT safe.
324  */
325 GstTask *
326 gst_task_create (GstTaskFunction func, gpointer data)
327 {
328   GstTask *task;
329
330   task = g_object_newv (GST_TYPE_TASK, 0, NULL);
331   task->func = func;
332   task->data = data;
333
334   GST_DEBUG ("Created task %p", task);
335
336   return task;
337 }
338
339 /**
340  * gst_task_set_lock:
341  * @task: The #GstTask to use
342  * @mutex: The #GMutex to use
343  *
344  * Set the mutex used by the task. The mutex will be acquired before
345  * calling the #GstTaskFunction.
346  *
347  * This function has to be called before calling gst_task_pause() or
348  * gst_task_start().
349  *
350  * MT safe.
351  */
352 void
353 gst_task_set_lock (GstTask * task, GStaticRecMutex * mutex)
354 {
355   GST_OBJECT_LOCK (task);
356   if (G_UNLIKELY (task->running))
357     goto is_running;
358   GST_TASK_GET_LOCK (task) = mutex;
359   GST_OBJECT_UNLOCK (task);
360
361   return;
362
363   /* ERRORS */
364 is_running:
365   {
366     GST_OBJECT_UNLOCK (task);
367     g_warning ("cannot call set_lock on a running task");
368   }
369 }
370
371 /**
372  * gst_task_set_priority:
373  * @task: a #GstTask
374  * @priority: a new priority for @task
375  *
376  * Changes the priority of @task to @priority.
377  *
378  * Note: try not to depend on task priorities.
379  *
380  * MT safe.
381  *
382  * Since: 0.10.24
383  */
384 void
385 gst_task_set_priority (GstTask * task, GThreadPriority priority)
386 {
387   GstTaskPrivate *priv;
388   GThread *thread;
389
390   g_return_if_fail (GST_IS_TASK (task));
391
392   priv = task->priv;
393
394   GST_OBJECT_LOCK (task);
395   priv->prio_set = TRUE;
396   priv->priority = priority;
397   thread = task->abidata.ABI.thread;
398   if (thread != NULL) {
399     /* if this task already has a thread, we can configure the priority right
400      * away, else we do that when we assign a thread to the task. */
401     g_thread_set_priority (thread, priority);
402   }
403   GST_OBJECT_UNLOCK (task);
404 }
405
406 /**
407  * gst_task_get_pool:
408  * @task: a #GstTask
409  *
410  * Get the #GstTaskPool that this task will use for its streaming
411  * threads.
412  *
413  * MT safe.
414  *
415  * Returns: the #GstTaskPool used by @task. gst_object_unref()
416  * after usage.
417  *
418  * Since: 0.10.24
419  */
420 GstTaskPool *
421 gst_task_get_pool (GstTask * task)
422 {
423   GstTaskPool *result;
424   GstTaskPrivate *priv;
425
426   g_return_val_if_fail (GST_IS_TASK (task), NULL);
427
428   priv = task->priv;
429
430   GST_OBJECT_LOCK (task);
431   result = gst_object_ref (priv->pool);
432   GST_OBJECT_UNLOCK (task);
433
434   return result;
435 }
436
437 /**
438  * gst_task_set_pool:
439  * @task: a #GstTask
440  * @pool: a #GstTaskPool
441  *
442  * Set @pool as the new GstTaskPool for @task. Any new streaming threads that
443  * will be created by @task will now use @pool.
444  *
445  * MT safe.
446  *
447  * Since: 0.10.24
448  */
449 void
450 gst_task_set_pool (GstTask * task, GstTaskPool * pool)
451 {
452   GstTaskPool *old;
453   GstTaskPrivate *priv;
454
455   g_return_if_fail (GST_IS_TASK (task));
456   g_return_if_fail (GST_IS_TASK_POOL (pool));
457
458   priv = task->priv;
459
460   GST_OBJECT_LOCK (task);
461   if (priv->pool != pool) {
462     old = priv->pool;
463     priv->pool = gst_object_ref (pool);
464   } else
465     old = NULL;
466   GST_OBJECT_UNLOCK (task);
467
468   if (old)
469     gst_object_unref (old);
470 }
471
472
473 /**
474  * gst_task_set_thread_callbacks:
475  * @task: The #GstTask to use
476  * @callbacks: a #GstTaskThreadCallbacks pointer
477  * @user_data: user data passed to the callbacks
478  * @notify: called when @user_data is no longer referenced
479  *
480  * Set callbacks which will be executed when a new thread is needed, the thread
481  * function is entered and left and when the thread is joined.
482  *
483  * By default a thread for @task will be created from a default thread pool.
484  *
485  * Objects can use custom GThreads or can perform additional configuration of
486  * the threads (such as changing the thread priority) by installing callbacks.
487  *
488  * MT safe.
489  *
490  * Since: 0.10.24
491  */
492 void
493 gst_task_set_thread_callbacks (GstTask * task,
494     GstTaskThreadCallbacks * callbacks, gpointer user_data,
495     GDestroyNotify notify)
496 {
497   GDestroyNotify old_notify;
498
499   g_return_if_fail (task != NULL);
500   g_return_if_fail (GST_IS_TASK (task));
501   g_return_if_fail (callbacks != NULL);
502
503   GST_OBJECT_LOCK (task);
504   old_notify = task->priv->thr_notify;
505
506   if (old_notify) {
507     gpointer old_data;
508
509     old_data = task->priv->thr_user_data;
510
511     task->priv->thr_user_data = NULL;
512     task->priv->thr_notify = NULL;
513     GST_OBJECT_UNLOCK (task);
514
515     old_notify (old_data);
516
517     GST_OBJECT_LOCK (task);
518   }
519   task->priv->thr_callbacks = *callbacks;
520   task->priv->thr_user_data = user_data;
521   task->priv->thr_notify = notify;
522   GST_OBJECT_UNLOCK (task);
523 }
524
525 /**
526  * gst_task_get_state:
527  * @task: The #GstTask to query
528  *
529  * Get the current state of the task.
530  *
531  * Returns: The #GstTaskState of the task
532  *
533  * MT safe.
534  */
535 GstTaskState
536 gst_task_get_state (GstTask * task)
537 {
538   GstTaskState result;
539
540   g_return_val_if_fail (GST_IS_TASK (task), GST_TASK_STOPPED);
541
542   GST_OBJECT_LOCK (task);
543   result = task->state;
544   GST_OBJECT_UNLOCK (task);
545
546   return result;
547 }
548
549 /* make sure the task is running and start a thread if it's not.
550  * This function must be called with the task LOCK. */
551 static gboolean
552 start_task (GstTask * task)
553 {
554   gboolean res = TRUE;
555   GError *error = NULL;
556   GstTaskPrivate *priv;
557
558   priv = task->priv;
559
560   /* new task, We ref before so that it remains alive while
561    * the thread is running. */
562   gst_object_ref (task);
563   /* mark task as running so that a join will wait until we schedule
564    * and exit the task function. */
565   task->running = TRUE;
566
567   /* push on the thread pool, we remember the original pool because the user
568    * could change it later on and then we join to the wrong pool. */
569   priv->pool_id = gst_object_ref (priv->pool);
570   priv->id =
571       gst_task_pool_push (priv->pool_id, (GstTaskPoolFunction) gst_task_func,
572       task, &error);
573
574   if (error != NULL) {
575     g_warning ("failed to create thread: %s", error->message);
576     g_error_free (error);
577     res = FALSE;
578   }
579   return res;
580 }
581
582
583 /**
584  * gst_task_set_state:
585  * @task: a #GstTask
586  * @state: the new task state
587  *
588  * Sets the state of @task to @state.
589  *
590  * The @task must have a lock associated with it using
591  * gst_task_set_lock() when going to GST_TASK_STARTED or GST_TASK_PAUSED or
592  * this function will return %FALSE.
593  *
594  * MT safe.
595  *
596  * Returns: %TRUE if the state could be changed.
597  *
598  * Since: 0.10.24
599  */
600 gboolean
601 gst_task_set_state (GstTask * task, GstTaskState state)
602 {
603   GstTaskState old;
604   gboolean res = TRUE;
605
606   g_return_val_if_fail (GST_IS_TASK (task), FALSE);
607
608   GST_DEBUG_OBJECT (task, "Changing task %p to state %d", task, state);
609
610   GST_OBJECT_LOCK (task);
611   if (state != GST_TASK_STOPPED)
612     if (G_UNLIKELY (GST_TASK_GET_LOCK (task) == NULL))
613       goto no_lock;
614
615   /* if the state changed, do our thing */
616   old = task->state;
617   if (old != state) {
618     task->state = state;
619     switch (old) {
620       case GST_TASK_STOPPED:
621         /* If the task already has a thread scheduled we don't have to do
622          * anything. */
623         if (G_UNLIKELY (!task->running))
624           res = start_task (task);
625         break;
626       case GST_TASK_PAUSED:
627         /* when we are paused, signal to go to the new state */
628         GST_TASK_SIGNAL (task);
629         break;
630       case GST_TASK_STARTED:
631         /* if we were started, we'll go to the new state after the next
632          * iteration. */
633         break;
634     }
635   }
636   GST_OBJECT_UNLOCK (task);
637
638   return res;
639
640   /* ERRORS */
641 no_lock:
642   {
643     GST_WARNING_OBJECT (task, "state %d set on task without a lock", state);
644     GST_OBJECT_UNLOCK (task);
645     g_warning ("task without a lock can't be set to state %d", state);
646     return FALSE;
647   }
648 }
649
650 /**
651  * gst_task_start:
652  * @task: The #GstTask to start
653  *
654  * Starts @task. The @task must have a lock associated with it using
655  * gst_task_set_lock() or this function will return %FALSE.
656  *
657  * Returns: %TRUE if the task could be started.
658  *
659  * MT safe.
660  */
661 gboolean
662 gst_task_start (GstTask * task)
663 {
664   return gst_task_set_state (task, GST_TASK_STARTED);
665 }
666
667 /**
668  * gst_task_stop:
669  * @task: The #GstTask to stop
670  *
671  * Stops @task. This method merely schedules the task to stop and
672  * will not wait for the task to have completely stopped. Use
673  * gst_task_join() to stop and wait for completion.
674  *
675  * Returns: %TRUE if the task could be stopped.
676  *
677  * MT safe.
678  */
679 gboolean
680 gst_task_stop (GstTask * task)
681 {
682   return gst_task_set_state (task, GST_TASK_STOPPED);
683 }
684
685 /**
686  * gst_task_pause:
687  * @task: The #GstTask to pause
688  *
689  * Pauses @task. This method can also be called on a task in the
690  * stopped state, in which case a thread will be started and will remain
691  * in the paused state. This function does not wait for the task to complete
692  * the paused state.
693  *
694  * Returns: %TRUE if the task could be paused.
695  *
696  * MT safe.
697  */
698 gboolean
699 gst_task_pause (GstTask * task)
700 {
701   return gst_task_set_state (task, GST_TASK_PAUSED);
702 }
703
704 /**
705  * gst_task_join:
706  * @task: The #GstTask to join
707  *
708  * Joins @task. After this call, it is safe to unref the task
709  * and clean up the lock set with gst_task_set_lock().
710  *
711  * The task will automatically be stopped with this call.
712  *
713  * This function cannot be called from within a task function as this
714  * would cause a deadlock. The function will detect this and print a 
715  * g_warning.
716  *
717  * Returns: %TRUE if the task could be joined.
718  *
719  * MT safe.
720  */
721 gboolean
722 gst_task_join (GstTask * task)
723 {
724   GThread *tself;
725   GstTaskPrivate *priv;
726   gpointer id;
727   GstTaskPool *pool = NULL;
728
729   priv = task->priv;
730
731   g_return_val_if_fail (GST_IS_TASK (task), FALSE);
732
733   tself = g_thread_self ();
734
735   GST_DEBUG_OBJECT (task, "Joining task %p, thread %p", task, tself);
736
737   /* we don't use a real thread join here because we are using
738    * thread pools */
739   GST_OBJECT_LOCK (task);
740   if (G_UNLIKELY (tself == task->abidata.ABI.thread))
741     goto joining_self;
742   task->state = GST_TASK_STOPPED;
743   /* signal the state change for when it was blocked in PAUSED. */
744   GST_TASK_SIGNAL (task);
745   /* we set the running flag when pushing the task on the thread pool.
746    * This means that the task function might not be called when we try
747    * to join it here. */
748   while (G_LIKELY (task->running))
749     GST_TASK_WAIT (task);
750   /* clean the thread */
751   task->abidata.ABI.thread = NULL;
752   /* get the id and pool to join */
753   pool = priv->pool_id;
754   id = priv->id;
755   priv->pool_id = NULL;
756   priv->id = NULL;
757   GST_OBJECT_UNLOCK (task);
758
759   if (pool) {
760     if (id)
761       gst_task_pool_join (pool, id);
762     gst_object_unref (pool);
763   }
764
765   GST_DEBUG_OBJECT (task, "Joined task %p", task);
766
767   return TRUE;
768
769   /* ERRORS */
770 joining_self:
771   {
772     GST_WARNING_OBJECT (task, "trying to join task from its thread");
773     GST_OBJECT_UNLOCK (task);
774     g_warning ("\nTrying to join task %p from its thread would deadlock.\n"
775         "You cannot change the state of an element from its streaming\n"
776         "thread. Use g_idle_add() or post a GstMessage on the bus to\n"
777         "schedule the state change from the main thread.\n", task);
778     return FALSE;
779   }
780 }