b28d892909a8a1800e721a6a87afc05e73ad31f6
[platform/upstream/gstreamer.git] / gst / gstthread.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *                    2003 Benjamin Otte <in7y118@public.uni-hamburg.de>
5  *
6  * gstthread.c: Threaded container object
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 #include "gst_private.h"
25
26 #include "gstthread.h"
27 #include "gstscheduler.h"
28 #include "gstinfo.h"
29 #include "gstlog.h"
30
31 #define GST_CAT_DEFAULT GST_CAT_THREAD
32 #define STACK_SIZE 0x200000
33
34 static GstElementDetails gst_thread_details = GST_ELEMENT_DETAILS (
35   "Threaded container",
36   "Generic/Bin",
37   "Container that creates/manages a thread",
38   "Erik Walthinsen <omega@cse.ogi.edu>, "
39   "Benjamin Otte <in7y118@informatik.uni-hamburg.de"
40 );
41
42 /* Thread signals and args */
43 enum {
44   SHUTDOWN,
45   /* FILL ME */
46   LAST_SIGNAL
47 };
48
49 enum {
50   SPINUP=0,
51   STATECHANGE,
52   STARTUP
53 };
54
55 enum {
56   ARG_0,
57   ARG_PRIORITY,
58 };
59
60
61 static void             gst_thread_base_init            (gpointer g_class);
62 static void             gst_thread_class_init           (gpointer g_class, gpointer class_data);
63 static void             gst_thread_init                 (GTypeInstance *instance, gpointer g_class);
64
65 static void             gst_thread_dispose              (GObject *object);
66
67 static void             gst_thread_set_property         (GObject *object, guint prop_id, 
68                                                          const GValue *value, GParamSpec *pspec);
69 static void             gst_thread_get_property         (GObject *object, guint prop_id,
70                                                          GValue *value, GParamSpec *pspec);
71 static GstElementStateReturn gst_thread_change_state    (GstElement *element);
72 static void             gst_thread_child_state_change   (GstBin *bin, GstElementState oldstate, 
73                                                          GstElementState newstate, GstElement *element);
74
75 static void             gst_thread_catch                (GstThread *thread);
76 static void             gst_thread_release              (GstThread *thread);
77
78 #ifndef GST_DISABLE_LOADSAVE
79 static xmlNodePtr       gst_thread_save_thyself         (GstObject *object,
80                                                          xmlNodePtr parent);
81 static void             gst_thread_restore_thyself      (GstObject *object,
82                                                          xmlNodePtr self);
83 #endif
84
85 static void *           gst_thread_main_loop            (void *arg);
86
87 #define GST_TYPE_THREAD_PRIORITY (gst_thread_priority_get_type())
88 static GType
89 gst_thread_priority_get_type(void) 
90 {
91   static GType thread_priority_type = 0;
92   static GEnumValue thread_priority[] = 
93   {
94     { G_THREAD_PRIORITY_LOW,    "LOW",     "Low Priority Scheduling" },
95     { G_THREAD_PRIORITY_NORMAL, "NORMAL",  "Normal Scheduling" },
96     { G_THREAD_PRIORITY_HIGH,   "HIGH",    "High Priority Scheduling" },
97     { G_THREAD_PRIORITY_URGENT, "URGENT",  "Urgent Scheduling" },
98     { 0, NULL, NULL },
99   };
100   if (!thread_priority_type) {
101     thread_priority_type = g_enum_register_static("GstThreadPriority", thread_priority);
102   }
103   return thread_priority_type;
104 }
105
106 static GstBinClass *parent_class = NULL;
107 static guint gst_thread_signals[LAST_SIGNAL] = { 0 };
108 GPrivate *gst_thread_current;
109
110 GType
111 gst_thread_get_type(void) {
112   static GType thread_type = 0;
113
114   if (!thread_type) {
115     static const GTypeInfo thread_info = {
116       sizeof (GstThreadClass),
117       gst_thread_base_init, 
118       NULL,
119       gst_thread_class_init, 
120       NULL, 
121       NULL,
122       sizeof (GstThread),
123       4,
124       gst_thread_init,
125       NULL
126     };
127     thread_type = g_type_register_static (GST_TYPE_BIN, "GstThread",
128                                           &thread_info, 0);
129   }
130   return thread_type;
131 }
132
133 static void
134 gst_thread_base_init (gpointer g_class)
135 {
136   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
137
138   gst_element_class_set_details (gstelement_class, &gst_thread_details);
139 }
140 static void do_nothing (gpointer hi) {}
141 static void
142 gst_thread_class_init (gpointer g_class, gpointer class_data)
143 {
144   GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
145   GstObjectClass *gstobject_class = GST_OBJECT_CLASS (g_class);
146   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
147   GstBinClass *gstbin_class = GST_BIN_CLASS (g_class);
148   GstThreadClass *klass = GST_THREAD_CLASS (g_class);
149
150   /* setup gst_thread_current */
151   gst_thread_current = g_private_new (do_nothing);
152
153   parent_class = g_type_class_peek_parent (g_class);
154
155   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_PRIORITY,
156     g_param_spec_enum ("priority", "Scheduling Policy", "The scheduling priority of the thread",
157                        GST_TYPE_THREAD_PRIORITY, G_THREAD_PRIORITY_NORMAL, G_PARAM_READWRITE));
158
159   gst_thread_signals[SHUTDOWN] =
160     g_signal_new ("shutdown", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
161                   G_STRUCT_OFFSET (GstThreadClass, shutdown), NULL, NULL,
162                   gst_marshal_VOID__VOID, G_TYPE_NONE, 0);
163
164   gobject_class->dispose =              gst_thread_dispose;
165
166 #ifndef GST_DISABLE_LOADSAVE
167   gstobject_class->save_thyself =       GST_DEBUG_FUNCPTR (gst_thread_save_thyself);
168   gstobject_class->restore_thyself =    GST_DEBUG_FUNCPTR (gst_thread_restore_thyself);
169 #endif
170
171   gstelement_class->change_state =      GST_DEBUG_FUNCPTR (gst_thread_change_state);
172
173   gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_thread_set_property);
174   gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_thread_get_property);
175
176   gstbin_class->child_state_change =    GST_DEBUG_FUNCPTR (gst_thread_child_state_change);
177 }
178
179 static void
180 gst_thread_init (GTypeInstance *instance, gpointer g_class)
181 {
182   GstScheduler *scheduler;
183   GstThread *thread = GST_THREAD (instance);
184
185   GST_DEBUG ("initializing thread");
186
187   /* threads are managing bins and iterate themselves */
188   /* CR1: the GstBin code checks these flags */
189   GST_FLAG_SET (thread, GST_BIN_FLAG_MANAGER);
190   GST_FLAG_SET (thread, GST_BIN_SELF_SCHEDULABLE);
191
192   scheduler = gst_scheduler_factory_make (NULL, GST_ELEMENT (thread));
193   g_assert (scheduler);
194
195   thread->lock = g_mutex_new ();
196   thread->cond = g_cond_new ();
197
198   thread->thread_id = (GThread *) NULL; /* set in NULL -> READY */
199   thread->priority = G_THREAD_PRIORITY_NORMAL;
200 }
201
202 static void
203 gst_thread_dispose (GObject *object)
204 {
205   GstThread *thread = GST_THREAD (object);
206
207   GST_CAT_DEBUG (GST_CAT_REFCOUNTING, "GstThread: dispose");
208
209   G_OBJECT_CLASS (parent_class)->dispose (object);
210
211   g_assert (GST_STATE (thread) == GST_STATE_NULL);
212
213   g_mutex_free (thread->lock);
214   g_cond_free (thread->cond);
215
216   gst_object_replace ((GstObject **)&GST_ELEMENT_SCHED (thread), NULL);
217 }
218
219 /**
220  * gst_thread_set_priority:
221  * @thread: the thread to change 
222  * @priority: the new priority for the thread
223  *
224  * change the thread's priority
225  */
226 void
227 gst_thread_set_priority (GstThread *thread, GThreadPriority priority)
228 {
229   g_return_if_fail (GST_IS_THREAD (thread));
230
231   thread->priority = priority;
232 }
233
234 static void
235 gst_thread_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
236 {
237   GstThread *thread;
238
239   thread = GST_THREAD (object);
240
241   switch (prop_id) {
242     case ARG_PRIORITY:
243       thread->priority = g_value_get_enum (value);
244       break;
245     default:
246       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
247       break;
248   }
249 }
250
251 static void
252 gst_thread_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
253 {
254   GstThread *thread;
255
256   thread = GST_THREAD (object);
257
258   switch (prop_id) {
259     case ARG_PRIORITY:
260       g_value_set_enum (value, thread->priority);
261       break;
262     default:
263       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
264       break;
265   }
266 }
267
268
269 /**
270  * gst_thread_new:
271  * @name: the name of the thread
272  *
273  * Create a new thread with the given name.
274  *
275  * Returns: The new thread
276  */
277 GstElement*
278 gst_thread_new (const gchar *name)
279 {
280   return gst_element_factory_make ("thread", name);
281 }
282
283 /**
284  * gst_thread_get_current:
285  *
286  * Create a new thread with the given name.
287  *
288  * Returns: The current GstThread or NULL if you are not running inside a 
289  *          #GstThread.
290  */
291 GstThread *
292 gst_thread_get_current (void)
293 {
294   return (GstThread *) g_private_get (gst_thread_current);
295 }
296
297 static inline void
298 gst_thread_release_children_locks (GstThread *thread)
299 {
300   GstRealPad *peer = NULL;
301   GstElement *peerelement;
302   GList *elements = (GList *) gst_bin_get_list (GST_BIN (thread));
303
304   while (elements) {
305     GstElement *element = GST_ELEMENT (elements->data);
306     GList *pads;
307
308     g_assert (element);
309     GST_DEBUG_OBJECT (thread, "waking element \"%s\"", GST_ELEMENT_NAME (element));
310     elements = g_list_next (elements);
311
312     if (!gst_element_release_locks (element))
313       g_warning ("element %s could not release locks", GST_ELEMENT_NAME (element));
314
315     pads = GST_ELEMENT_PADS (element);
316
317     while (pads) {
318       if (GST_PAD_PEER (pads->data)) {
319         peer = GST_REAL_PAD (GST_PAD_PEER (pads->data));
320         pads = g_list_next (pads);
321       } else {
322         pads = g_list_next (pads);
323         continue;
324       }
325
326       if (!peer)
327         continue;
328
329       peerelement = GST_PAD_PARENT (peer);
330       if (!peerelement)
331         continue; /* FIXME: deal with case where there's no peer */
332
333       if (GST_ELEMENT_SCHED (peerelement) != GST_ELEMENT_SCHED (thread)) {
334         GST_LOG_OBJECT (thread, "element \"%s\" has pad cross sched boundary", GST_ELEMENT_NAME (element));
335         GST_LOG_OBJECT (thread, "waking element \"%s\"", GST_ELEMENT_NAME (peerelement));
336         if (!gst_element_release_locks (peerelement))
337           g_warning ("element %s could not release locks", GST_ELEMENT_NAME (peerelement));
338       }
339     }
340   }
341 }
342 /* stops the main thread, if there is one and grabs the thread's mutex */
343 static void
344 gst_thread_catch (GstThread *thread)
345 {
346   gboolean wait;
347   if (thread == gst_thread_get_current()) {
348     /* we're trying to catch ourself */
349     if (!GST_FLAG_IS_SET (thread, GST_THREAD_MUTEX_LOCKED)) {
350       g_mutex_lock (thread->lock);
351       GST_FLAG_SET (thread, GST_THREAD_MUTEX_LOCKED);
352     }
353     GST_DEBUG_OBJECT (thread, "catching itself");
354     GST_FLAG_UNSET (thread, GST_THREAD_STATE_SPINNING);
355   } else {
356     /* another thread is trying to catch us */
357     g_mutex_lock (thread->lock);
358     wait = !GST_FLAG_IS_SET (thread, GST_THREAD_STATE_SPINNING);
359     while (!wait) {
360       GTimeVal tv;
361       GST_LOG_OBJECT (thread, "catching thread...");
362       GST_FLAG_UNSET (thread, GST_THREAD_STATE_SPINNING);
363       g_cond_signal (thread->cond);
364       gst_thread_release_children_locks (thread);
365       g_get_current_time (&tv);
366       g_time_val_add (&tv, 1000); /* wait a millisecond to catch the thread */
367       wait = g_cond_timed_wait (thread->cond, thread->lock, &tv);
368     }
369     GST_LOG_OBJECT (thread, "caught thread");
370   }
371   g_assert (!GST_FLAG_IS_SET (thread, GST_THREAD_STATE_SPINNING));
372 }
373
374 static void
375 gst_thread_release (GstThread *thread)
376 {
377   if (thread != gst_thread_get_current()) {
378     g_cond_signal (thread->cond);
379     g_mutex_unlock (thread->lock);
380   }
381 }
382
383 static GstElementStateReturn
384 gst_thread_change_state (GstElement *element)
385 {
386   GstThread *thread;
387   GstElementStateReturn ret;
388   gint transition;
389
390   g_return_val_if_fail (GST_IS_THREAD (element), GST_STATE_FAILURE);
391   transition = GST_STATE_TRANSITION (element);
392
393   thread = GST_THREAD (element);
394
395   GST_DEBUG_OBJECT (element, "changing state from %s to %s",
396              gst_element_state_get_name (GST_STATE (element)),
397              gst_element_state_get_name (GST_STATE_PENDING (element)));
398
399   gst_thread_catch (thread);
400
401   /* FIXME: (or GStreamers ideas about "threading"): the element variables are
402      commonly accessed by multiple threads at the same time (see bug #111146
403      for an example) */
404   if (transition != GST_STATE_TRANSITION (element)) {
405     g_warning ("inconsistent state information, fix threading please");
406   }
407
408   switch (transition) {
409     case GST_STATE_NULL_TO_READY:
410       /* create the thread */
411       GST_FLAG_UNSET (thread, GST_THREAD_STATE_REAPING);
412       thread->thread_id = g_thread_create_full(gst_thread_main_loop,
413           thread, STACK_SIZE, FALSE, TRUE, thread->priority,
414           NULL);
415       if (!thread->thread_id){
416         GST_ERROR_OBJECT (element, "g_thread_create_full failed");
417         goto error_out;
418       }
419       GST_LOG_OBJECT (element, "GThread created");
420
421       /* wait for it to 'spin up' */
422       g_cond_wait (thread->cond, thread->lock);
423       break;
424     case GST_STATE_READY_TO_PAUSED:
425       break;
426     case GST_STATE_PAUSED_TO_PLAYING:
427     {
428       /* FIXME: recurse into sub-bins */
429       GList *elements = (GList *) gst_bin_get_list (GST_BIN (thread));
430       while (elements) {
431         gst_element_enable_threadsafe_properties ((GstElement*)elements->data);
432         elements = g_list_next (elements);
433       }
434       /* reset self to spinning */
435       if (thread == gst_thread_get_current()) 
436         GST_FLAG_SET (thread, GST_THREAD_STATE_SPINNING);
437       break;
438     }
439     case GST_STATE_PLAYING_TO_PAUSED:
440     {
441       GList *elements = (GList *) gst_bin_get_list (GST_BIN (thread));
442       while (elements) {
443         gst_element_disable_threadsafe_properties ((GstElement*)elements->data);
444         elements = g_list_next (elements);
445       }
446       break;
447     }
448     case GST_STATE_PAUSED_TO_READY:
449       break;
450     case GST_STATE_READY_TO_NULL:
451       /* we can't join the threads here, because this could have been triggered
452          by ourself (ouch) */
453       GST_LOG_OBJECT (thread, "destroying GThread %p", thread->thread_id);
454       GST_FLAG_SET (thread, GST_THREAD_STATE_REAPING);
455       thread->thread_id = NULL;
456       if (thread == gst_thread_get_current()) {
457         /* or should we continue? */
458         g_warning ("Thread %s is destroying itself. Function call will not return!", GST_ELEMENT_NAME (thread));
459         gst_scheduler_reset (GST_ELEMENT_SCHED (thread));
460         
461         /* unlock and signal - we are out */
462         gst_thread_release (thread);
463
464         GST_INFO_OBJECT (thread, "GThread %p is exiting", g_thread_self());
465
466         g_signal_emit (G_OBJECT (thread), gst_thread_signals[SHUTDOWN], 0);
467
468         g_thread_exit (NULL);
469       }
470       /* now wait for the thread to destroy itself */
471       g_cond_signal (thread->cond);
472       g_cond_wait (thread->cond, thread->lock);
473       /* it should be dead now */
474       break;
475     default:
476       GST_ERROR_OBJECT (element, "UNHANDLED STATE CHANGE! %x", 
477                         GST_STATE_TRANSITION (element));
478       g_assert_not_reached ();
479       break;
480   }
481
482   if (GST_ELEMENT_CLASS (parent_class)->change_state) {
483     ret = GST_ELEMENT_CLASS (parent_class)->change_state (GST_ELEMENT (thread));
484   } else {
485     ret = GST_STATE_SUCCESS;
486   }
487
488   gst_thread_release (thread);
489   return ret;
490   
491 error_out:
492   GST_CAT_DEBUG (GST_CAT_STATES, "changing state from %s to %s failed for %s",
493              gst_element_state_get_name (GST_STATE (element)),
494              gst_element_state_get_name (GST_STATE_PENDING (element)),
495              GST_ELEMENT_NAME (element));
496   gst_thread_release (thread);
497   return GST_STATE_FAILURE;
498 }
499
500 /* state changes work this way: We grab the lock and stop the thread from 
501    spinning (via gst_thread_catch) - then we change the state. After that the
502    thread may spin on. */
503 static void
504 gst_thread_child_state_change (GstBin *bin, GstElementState oldstate, 
505                                GstElementState newstate, GstElement *element)
506 {
507   GST_LOG_OBJECT (bin, "(from thread %s) child %s changed state from %s to %s",
508               gst_thread_get_current() ? GST_ELEMENT_NAME (gst_thread_get_current()) : "(none)", 
509               GST_ELEMENT_NAME (element), gst_element_state_get_name (oldstate),
510               gst_element_state_get_name (newstate));
511   if (parent_class->child_state_change)
512     parent_class->child_state_change (bin, oldstate, newstate, element);
513   /* We'll wake up the main thread now. Note that we can't lock the thread here, 
514      because we might be called from inside gst_thread_change_state when holding
515      the lock. But this doesn't cause any problems. */
516   if (newstate == GST_STATE_PLAYING)
517     g_cond_signal (GST_THREAD (bin)->cond);
518 }
519 /**
520  * gst_thread_main_loop:
521  * @arg: the thread to start
522  *
523  * The main loop of the thread. The thread will iterate
524  * while the state is GST_THREAD_STATE_SPINNING.
525  */
526 static void *
527 gst_thread_main_loop (void *arg)
528 {
529   GstThread *thread = NULL;
530   gboolean status;
531
532   thread = GST_THREAD (arg);
533   g_mutex_lock (thread->lock);
534   GST_LOG_OBJECT (thread, "Started main loop");
535
536   /* initialize gst_thread_current */
537   g_private_set (gst_thread_current, thread);
538
539   /* set up the element's scheduler */
540   gst_scheduler_setup (GST_ELEMENT_SCHED (thread));
541   GST_FLAG_UNSET (thread, GST_THREAD_STATE_REAPING);
542
543   g_cond_signal (thread->cond);
544   while (!(GST_FLAG_IS_SET (thread, GST_THREAD_STATE_REAPING))) {
545     if (GST_STATE (thread) == GST_STATE_PLAYING) {
546       GST_FLAG_SET (thread, GST_THREAD_STATE_SPINNING);
547       status = TRUE;
548       GST_LOG_OBJECT (thread, "starting to iterate");
549       while (status && GST_FLAG_IS_SET (thread, GST_THREAD_STATE_SPINNING)) {
550         g_mutex_unlock (thread->lock);
551         status = gst_bin_iterate (GST_BIN (thread));
552         if (GST_FLAG_IS_SET (thread, GST_THREAD_MUTEX_LOCKED)) {
553           GST_FLAG_UNSET (thread, GST_THREAD_MUTEX_LOCKED);
554         } else {
555           g_mutex_lock (thread->lock);
556         }
557       }
558       GST_FLAG_UNSET (thread, GST_THREAD_STATE_SPINNING);
559     }
560     if (GST_FLAG_IS_SET (thread, GST_THREAD_STATE_REAPING))
561       break;
562     GST_LOG_OBJECT (thread, "we're caught");
563     g_cond_signal (thread->cond);
564     g_cond_wait (thread->cond, thread->lock);
565   }
566
567   /* we need to destroy the scheduler here because it has mapped it's
568    * stack into the threads stack space */
569   gst_scheduler_reset (GST_ELEMENT_SCHED (thread));
570
571   /* must do that before releasing the lock - we might get disposed before being done */
572   g_signal_emit (G_OBJECT (thread), gst_thread_signals[SHUTDOWN], 0);
573
574   /* unlock and signal - we are out */
575   
576   GST_LOG_OBJECT (thread, "Thread %p exits main loop", g_thread_self());
577   g_cond_signal (thread->cond);
578   g_mutex_unlock (thread->lock);
579   /* don't assume the GstThread object exists anymore now */
580
581   return NULL;
582 }
583
584 #ifndef GST_DISABLE_LOADSAVE
585 static xmlNodePtr
586 gst_thread_save_thyself (GstObject *object,
587                          xmlNodePtr self)
588 {
589   if (GST_OBJECT_CLASS (parent_class)->save_thyself)
590     GST_OBJECT_CLASS (parent_class)->save_thyself (object, self);
591   return NULL;
592 }
593
594 static void
595 gst_thread_restore_thyself (GstObject *object,
596                             xmlNodePtr self)
597 {
598   GST_LOG_OBJECT (object, "restoring");
599
600   if (GST_OBJECT_CLASS (parent_class)->restore_thyself)
601     GST_OBJECT_CLASS (parent_class)->restore_thyself (object, self);
602 }
603 #endif /* GST_DISABLE_LOADSAVE */