Add timeout property
[platform/upstream/gstreamer.git] / gst / rtsp-server / rtsp-client.c
1 /* GStreamer
2  * Copyright (C) 2008 Wim Taymans <wim.taymans at gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 #include <sys/ioctl.h>
21
22 #include "rtsp-client.h"
23 #include "rtsp-sdp.h"
24
25 #undef DEBUG
26
27 #define DEFAULT_TIMEOUT  60
28
29 enum
30 {
31   PROP_0,
32   PROP_TIMEOUT,
33   PROP_SESSION_POOL,
34   PROP_MEDIA_MAPPING,
35   PROP_LAST
36 };
37
38 static void gst_rtsp_client_get_property (GObject *object, guint propid,
39     GValue *value, GParamSpec *pspec);
40 static void gst_rtsp_client_set_property (GObject *object, guint propid,
41     const GValue *value, GParamSpec *pspec);
42 static void gst_rtsp_client_finalize (GObject * obj);
43
44 G_DEFINE_TYPE (GstRTSPClient, gst_rtsp_client, G_TYPE_OBJECT);
45
46 static void
47 gst_rtsp_client_class_init (GstRTSPClientClass * klass)
48 {
49   GObjectClass *gobject_class;
50
51   gobject_class = G_OBJECT_CLASS (klass);
52
53   gobject_class->get_property = gst_rtsp_client_get_property;
54   gobject_class->set_property = gst_rtsp_client_set_property;
55   gobject_class->finalize = gst_rtsp_client_finalize;
56
57   g_object_class_install_property (gobject_class, PROP_SESSION_POOL,
58       g_param_spec_uint ("timeout", "Timeout", "The client timeout",
59           0, G_MAXUINT, DEFAULT_TIMEOUT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
60
61   g_object_class_install_property (gobject_class, PROP_SESSION_POOL,
62       g_param_spec_object ("session-pool", "Session Pool",
63           "The session pool to use for client session",
64           GST_TYPE_RTSP_SESSION_POOL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
65
66   g_object_class_install_property (gobject_class, PROP_MEDIA_MAPPING,
67       g_param_spec_object ("media-mapping", "Media Mapping",
68           "The media mapping to use for client session",
69           GST_TYPE_RTSP_MEDIA_MAPPING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
70 }
71
72 static void
73 gst_rtsp_client_init (GstRTSPClient * client)
74 {
75   client->timeout = DEFAULT_TIMEOUT;
76 }
77
78 /* A client is finalized when the connection is broken */
79 static void
80 gst_rtsp_client_finalize (GObject * obj)
81 {
82   GstRTSPClient *client = GST_RTSP_CLIENT (obj);
83
84   g_message ("finalize client %p", client);
85
86   gst_rtsp_connection_free (client->connection);
87   if (client->session_pool)
88     g_object_unref (client->session_pool);
89   if (client->media_mapping)
90     g_object_unref (client->media_mapping);
91
92   if (client->uri)
93     gst_rtsp_url_free (client->uri);
94   if (client->media)
95     g_object_unref (client->media);
96
97   G_OBJECT_CLASS (gst_rtsp_client_parent_class)->finalize (obj);
98 }
99
100 static void
101 gst_rtsp_client_get_property (GObject *object, guint propid,
102     GValue *value, GParamSpec *pspec)
103 {
104   GstRTSPClient *client = GST_RTSP_CLIENT (object);
105
106   switch (propid) {
107     case PROP_TIMEOUT:
108       g_value_set_uint (value, gst_rtsp_client_get_timeout (client));
109       break;
110     case PROP_SESSION_POOL:
111       g_value_take_object (value, gst_rtsp_client_get_session_pool (client));
112       break;
113     case PROP_MEDIA_MAPPING:
114       g_value_take_object (value, gst_rtsp_client_get_media_mapping (client));
115       break;
116     default:
117       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
118   }
119 }
120
121 static void
122 gst_rtsp_client_set_property (GObject *object, guint propid,
123     const GValue *value, GParamSpec *pspec)
124 {
125   GstRTSPClient *client = GST_RTSP_CLIENT (object);
126
127   switch (propid) {
128     case PROP_TIMEOUT:
129       gst_rtsp_client_set_timeout (client, g_value_get_uint (value));
130       break;
131     case PROP_SESSION_POOL:
132       gst_rtsp_client_set_session_pool (client, g_value_get_object (value));
133       break;
134     case PROP_MEDIA_MAPPING:
135       gst_rtsp_client_set_media_mapping (client, g_value_get_object (value));
136       break;
137     default:
138       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
139   }
140 }
141
142 /**
143  * gst_rtsp_client_new:
144  *
145  * Create a new #GstRTSPClient instance.
146  */
147 GstRTSPClient *
148 gst_rtsp_client_new (void)
149 {
150   GstRTSPClient *result;
151
152   result = g_object_new (GST_TYPE_RTSP_CLIENT, NULL);
153
154   return result;
155 }
156
157 static void
158 send_response (GstRTSPClient *client, GstRTSPMessage *response)
159 {
160   GTimeVal timeout;
161
162   gst_rtsp_message_add_header (response, GST_RTSP_HDR_SERVER, "GStreamer RTSP server");
163
164 #ifdef DEBUG
165   gst_rtsp_message_dump (response);
166 #endif
167
168   timeout.tv_sec = client->timeout;
169   timeout.tv_usec = 0;
170
171   gst_rtsp_connection_send (client->connection, response, &timeout);
172   gst_rtsp_message_unset (response);
173 }
174
175 static void
176 send_generic_response (GstRTSPClient *client, GstRTSPStatusCode code, 
177     GstRTSPMessage *request)
178 {
179   GstRTSPMessage response = { 0 };
180
181   gst_rtsp_message_init_response (&response, code, 
182         gst_rtsp_status_as_text (code), request);
183
184   send_response (client, &response);
185 }
186
187 static gboolean
188 compare_uri (const GstRTSPUrl *uri1, const GstRTSPUrl *uri2)
189 {
190   if (uri1 == NULL || uri2 == NULL)
191     return FALSE;
192
193   if (strcmp (uri1->abspath, uri2->abspath))
194     return FALSE;
195
196   return TRUE;
197 }
198
199 /* this function is called to initially find the media for the DESCRIBE request
200  * but is cached for when the same client (without breaking the connection) is
201  * doing a setup for the exact same url. */
202 static GstRTSPMedia *
203 find_media (GstRTSPClient *client, GstRTSPUrl *uri, GstRTSPMessage *request)
204 {
205   GstRTSPMediaFactory *factory;
206   GstRTSPMedia *media;
207
208   if (!compare_uri (client->uri, uri)) {
209     /* remove any previously cached values before we try to construct a new
210      * media for uri */
211     if (client->uri)
212       gst_rtsp_url_free (client->uri);
213     client->uri = NULL;
214     if (client->media)
215       g_object_unref (client->media);
216     client->media = NULL;
217
218     if (!client->media_mapping)
219       goto no_mapping;
220
221     /* find the factory for the uri first */
222     if (!(factory = gst_rtsp_media_mapping_find_factory (client->media_mapping, uri)))
223       goto no_factory;
224
225     /* prepare the media and add it to the pipeline */
226     if (!(media = gst_rtsp_media_factory_construct (factory, uri)))
227       goto no_media;
228
229     /* prepare the media */
230     if (!(gst_rtsp_media_prepare (media)))
231       goto no_prepare;
232
233     /* now keep track of the uri and the media */
234     client->uri = gst_rtsp_url_copy (uri);
235     client->media = media;
236   }
237   else {
238     /* we have seen this uri before, used cached media */
239     media = client->media;
240     g_message ("reusing cached media %p", media); 
241   }
242
243   if (media)
244     g_object_ref (media);
245
246   return media;
247
248   /* ERRORS */
249 no_mapping:
250   {
251     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, request);
252     return NULL;
253   }
254 no_factory:
255   {
256     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, request);
257     return NULL;
258   }
259 no_media:
260   {
261     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, request);
262     g_object_unref (factory);
263     return NULL;
264   }
265 no_prepare:
266   {
267     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, request);
268     g_object_unref (media);
269     g_object_unref (factory);
270     return NULL;
271   }
272 }
273
274 /* Get the session or NULL when there was no session */
275 static GstRTSPSession *
276 ensure_session (GstRTSPClient *client, GstRTSPMessage *request)
277 {
278   GstRTSPResult res;
279   GstRTSPSession *session;
280   gchar *sessid;
281
282   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
283   if (res == GST_RTSP_OK) {
284     if (client->session_pool == NULL)
285       goto no_pool;
286
287     /* we had a session in the request, find it again */
288     if (!(session = gst_rtsp_session_pool_find (client->session_pool, sessid)))
289       goto session_not_found;
290
291     client->timeout = gst_rtsp_session_get_timeout (session);
292   }
293   else
294     goto service_unavailable;
295
296   return session;
297
298   /* ERRORS */
299 no_pool:
300   {
301     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, request);
302     return NULL;
303   }
304 session_not_found:
305   {
306     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, request);
307     return NULL;
308   }
309 service_unavailable:
310   {
311     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, request);
312     return NULL;
313   }
314 }
315
316 static gboolean
317 handle_teardown_request (GstRTSPClient *client, GstRTSPUrl *uri, GstRTSPMessage *request)
318 {
319   GstRTSPSessionMedia *media;
320   GstRTSPSession *session;
321   GstRTSPMessage response = { 0 };
322   GstRTSPStatusCode code;
323
324   if (!(session = ensure_session (client, request)))
325     goto no_session;
326
327   /* get a handle to the configuration of the media in the session */
328   media = gst_rtsp_session_get_media (session, uri);
329   if (!media)
330     goto not_found;
331
332   gst_rtsp_session_media_stop (media);
333
334   /* unmanage the media in the session, returns false if all media session
335    * are torn down. */
336   if (!gst_rtsp_session_release_media (session, media)) {
337     /* remove the session */
338     gst_rtsp_session_pool_remove (client->session_pool, session);
339
340     /* remove the session id from the request, which will also remove it from the
341      * response */
342     gst_rtsp_message_remove_header (request, GST_RTSP_HDR_SESSION, -1);
343   }
344   g_object_unref (session);
345
346   /* construct the response now */
347   code = GST_RTSP_STS_OK;
348   gst_rtsp_message_init_response (&response, code, gst_rtsp_status_as_text (code), request);
349
350   send_response (client, &response);
351
352   return FALSE;
353
354   /* ERRORS */
355 no_session:
356   {
357     /* error was sent already */
358     return FALSE;
359   }
360 not_found:
361   {
362     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, request);
363     return FALSE;
364   }
365 }
366
367 static gboolean
368 handle_pause_request (GstRTSPClient *client, GstRTSPUrl *uri, GstRTSPMessage *request)
369 {
370   GstRTSPSessionMedia *media;
371   GstRTSPSession *session;
372   GstRTSPMessage response = { 0 };
373   GstRTSPStatusCode code;
374
375   if (!(session = ensure_session (client, request)))
376     goto no_session;
377
378   /* get a handle to the configuration of the media in the session */
379   media = gst_rtsp_session_get_media (session, uri);
380   if (!media)
381     goto not_found;
382
383   /* the session state must be playing or recording */
384   if (media->state != GST_RTSP_STATE_PLAYING &&
385       media->state != GST_RTSP_STATE_RECORDING)
386     goto invalid_state;
387
388   gst_rtsp_session_media_pause (media);
389
390   /* construct the response now */
391   code = GST_RTSP_STS_OK;
392   gst_rtsp_message_init_response (&response, code, gst_rtsp_status_as_text (code), request);
393
394   send_response (client, &response);
395
396   /* the state is now READY */
397   media->state = GST_RTSP_STATE_READY;
398   g_object_unref (session);
399
400   return FALSE;
401
402   /* ERRORS */
403 no_session:
404   {
405     return FALSE;
406   }
407 not_found:
408   {
409     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, request);
410     g_object_unref (session);
411     return FALSE;
412   }
413 invalid_state:
414   {
415     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE, request);
416     g_object_unref (session);
417     return FALSE;
418   }
419 }
420
421 static gboolean
422 handle_play_request (GstRTSPClient *client, GstRTSPUrl *uri, GstRTSPMessage *request)
423 {
424   GstRTSPSessionMedia *media;
425   GstRTSPSession *session;
426   GstRTSPMessage response = { 0 };
427   GstRTSPStatusCode code;
428   GString *rtpinfo;
429   guint n_streams, i;
430   guint timestamp, seqnum;
431   gchar *str;
432
433   if (!(session = ensure_session (client, request)))
434     goto no_session;
435
436   /* get a handle to the configuration of the media in the session */
437   media = gst_rtsp_session_get_media (session, uri);
438   if (!media)
439     goto not_found;
440
441   /* the session state must be playing or ready */
442   if (media->state != GST_RTSP_STATE_PLAYING &&
443       media->state != GST_RTSP_STATE_READY)
444     goto invalid_state;
445
446   /* grab RTPInfo from the payloaders now */
447   rtpinfo = g_string_new ("");
448
449   n_streams = gst_rtsp_media_n_streams (media->media);
450   for (i = 0; i < n_streams; i++) {
451     GstRTSPMediaStream *stream;
452     gchar *uristr;
453
454     stream = gst_rtsp_media_get_stream (media->media, i);
455
456     g_object_get (G_OBJECT (stream->payloader), "seqnum", &seqnum, NULL);
457     g_object_get (G_OBJECT (stream->payloader), "timestamp", &timestamp, NULL);
458
459     if (i > 0)
460       g_string_append (rtpinfo, ", ");
461
462     uristr = gst_rtsp_url_get_request_uri (uri);
463     g_string_append_printf (rtpinfo, "url=%s/stream=%d;seq=%u;rtptime=%u", uristr, i, seqnum, timestamp);
464     g_free (uristr);
465   }
466
467   /* construct the response now */
468   code = GST_RTSP_STS_OK;
469   gst_rtsp_message_init_response (&response, code, gst_rtsp_status_as_text (code), request);
470
471   /* add the RTP-Info header */
472   str = g_string_free (rtpinfo, FALSE);
473   gst_rtsp_message_take_header (&response, GST_RTSP_HDR_RTP_INFO, str);
474
475   /* add the range */
476   str = gst_rtsp_range_to_string (&media->media->range);
477   gst_rtsp_message_take_header (&response, GST_RTSP_HDR_RANGE, str);
478
479   send_response (client, &response);
480
481   /* start playing after sending the request */
482   gst_rtsp_session_media_play (media);
483
484   media->state = GST_RTSP_STATE_PLAYING;
485   g_object_unref (session);
486
487   return FALSE;
488
489   /* ERRORS */
490 no_session:
491   {
492     /* error was sent */
493     return FALSE;
494   }
495 not_found:
496   {
497     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, request);
498     g_object_unref (session);
499     return FALSE;
500   }
501 invalid_state:
502   {
503     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE, request);
504     g_object_unref (session);
505     return FALSE;
506   }
507 }
508
509 static gboolean
510 handle_setup_request (GstRTSPClient *client, GstRTSPUrl *uri, GstRTSPMessage *request)
511 {
512   GstRTSPResult res;
513   gchar *sessid;
514   gchar *transport;
515   gchar **transports;
516   gboolean have_transport;
517   GstRTSPTransport *ct, *st;
518   GstRTSPSession *session;
519   gint i;
520   GstRTSPLowerTrans supported;
521   GstRTSPMessage response = { 0 };
522   GstRTSPStatusCode code;
523   GstRTSPSessionStream *stream;
524   gchar *trans_str, *pos;
525   guint streamid;
526   GstRTSPSessionMedia *media;
527   gboolean need_session;
528
529   /* the uri contains the stream number we added in the SDP config, which is
530    * always /stream=%d so we need to strip that off 
531    * parse the stream we need to configure, look for the stream in the abspath
532    * first and then in the query. */
533   if (!(pos = strstr (uri->abspath, "/stream="))) {
534     if (!(pos = strstr (uri->query, "/stream=")))
535       goto bad_request;
536   }
537
538   /* we can mofify the parse uri in place */
539   *pos = '\0';
540
541   pos += strlen ("/stream=");
542   if (sscanf (pos, "%u", &streamid) != 1)
543     goto bad_request;
544
545   /* parse the transport */
546   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_TRANSPORT, &transport, 0);
547   if (res != GST_RTSP_OK)
548     goto no_transport;
549
550   transports = g_strsplit (transport, ",", 0);
551   gst_rtsp_transport_new (&ct);  
552
553   /* loop through the transports, try to parse */
554   have_transport = FALSE;
555   for (i = 0; transports[i]; i++) {
556
557     gst_rtsp_transport_init (ct);  
558     res = gst_rtsp_transport_parse (transports[i], ct);
559     if (res == GST_RTSP_OK) {
560       have_transport = TRUE;
561       break;
562     }
563   }
564   g_strfreev (transports);
565
566   /* we have not found anything usable, error out */
567   if (!have_transport) 
568     goto unsupported_transports;
569
570   /* we have a valid transport, check if we can handle it */
571   if (ct->trans != GST_RTSP_TRANS_RTP)
572     goto unsupported_transports;
573   if (ct->profile != GST_RTSP_PROFILE_AVP)
574     goto unsupported_transports;
575
576   supported = GST_RTSP_LOWER_TRANS_UDP |
577         GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP;
578   if (!(ct->lower_transport & supported))
579     goto unsupported_transports;
580
581   if (client->session_pool == NULL)
582     goto no_pool;
583
584   /* we have a valid transport now, set the destination of the client. */
585   g_free (ct->destination);
586   ct->destination = g_strdup (inet_ntoa (client->address.sin_addr));
587
588   /* a setup request creates a session for a client, check if the client already
589    * sent a session id to us */
590   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
591   if (res == GST_RTSP_OK) {
592     /* we had a session in the request, find it again */
593     if (!(session = gst_rtsp_session_pool_find (client->session_pool, sessid)))
594       goto session_not_found;
595
596     /* get a handle to the configuration of the media in the session, this can
597      * return NULL if this is a new url to manage in this session. */
598     media = gst_rtsp_session_get_media (session, uri);
599
600     need_session = FALSE;
601   }
602   else {
603     /* create a session if this fails we probably reached our session limit or
604      * something. */
605     if (!(session = gst_rtsp_session_pool_create (client->session_pool)))
606       goto service_unavailable;
607
608     /* we need a new media configuration in this session */
609     media = NULL;
610
611     need_session = TRUE;
612   }
613
614   /* we have no media, find one and manage it */
615   if (media == NULL) {
616     GstRTSPMedia *m;
617
618     /* get a handle to the configuration of the media in the session */
619     if ((m = find_media (client, uri, request))) {
620       /* manage the media in our session now */
621       media = gst_rtsp_session_manage_media (session, uri, m);
622     }
623   }
624
625   /* if we stil have no media, error */
626   if (media == NULL)
627     goto not_found;
628
629   /* get a handle to the stream in the media */
630   if (!(stream = gst_rtsp_session_media_get_stream (media, streamid)))
631     goto no_stream;
632
633   /* setup the server transport from the client transport */
634   st = gst_rtsp_session_stream_set_transport (stream, ct);
635
636   /* serialize the server transport */
637   trans_str = gst_rtsp_transport_as_text (st);
638   gst_rtsp_transport_free (st);
639
640   /* construct the response now */
641   code = GST_RTSP_STS_OK;
642   gst_rtsp_message_init_response (&response, code, gst_rtsp_status_as_text (code), request);
643
644   /* add the new session header for new session ids */
645   if (need_session) {
646     gchar *str;
647
648     if (session->timeout != 60)
649       str = g_strdup_printf ("%s; timeout=%d", session->sessionid, session->timeout);
650     else
651       str = g_strdup (session->sessionid);
652
653     gst_rtsp_message_take_header (&response, GST_RTSP_HDR_SESSION, str);
654   }
655
656   gst_rtsp_message_add_header (&response, GST_RTSP_HDR_TRANSPORT, trans_str);
657   g_free (trans_str);
658
659   send_response (client, &response);
660
661   /* update the state */
662   switch (media->state) {
663     case GST_RTSP_STATE_PLAYING:
664     case GST_RTSP_STATE_RECORDING:
665     case GST_RTSP_STATE_READY:
666       /* no state change */
667       break;
668     default:
669       media->state = GST_RTSP_STATE_READY;
670       break;
671   }
672
673   g_object_unref (session);
674
675   return TRUE;
676
677   /* ERRORS */
678 bad_request:
679   {
680     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, request);
681     return FALSE;
682   }
683 not_found:
684   {
685     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, request);
686     return FALSE;
687   }
688 no_stream:
689   {
690     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, request);
691     g_object_unref (media);
692     return FALSE;
693   }
694 session_not_found:
695   {
696     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, request);
697     return FALSE;
698   }
699 no_transport:
700   {
701     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, request);
702     return FALSE;
703   }
704 unsupported_transports:
705   {
706     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, request);
707     gst_rtsp_transport_free (ct);  
708     return FALSE;
709   }
710 no_pool:
711   {
712     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, request);
713     return FALSE;
714   }
715 service_unavailable:
716   {
717     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, request);
718     return FALSE;
719   }
720 }
721
722 /* for the describe we must generate an SDP */
723 static gboolean
724 handle_describe_request (GstRTSPClient *client, GstRTSPUrl *uri, GstRTSPMessage *request)
725 {
726   GstRTSPMessage response = { 0 };
727   GstRTSPResult res;
728   GstSDPMessage *sdp;
729   guint i;
730   gchar *str;
731   GstRTSPMedia *media;
732
733   /* check what kind of format is accepted, we don't really do anything with it
734    * and always return SDP for now. */
735   for (i = 0; i++; ) {
736     gchar *accept;
737
738     res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_ACCEPT, &accept, i);
739     if (res == GST_RTSP_ENOTIMPL)
740       break;
741
742     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
743       break;
744   }
745
746   /* find the media object for the uri */
747   if (!(media = find_media (client, uri, request)))
748     goto no_media;
749
750   /* create an SDP for the media object */
751   if (!(sdp = gst_rtsp_sdp_from_media (media)))
752     goto no_sdp;
753
754   g_object_unref (media);
755
756   gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, 
757         gst_rtsp_status_as_text (GST_RTSP_STS_OK), request);
758
759   gst_rtsp_message_add_header (&response, GST_RTSP_HDR_CONTENT_TYPE, "application/sdp");
760
761   /* content base for some clients that might screw up creating the setup uri */
762   str = g_strdup_printf ("rtsp://%s:%u%s/", uri->host, uri->port, uri->abspath);
763   gst_rtsp_message_add_header (&response, GST_RTSP_HDR_CONTENT_BASE, str);
764   g_free (str);
765
766   /* add SDP to the response body */
767   str = gst_sdp_message_as_text (sdp);
768   gst_rtsp_message_take_body (&response, (guint8 *)str, strlen (str));
769   gst_sdp_message_free (sdp);
770
771   send_response (client, &response);
772
773   return TRUE;
774
775   /* ERRORS */
776 no_media:
777   {
778     /* error reply is already sent */
779     return FALSE;
780   }
781 no_sdp:
782   {
783     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, request);
784     g_object_unref (media);
785     return FALSE;
786   }
787 }
788
789 static void
790 handle_options_request (GstRTSPClient *client, GstRTSPUrl *uri, GstRTSPMessage *request)
791 {
792   GstRTSPMessage response = { 0 };
793   GstRTSPMethod options;
794   gchar *str;
795
796   options = GST_RTSP_DESCRIBE |
797             GST_RTSP_OPTIONS |
798     //        GST_RTSP_PAUSE |
799             GST_RTSP_PLAY |
800             GST_RTSP_SETUP |
801             GST_RTSP_TEARDOWN;
802
803   str = gst_rtsp_options_as_text (options);
804
805   gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, 
806         gst_rtsp_status_as_text (GST_RTSP_STS_OK), request);
807
808   gst_rtsp_message_add_header (&response, GST_RTSP_HDR_PUBLIC, str);
809   g_free (str);
810
811   send_response (client, &response);
812 }
813
814 /* remove duplicate and trailing '/' */
815 static void
816 santize_uri (GstRTSPUrl *uri)
817 {
818   gint i, len;
819   gchar *s, *d;
820   gboolean have_slash, prev_slash;
821
822   s = d = uri->abspath;
823   len = strlen (uri->abspath);
824
825   prev_slash = FALSE;
826
827   for (i = 0; i < len; i++) {
828     have_slash = s[i] == '/';
829     *d = s[i];
830     if (!have_slash || !prev_slash)
831       d++;
832     prev_slash = have_slash;
833   }
834   len = d - uri->abspath;
835   /* don't remove the first slash if that's the only thing left */
836   if (len > 1 && *(d-1) == '/')
837     d--;
838   *d = '\0';
839 }
840
841 /* this function runs in a client specific thread and handles all rtsp messages
842  * with the client */
843 static gpointer
844 handle_client (GstRTSPClient *client)
845 {
846   GstRTSPMessage request = { 0 };
847   GstRTSPResult res;
848   GstRTSPMethod method;
849   const gchar *uristr;
850   GstRTSPUrl *uri;
851   GstRTSPVersion version;
852
853   while (TRUE) {
854     GTimeVal timeout;
855
856     timeout.tv_sec = client->timeout;
857
858     /* start by waiting for a message from the client */
859     res = gst_rtsp_connection_receive (client->connection, &request, &timeout);
860     if (res < 0)
861       goto receive_failed;
862
863 #ifdef DEBUG
864     gst_rtsp_message_dump (&request);
865 #endif
866
867     gst_rtsp_message_parse_request (&request, &method, &uristr, &version);
868
869     if (version != GST_RTSP_VERSION_1_0) {
870       /* we can only handle 1.0 requests */
871       send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED, &request);
872       continue;
873     }
874
875     /* we always try to parse the url first */
876     if ((res = gst_rtsp_url_parse (uristr, &uri)) != GST_RTSP_OK) {
877       send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, &request);
878       continue;
879     }
880
881     /* sanitize the uri */
882     santize_uri (uri);
883
884     /* now see what is asked and dispatch to a dedicated handler */
885     switch (method) {
886       case GST_RTSP_OPTIONS:
887         handle_options_request (client, uri, &request);
888         break;
889       case GST_RTSP_DESCRIBE:
890         handle_describe_request (client, uri, &request);
891         break;
892       case GST_RTSP_SETUP:
893         handle_setup_request (client, uri, &request);
894         break;
895       case GST_RTSP_PLAY:
896         handle_play_request (client, uri, &request);
897         break;
898       case GST_RTSP_PAUSE:
899         handle_pause_request (client, uri, &request);
900         break;
901       case GST_RTSP_TEARDOWN:
902         handle_teardown_request (client, uri, &request);
903         break;
904       case GST_RTSP_ANNOUNCE:
905       case GST_RTSP_GET_PARAMETER:
906       case GST_RTSP_RECORD:
907       case GST_RTSP_REDIRECT:
908       case GST_RTSP_SET_PARAMETER:
909         send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, &request);
910         break;
911       case GST_RTSP_INVALID:
912       default:
913         send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, &request);
914         break;
915     }
916     gst_rtsp_url_free (uri);
917   }
918   g_object_unref (client);
919   return NULL;
920
921   /* ERRORS */
922 receive_failed:
923   {
924     gchar *str;
925     str = gst_rtsp_strresult (res);
926     g_message ("receive failed %d (%s), disconnect client %p", res, 
927             str, client);
928     g_free (str);
929     gst_rtsp_message_unset (&request);
930     gst_rtsp_connection_close (client->connection);
931     g_object_unref (client);
932     return NULL;
933   }
934 }
935
936 /* called when we need to accept a new request from a client */
937 static gboolean
938 client_accept (GstRTSPClient *client, GIOChannel *channel)
939 {
940   /* a new client connected. */
941   int server_sock_fd, fd;
942   unsigned int address_len;
943   GstRTSPConnection *conn;
944
945   server_sock_fd = g_io_channel_unix_get_fd (channel);
946
947   address_len = sizeof (client->address);
948   memset (&client->address, 0, address_len);
949
950   fd = accept (server_sock_fd, (struct sockaddr *) &client->address,
951       &address_len);
952   if (fd == -1)
953     goto accept_failed;
954
955   /* now create the connection object */
956   gst_rtsp_connection_create (NULL, &conn);
957   conn->fd.fd = fd;
958
959   /* FIXME some hackery, we need to have a connection method to accept server
960    * connections */
961   gst_poll_add_fd (conn->fdset, &conn->fd);
962
963   g_message ("added new client %p ip %s with fd %d", client,
964                 inet_ntoa (client->address.sin_addr), conn->fd.fd);
965
966   client->connection = conn;
967
968   return TRUE;
969
970   /* ERRORS */
971 accept_failed:
972   {
973     g_error ("Could not accept client on server socket %d: %s (%d)",
974             server_sock_fd, g_strerror (errno), errno);
975     return FALSE;
976   }
977 }
978
979 /**
980  * gst_rtsp_client_set_timeout:
981  * @client: a #GstRTSPClient
982  * @timeout: a timeout in seconds
983  *
984  * Set the connection timeout to @timeout seconds for @client.
985  */
986 void
987 gst_rtsp_client_set_timeout (GstRTSPClient *client, guint timeout)
988 {
989   client->timeout = timeout;
990 }
991
992 /**
993  * gst_rtsp_client_get_timeout:
994  * @client: a #GstRTSPClient
995  *
996  * Get the connection timeout @client.
997  *
998  * Returns: the connection timeout for @client in seconds.
999  */
1000 guint
1001 gst_rtsp_client_get_timeout (GstRTSPClient *client)
1002 {
1003   return client->timeout;
1004 }
1005
1006 /**
1007  * gst_rtsp_client_set_session_pool:
1008  * @client: a #GstRTSPClient
1009  * @pool: a #GstRTSPSessionPool
1010  *
1011  * Set @pool as the sessionpool for @client which it will use to find
1012  * or allocate sessions. the sessionpool is usually inherited from the server
1013  * that created the client but can be overridden later.
1014  */
1015 void
1016 gst_rtsp_client_set_session_pool (GstRTSPClient *client, GstRTSPSessionPool *pool)
1017 {
1018   GstRTSPSessionPool *old;
1019
1020   old = client->session_pool;
1021   if (old != pool) {
1022     if (pool)
1023       g_object_ref (pool);
1024     client->session_pool = pool;
1025     if (old)
1026       g_object_unref (old);
1027   }
1028 }
1029
1030 /**
1031  * gst_rtsp_client_get_session_pool:
1032  * @client: a #GstRTSPClient
1033  *
1034  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
1035  *
1036  * Returns: a #GstRTSPSessionPool, unref after usage.
1037  */
1038 GstRTSPSessionPool *
1039 gst_rtsp_client_get_session_pool (GstRTSPClient *client)
1040 {
1041   GstRTSPSessionPool *result;
1042
1043   if ((result = client->session_pool))
1044     g_object_ref (result);
1045
1046   return result;
1047 }
1048
1049 /**
1050  * gst_rtsp_client_set_media_mapping:
1051  * @client: a #GstRTSPClient
1052  * @mapping: a #GstRTSPMediaMapping
1053  *
1054  * Set @mapping as the media mapping for @client which it will use to map urls
1055  * to media streams. These mapping is usually inherited from the server that
1056  * created the client but can be overriden later.
1057  */
1058 void
1059 gst_rtsp_client_set_media_mapping (GstRTSPClient *client, GstRTSPMediaMapping *mapping)
1060 {
1061   GstRTSPMediaMapping *old;
1062
1063   old = client->media_mapping;
1064
1065   if (old != mapping) {
1066     if (mapping)
1067       g_object_ref (mapping);
1068     client->media_mapping = mapping;
1069     if (old)
1070       g_object_unref (old);
1071   }
1072 }
1073
1074 /**
1075  * gst_rtsp_client_get_media_mapping:
1076  * @client: a #GstRTSPClient
1077  *
1078  * Get the #GstRTSPMediaMapping object that @client uses to manage its sessions.
1079  *
1080  * Returns: a #GstRTSPMediaMapping, unref after usage.
1081  */
1082 GstRTSPMediaMapping *
1083 gst_rtsp_client_get_media_mapping (GstRTSPClient *client)
1084 {
1085   GstRTSPMediaMapping *result;
1086
1087   if ((result = client->media_mapping))
1088     g_object_ref (result);
1089
1090   return result;
1091 }
1092
1093 /**
1094  * gst_rtsp_client_attach:
1095  * @client: a #GstRTSPClient
1096  * @channel: a #GIOChannel
1097  *
1098  * Accept a new connection for @client on the socket in @source. 
1099  *
1100  * This function should be called when the client properties and urls are fully
1101  * configured and the client is ready to start.
1102  *
1103  * Returns: %TRUE if the client could be accepted.
1104  */
1105 gboolean
1106 gst_rtsp_client_accept (GstRTSPClient *client, GIOChannel *channel)
1107 {
1108   GError *error = NULL;
1109
1110   if (!client_accept (client, channel))
1111     goto accept_failed;
1112
1113   /* client accepted, spawn a thread for the client, we don't need to join the
1114    * thread */
1115   g_object_ref (client);
1116   client->thread = g_thread_create ((GThreadFunc)handle_client, client, FALSE, &error);
1117   if (client->thread == NULL)
1118     goto no_thread;
1119
1120   return TRUE;
1121
1122   /* ERRORS */
1123 accept_failed:
1124   {
1125     return FALSE;
1126   }
1127 no_thread:
1128   {
1129     if (error) {
1130       g_warning ("could not create thread for client %p: %s", client, error->message);
1131       g_error_free (error);
1132     }
1133     g_object_unref (client);
1134     return FALSE;
1135   }
1136 }