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