Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / ext / dvdread / dvdreadsrc.c
1 /* GStreamer DVD title source
2  * Copyright (C) 1999 Erik Walthinsen <omega@cse.ogi.edu>
3  * Copyright (C) 2001 Billy Biggs <vektor@dumbterm.net>.
4  * Copyright (C) 2006 Tim-Philipp Müller <tim centricular net>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include "_stdint.h"
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <string.h>
32 #include <errno.h>
33
34 #include "dvdreadsrc.h"
35
36 #include <gst/gst-i18n-plugin.h>
37
38 GST_DEBUG_CATEGORY_STATIC (gstgst_dvd_read_src_debug);
39 #define GST_CAT_DEFAULT (gstgst_dvd_read_src_debug)
40
41 enum
42 {
43   ARG_0,
44   ARG_DEVICE,
45   ARG_TITLE,
46   ARG_CHAPTER,
47   ARG_ANGLE
48 };
49
50 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
51     GST_PAD_SRC,
52     GST_PAD_ALWAYS,
53     GST_STATIC_CAPS ("video/mpeg, mpegversion=2, systemstream=(boolean)true"));
54
55 static GstFormat title_format;
56 static GstFormat angle_format;
57 static GstFormat sector_format;
58 static GstFormat chapter_format;
59
60 static gboolean gst_dvd_read_src_start (GstBaseSrc * basesrc);
61 static gboolean gst_dvd_read_src_stop (GstBaseSrc * basesrc);
62 static GstFlowReturn gst_dvd_read_src_create (GstPushSrc * pushsrc,
63     GstBuffer ** buf);
64 static gboolean gst_dvd_read_src_src_query (GstBaseSrc * basesrc,
65     GstQuery * query);
66 static gboolean gst_dvd_read_src_src_event (GstBaseSrc * basesrc,
67     GstEvent * event);
68 static gboolean gst_dvd_read_src_goto_title (GstDvdReadSrc * src, gint title,
69     gint angle);
70 static gboolean gst_dvd_read_src_goto_chapter (GstDvdReadSrc * src,
71     gint chapter);
72 static gboolean gst_dvd_read_src_goto_sector (GstDvdReadSrc * src, gint angle);
73 static void gst_dvd_read_src_set_property (GObject * object, guint prop_id,
74     const GValue * value, GParamSpec * pspec);
75 static void gst_dvd_read_src_get_property (GObject * object, guint prop_id,
76     GValue * value, GParamSpec * pspec);
77 static GstEvent *gst_dvd_read_src_make_clut_change_event (GstDvdReadSrc * src,
78     const guint * clut);
79 static gboolean gst_dvd_read_src_get_size (GstDvdReadSrc * src, gint64 * size);
80 static gboolean gst_dvd_read_src_do_seek (GstBaseSrc * src, GstSegment * s);
81 static gint64 gst_dvd_read_src_convert_timecode (dvd_time_t * time);
82 static gint gst_dvd_read_src_get_next_cell (GstDvdReadSrc * src,
83     pgc_t * pgc, gint cell);
84 static GstClockTime gst_dvd_read_src_get_time_for_sector (GstDvdReadSrc * src,
85     guint sector);
86 static gint gst_dvd_read_src_get_sector_from_time (GstDvdReadSrc * src,
87     GstClockTime ts);
88
89 static void gst_dvd_read_src_uri_handler_init (gpointer g_iface,
90     gpointer iface_data);
91
92 #define gst_dvd_read_src_parent_class parent_class
93 G_DEFINE_TYPE_WITH_CODE (GstDvdReadSrc, gst_dvd_read_src, GST_TYPE_PUSH_SRC,
94     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
95         gst_dvd_read_src_uri_handler_init));
96
97 static void
98 gst_dvd_read_src_finalize (GObject * object)
99 {
100   GstDvdReadSrc *src = GST_DVD_READ_SRC (object);
101
102   g_free (src->location);
103   g_free (src->last_uri);
104
105   G_OBJECT_CLASS (parent_class)->finalize (object);
106 }
107
108 static void
109 gst_dvd_read_src_init (GstDvdReadSrc * src)
110 {
111   src->dvd = NULL;
112   src->vts_file = NULL;
113   src->vmg_file = NULL;
114   src->dvd_title = NULL;
115
116   src->location = g_strdup ("/dev/dvd");
117   src->last_uri = NULL;
118   src->new_seek = TRUE;
119   src->new_cell = TRUE;
120   src->change_cell = FALSE;
121   src->uri_title = 1;
122   src->uri_chapter = 1;
123   src->uri_angle = 1;
124
125   src->title_lang_event_pending = NULL;
126   src->pending_clut_event = NULL;
127
128   gst_pad_use_fixed_caps (GST_BASE_SRC_PAD (src));
129   gst_pad_set_caps (GST_BASE_SRC_PAD (src),
130       gst_static_pad_template_get_caps (&srctemplate));
131 }
132
133 static gboolean
134 gst_dvd_read_src_is_seekable (GstBaseSrc * src)
135 {
136   return TRUE;
137 }
138
139 static void
140 gst_dvd_read_src_class_init (GstDvdReadSrcClass * klass)
141 {
142   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
143   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
144   GstPushSrcClass *gstpushsrc_class = GST_PUSH_SRC_CLASS (klass);
145   GstBaseSrcClass *gstbasesrc_class = GST_BASE_SRC_CLASS (klass);
146
147   gobject_class->finalize = gst_dvd_read_src_finalize;
148   gobject_class->set_property = gst_dvd_read_src_set_property;
149   gobject_class->get_property = gst_dvd_read_src_get_property;
150
151   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_DEVICE,
152       g_param_spec_string ("device", "Device",
153           "DVD device location", NULL,
154           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
155   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_TITLE,
156       g_param_spec_int ("title", "title", "title",
157           1, 999, 1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
158   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_CHAPTER,
159       g_param_spec_int ("chapter", "chapter", "chapter",
160           1, 999, 1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
161   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_ANGLE,
162       g_param_spec_int ("angle", "angle", "angle",
163           1, 999, 1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
164
165   gst_element_class_add_pad_template (gstelement_class,
166       gst_static_pad_template_get (&srctemplate));
167
168   gst_element_class_set_details_simple (gstelement_class, "DVD Source",
169       "Source/File/DVD",
170       "Access a DVD title/chapter/angle using libdvdread",
171       "Erik Walthinsen <omega@cse.ogi.edu>");
172
173   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_dvd_read_src_start);
174   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_dvd_read_src_stop);
175   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_dvd_read_src_src_query);
176   gstbasesrc_class->event = GST_DEBUG_FUNCPTR (gst_dvd_read_src_src_event);
177   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_dvd_read_src_do_seek);
178   gstbasesrc_class->is_seekable =
179       GST_DEBUG_FUNCPTR (gst_dvd_read_src_is_seekable);
180
181   gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_dvd_read_src_create);
182
183   title_format = gst_format_register ("title", "DVD title");
184   angle_format = gst_format_register ("angle", "DVD angle");
185   sector_format = gst_format_register ("sector", "DVD sector");
186   chapter_format = gst_format_register ("chapter", "DVD chapter");
187 }
188
189 static gboolean
190 gst_dvd_read_src_start (GstBaseSrc * basesrc)
191 {
192   GstDvdReadSrc *src = GST_DVD_READ_SRC (basesrc);
193
194   g_return_val_if_fail (src->location != NULL, FALSE);
195
196   GST_DEBUG_OBJECT (src, "Opening DVD '%s'", src->location);
197
198   if ((src->dvd = DVDOpen (src->location)) == NULL)
199     goto open_failed;
200
201   /* Load the video manager to find out the information about the titles */
202   GST_DEBUG_OBJECT (src, "Loading VMG info");
203
204   if (!(src->vmg_file = ifoOpen (src->dvd, 0)))
205     goto ifo_open_failed;
206
207   src->tt_srpt = src->vmg_file->tt_srpt;
208
209   src->title = src->uri_title - 1;
210   src->chapter = src->uri_chapter - 1;
211   src->angle = src->uri_angle - 1;
212
213   if (!gst_dvd_read_src_goto_title (src, src->title, src->angle))
214     goto title_open_failed;
215
216   if (!gst_dvd_read_src_goto_chapter (src, src->chapter))
217     goto chapter_open_failed;
218
219   src->new_seek = FALSE;
220   src->change_cell = TRUE;
221
222   return TRUE;
223
224   /* ERRORS */
225 open_failed:
226   {
227     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
228         (_("Could not open DVD")),
229         ("DVDOpen(%s) failed: %s", src->location, g_strerror (errno)));
230     return FALSE;
231   }
232 ifo_open_failed:
233   {
234     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
235         (_("Could not open DVD")),
236         ("ifoOpen() failed: %s", g_strerror (errno)));
237     return FALSE;
238   }
239 title_open_failed:
240   {
241     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
242         (_("Could not open DVD title %d"), src->uri_title), (NULL));
243     return FALSE;
244   }
245 chapter_open_failed:
246   {
247     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
248         (_("Failed to go to chapter %d of DVD title %d"),
249             src->uri_chapter, src->uri_title), (NULL));
250     return FALSE;
251   }
252 }
253
254 static gboolean
255 gst_dvd_read_src_stop (GstBaseSrc * basesrc)
256 {
257   GstDvdReadSrc *src = GST_DVD_READ_SRC (basesrc);
258
259   if (src->vts_file) {
260     ifoClose (src->vts_file);
261     src->vts_file = NULL;
262   }
263   if (src->vmg_file) {
264     ifoClose (src->vmg_file);
265     src->vmg_file = NULL;
266   }
267   if (src->dvd_title) {
268     DVDCloseFile (src->dvd_title);
269     src->dvd_title = NULL;
270   }
271   if (src->dvd) {
272     DVDClose (src->dvd);
273     src->dvd = NULL;
274   }
275   src->new_cell = TRUE;
276   src->new_seek = TRUE;
277   src->change_cell = FALSE;
278   src->chapter = 0;
279   src->title = 0;
280   src->need_newsegment = TRUE;
281   src->vts_tmapt = NULL;
282   if (src->title_lang_event_pending) {
283     gst_event_unref (src->title_lang_event_pending);
284     src->title_lang_event_pending = NULL;
285   }
286   if (src->pending_clut_event) {
287     gst_event_unref (src->pending_clut_event);
288     src->pending_clut_event = NULL;
289   }
290   if (src->chapter_starts) {
291     g_free (src->chapter_starts);
292     src->chapter_starts = NULL;
293   }
294
295   GST_LOG_OBJECT (src, "closed DVD");
296
297   return TRUE;
298 }
299
300 static void
301 cur_title_get_chapter_pgc (GstDvdReadSrc * src, gint chapter, gint * p_pgn,
302     gint * p_pgc_id, pgc_t ** p_pgc)
303 {
304   pgc_t *pgc;
305   gint pgn, pgc_id;
306
307   g_assert (chapter >= 0 && chapter < src->num_chapters);
308
309   pgc_id = src->vts_ptt_srpt->title[src->ttn - 1].ptt[chapter].pgcn;
310   pgn = src->vts_ptt_srpt->title[src->ttn - 1].ptt[chapter].pgn;
311   pgc = src->vts_file->vts_pgcit->pgci_srp[pgc_id - 1].pgc;
312
313   *p_pgn = pgn;
314   *p_pgc_id = pgc_id;
315   *p_pgc = pgc;
316 }
317
318 static void
319 cur_title_get_chapter_bounds (GstDvdReadSrc * src, gint chapter,
320     gint * p_first_cell, gint * p_last_cell)
321 {
322   pgc_t *pgc;
323   gint pgn, pgc_id, pgn_next_ch;
324
325   g_assert (chapter >= 0 && chapter < src->num_chapters);
326
327   cur_title_get_chapter_pgc (src, chapter, &pgn, &pgc_id, &pgc);
328
329   *p_first_cell = pgc->program_map[pgn - 1] - 1;
330
331   if (chapter == (src->num_chapters - 1)) {
332     *p_last_cell = pgc->nr_of_cells;
333   } else {
334     pgn_next_ch = src->vts_ptt_srpt->title[src->ttn - 1].ptt[chapter + 1].pgn;
335     *p_last_cell = pgc->program_map[pgn_next_ch - 1] - 1;
336   }
337 }
338
339 static gboolean
340 gst_dvd_read_src_goto_chapter (GstDvdReadSrc * src, gint chapter)
341 {
342   gint i;
343
344   /* make sure the chapter number is valid for this title */
345   if (chapter < 0 || chapter >= src->num_chapters) {
346     GST_WARNING_OBJECT (src, "invalid chapter %d (only %d available)",
347         chapter, src->num_chapters);
348     chapter = CLAMP (chapter, 0, src->num_chapters - 1);
349   }
350
351   /* determine which program chain we want to watch. This is
352    * based on the chapter number */
353   cur_title_get_chapter_pgc (src, chapter, &src->pgn, &src->pgc_id,
354       &src->cur_pgc);
355   cur_title_get_chapter_bounds (src, chapter, &src->start_cell,
356       &src->last_cell);
357
358   GST_LOG_OBJECT (src, "Opened chapter %d - cell %d-%d", chapter + 1,
359       src->start_cell, src->last_cell);
360
361   /* retrieve position */
362   src->cur_pack = 0;
363   for (i = 0; i < chapter; i++) {
364     gint c1, c2;
365
366     cur_title_get_chapter_bounds (src, i, &c1, &c2);
367
368     while (c1 < c2) {
369       src->cur_pack +=
370           src->cur_pgc->cell_playback[c1].last_sector -
371           src->cur_pgc->cell_playback[c1].first_sector;
372       ++c1;
373     }
374   }
375
376   /* prepare reading for new cell */
377   src->new_cell = TRUE;
378   src->next_cell = src->start_cell;
379
380   src->chapter = chapter;
381
382   if (src->pending_clut_event)
383     gst_event_unref (src->pending_clut_event);
384
385   src->pending_clut_event =
386       gst_dvd_read_src_make_clut_change_event (src, src->cur_pgc->palette);
387
388   return TRUE;
389 }
390
391 static void
392 gst_dvd_read_src_get_chapter_starts (GstDvdReadSrc * src)
393 {
394   GstClockTime uptohere;
395   guint c;
396
397   g_free (src->chapter_starts);
398   src->chapter_starts = g_new (GstClockTime, src->num_chapters);
399
400   uptohere = (GstClockTime) 0;
401   for (c = 0; c < src->num_chapters; ++c) {
402     GstClockTime chapter_duration = 0;
403     gint cell_start, cell_end, cell;
404     gint pgn, pgc_id;
405     pgc_t *pgc;
406
407     cur_title_get_chapter_pgc (src, c, &pgn, &pgc_id, &pgc);
408     cur_title_get_chapter_bounds (src, c, &cell_start, &cell_end);
409
410     cell = cell_start;
411     while (cell < cell_end) {
412       dvd_time_t *cell_duration;
413
414       cell_duration = &pgc->cell_playback[cell].playback_time;
415       chapter_duration += gst_dvd_read_src_convert_timecode (cell_duration);
416       cell = gst_dvd_read_src_get_next_cell (src, pgc, cell);
417     }
418
419     src->chapter_starts[c] = uptohere;
420
421     GST_INFO_OBJECT (src, "[%02u] Chapter %02u starts at %" GST_TIME_FORMAT
422         ", dur = %" GST_TIME_FORMAT ", cells %d-%d", src->title + 1, c + 1,
423         GST_TIME_ARGS (uptohere), GST_TIME_ARGS (chapter_duration),
424         cell_start, cell_end);
425
426     uptohere += chapter_duration;
427   }
428 }
429
430 static gboolean
431 gst_dvd_read_src_goto_title (GstDvdReadSrc * src, gint title, gint angle)
432 {
433   GstStructure *s;
434   gchar lang_code[3] = { '\0', '\0', '\0' }, *t;
435   pgc_t *pgc0;
436   gint title_set_nr;
437   gint num_titles;
438   gint pgn0, pgc0_id;
439   gint i;
440
441   /* make sure our title number is valid */
442   num_titles = src->tt_srpt->nr_of_srpts;
443   GST_INFO_OBJECT (src, "There are %d titles on this DVD", num_titles);
444   if (title < 0 || title >= num_titles)
445     goto invalid_title;
446
447   src->num_chapters = src->tt_srpt->title[title].nr_of_ptts;
448   GST_INFO_OBJECT (src, "Title %d has %d chapters", title + 1,
449       src->num_chapters);
450
451   /* make sure the angle number is valid for this title */
452   src->num_angles = src->tt_srpt->title[title].nr_of_angles;
453   GST_LOG_OBJECT (src, "Title %d has %d angles", title + 1, src->num_angles);
454   if (angle < 0 || angle >= src->num_angles) {
455     GST_WARNING_OBJECT (src, "Invalid angle %d (only %d available)",
456         angle, src->num_angles);
457     angle = CLAMP (angle, 0, src->num_angles - 1);
458   }
459
460   /* load the VTS information for the title set our title is in */
461   title_set_nr = src->tt_srpt->title[title].title_set_nr;
462   src->vts_file = ifoOpen (src->dvd, title_set_nr);
463   if (src->vts_file == NULL)
464     goto ifo_open_failed;
465
466   src->ttn = src->tt_srpt->title[title].vts_ttn;
467   src->vts_ptt_srpt = src->vts_file->vts_ptt_srpt;
468
469   /* interactive title? */
470   if (src->num_chapters > 0 &&
471       src->vts_ptt_srpt->title[src->ttn - 1].ptt[0].pgn == 0) {
472     goto commands_only_pgc;
473   }
474
475   /* we've got enough info, time to open the title set data */
476   src->dvd_title = DVDOpenFile (src->dvd, title_set_nr, DVD_READ_TITLE_VOBS);
477   if (src->dvd_title == NULL)
478     goto title_open_failed;
479
480   GST_INFO_OBJECT (src, "Opened title %d, angle %d", title + 1, angle);
481   src->title = title;
482   src->angle = angle;
483
484   /* build event */
485
486   if (src->title_lang_event_pending) {
487     gst_event_unref (src->title_lang_event_pending);
488     src->title_lang_event_pending = NULL;
489   }
490
491   s = gst_structure_new ("application/x-gst-dvd",
492       "event", G_TYPE_STRING, "dvd-lang-codes", NULL);
493
494   /* so we can filter out invalid/unused streams (same for all chapters) */
495   cur_title_get_chapter_pgc (src, 0, &pgn0, &pgc0_id, &pgc0);
496
497   /* audio */
498   for (i = 0; i < src->vts_file->vtsi_mat->nr_of_vts_audio_streams; i++) {
499     const audio_attr_t *a;
500
501     /* audio stream present? */
502     if (pgc0 != NULL && (pgc0->audio_control[i] & 0x8000) == 0)
503       continue;
504
505     a = &src->vts_file->vtsi_mat->vts_audio_attr[i];
506
507     t = g_strdup_printf ("audio-%d-format", i);
508     gst_structure_set (s, t, G_TYPE_INT, (int) a->audio_format, NULL);
509     g_free (t);
510
511     if (a->lang_type) {
512       t = g_strdup_printf ("audio-%d-language", i);
513       lang_code[0] = (a->lang_code >> 8) & 0xff;
514       lang_code[1] = a->lang_code & 0xff;
515       gst_structure_set (s, t, G_TYPE_STRING, lang_code, NULL);
516       g_free (t);
517     } else {
518       lang_code[0] = '\0';
519     }
520
521     GST_INFO_OBJECT (src, "[%02d] Audio    %02d: lang='%s', format=%d",
522         src->title + 1, i, lang_code, (gint) a->audio_format);
523   }
524
525   /* subtitle */
526   for (i = 0; i < src->vts_file->vtsi_mat->nr_of_vts_subp_streams; i++) {
527     const subp_attr_t *u;
528
529     /* subpicture stream present? */
530     if (pgc0 != NULL && (pgc0->subp_control[i] & 0x80000000) == 0)
531       continue;
532
533     u = &src->vts_file->vtsi_mat->vts_subp_attr[i];
534
535     if (u->type) {
536       t = g_strdup_printf ("subtitle-%d-language", i);
537       lang_code[0] = (u->lang_code >> 8) & 0xff;
538       lang_code[1] = u->lang_code & 0xff;
539       gst_structure_set (s, t, G_TYPE_STRING, lang_code, NULL);
540       g_free (t);
541     } else {
542       lang_code[0] = '\0';
543     }
544
545     GST_INFO_OBJECT (src, "[%02d] Subtitle %02d: lang='%s', type=%d",
546         src->title + 1, i, lang_code, u->type);
547   }
548
549   src->title_lang_event_pending =
550       gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM, s);
551
552   /* dump seek tables */
553   src->vts_tmapt = src->vts_file->vts_tmapt;
554   if (src->vts_tmapt) {
555     gint i, j;
556
557     GST_LOG_OBJECT (src, "nr_of_tmaps = %d", src->vts_tmapt->nr_of_tmaps);
558     for (i = 0; i < src->vts_tmapt->nr_of_tmaps; ++i) {
559       GST_LOG_OBJECT (src, "======= Table %d ===================", i);
560       GST_LOG_OBJECT (src, "Offset relative to VTS_TMAPTI: %d",
561           src->vts_tmapt->tmap_offset[i]);
562       GST_LOG_OBJECT (src, "Time unit (seconds)          : %d",
563           src->vts_tmapt->tmap[i].tmu);
564       GST_LOG_OBJECT (src, "Number of entries            : %d",
565           src->vts_tmapt->tmap[i].nr_of_entries);
566       for (j = 0; j < src->vts_tmapt->tmap[i].nr_of_entries; j++) {
567         guint64 time;
568
569         time = src->vts_tmapt->tmap[i].tmu * (j + 1) * GST_SECOND;
570         GST_LOG_OBJECT (src, "Time: %" GST_TIME_FORMAT " VOBU "
571             "Sector: 0x%08x %s", GST_TIME_ARGS (time),
572             src->vts_tmapt->tmap[i].map_ent[j] & 0x7fffffff,
573             (src->vts_tmapt->tmap[i].map_ent[j] >> 31) ? "discontinuity" : "");
574       }
575     }
576   } else {
577     GST_WARNING_OBJECT (src, "no vts_tmapt - seeking will suck");
578   }
579
580   gst_dvd_read_src_get_chapter_starts (src);
581
582   return TRUE;
583
584   /* ERRORS */
585 invalid_title:
586   {
587     GST_WARNING_OBJECT (src, "Invalid title %d (only %d available)",
588         title, num_titles);
589     return FALSE;
590   }
591 ifo_open_failed:
592   {
593     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
594         (_("Could not open DVD title %d"), title_set_nr),
595         ("ifoOpen(%d) failed: %s", title_set_nr, g_strerror (errno)));
596     return FALSE;
597   }
598 title_open_failed:
599   {
600     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
601         (_("Could not open DVD title %d"), title_set_nr),
602         ("Can't open title VOBS (VTS_%02d_1.VOB)", title_set_nr));
603     return FALSE;
604   }
605 commands_only_pgc:
606   {
607     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
608         (_("Could not open DVD title %d. Interactive titles are not supported "
609                 "by this element"), title_set_nr),
610         ("Commands-only PGC, not supported, use rsndvdbin"));
611     return FALSE;
612   }
613 }
614
615 /* FIXME: double-check this function, compare against original */
616 static gint
617 gst_dvd_read_src_get_next_cell (GstDvdReadSrc * src, pgc_t * pgc, gint cell)
618 {
619   /* Check if we're entering an angle block. */
620   if (pgc->cell_playback[cell].block_type != BLOCK_TYPE_ANGLE_BLOCK)
621     return (cell + 1);
622
623   while (pgc->cell_playback[cell].block_mode != BLOCK_MODE_LAST_CELL)
624     ++cell;
625
626   return cell + 1;
627 }
628
629 /* Returns true if the pack is a NAV pack */
630 static gboolean
631 gst_dvd_read_src_is_nav_pack (const guint8 * data, gint lbn, dsi_t * dsi_pack)
632 {
633   if (GST_READ_UINT32_BE (data + 0x26) != 0x000001BF)
634     return FALSE;
635
636   /* Check that this is substream 0 (PCI) */
637   if (data[0x2c] != 0)
638     return FALSE;
639
640   if (GST_READ_UINT32_BE (data + 0x400) != 0x000001BF)
641     return FALSE;
642
643   /* Check that this is substream 1 (DSI) */
644   if (data[0x406] != 1)
645     return FALSE;
646
647   /* Check sizes of PCI and DSI packets */
648   if (GST_READ_UINT16_BE (data + 0x2a) != 0x03d4)
649     return FALSE;
650
651   if (GST_READ_UINT16_BE (data + 0x404) != 0x03fa)
652     return FALSE;
653
654   /* Read the DSI packet into the provided struct and check it */
655   navRead_DSI (dsi_pack, (unsigned char *) data + DSI_START_BYTE);
656   if (lbn != dsi_pack->dsi_gi.nv_pck_lbn)
657     return FALSE;
658
659   return TRUE;
660 }
661
662 /* find time for sector from index, returns NONE if there is no exact match */
663 static GstClockTime
664 gst_dvd_read_src_get_time_for_sector (GstDvdReadSrc * src, guint sector)
665 {
666   gint i, j;
667
668   if (src->vts_tmapt == NULL || src->vts_tmapt->nr_of_tmaps == 0)
669     return GST_CLOCK_TIME_NONE;
670
671   for (i = 0; i < src->vts_tmapt->nr_of_tmaps; ++i) {
672     for (j = 0; j < src->vts_tmapt->tmap[i].nr_of_entries; ++j) {
673       if ((src->vts_tmapt->tmap[i].map_ent[j] & 0x7fffffff) == sector)
674         return src->vts_tmapt->tmap[i].tmu * (j + 1) * GST_SECOND;
675     }
676   }
677
678   if (sector == 0)
679     return (GstClockTime) 0;
680
681   return GST_CLOCK_TIME_NONE;
682 }
683
684 /* returns the sector in the index at (or before) the given time, or -1 */
685 static gint
686 gst_dvd_read_src_get_sector_from_time (GstDvdReadSrc * src, GstClockTime ts)
687 {
688   gint sector, j;
689
690   if (src->vts_tmapt == NULL || src->vts_tmapt->nr_of_tmaps < src->ttn)
691     return -1;
692
693   sector = 0;
694   for (j = 0; j < src->vts_tmapt->tmap[src->ttn - 1].nr_of_entries; ++j) {
695     GstClockTime entry_time;
696
697     entry_time = src->vts_tmapt->tmap[src->ttn - 1].tmu * (j + 1) * GST_SECOND;
698     if (entry_time <= ts) {
699       sector = src->vts_tmapt->tmap[src->ttn - 1].map_ent[j] & 0x7fffffff;
700     }
701     if (entry_time >= ts) {
702       return sector;
703     }
704   }
705
706   if (ts == 0)
707     return 0;
708
709   return -1;
710 }
711
712 typedef enum
713 {
714   GST_DVD_READ_OK = 0,
715   GST_DVD_READ_ERROR = -1,
716   GST_DVD_READ_EOS = -2,
717   GST_DVD_READ_AGAIN = -3
718 } GstDvdReadReturn;
719
720 static GstDvdReadReturn
721 gst_dvd_read_src_read (GstDvdReadSrc * src, gint angle, gint new_seek,
722     GstBuffer ** p_buf)
723 {
724   GstBuffer *buf;
725   GstSegment *seg;
726   guint8 oneblock[DVD_VIDEO_LB_LEN];
727   dsi_t dsi_pack;
728   guint next_vobu, cur_output_size;
729   gint len;
730   gint retries;
731   gint64 next_time;
732   guint8 *data;
733
734   seg = &(GST_BASE_SRC (src)->segment);
735
736   /* playback by cell in this pgc, starting at the cell for our chapter */
737   if (new_seek)
738     src->cur_cell = src->start_cell;
739
740 again:
741
742   if (src->cur_cell >= src->last_cell) {
743     /* advance to next chapter */
744     if (src->chapter == (src->num_chapters - 1) ||
745         (seg->format == chapter_format && seg->stop != -1 &&
746             src->chapter == (seg->stop - 1))) {
747       GST_DEBUG_OBJECT (src, "end of chapter segment");
748       goto eos;
749     }
750
751     GST_INFO_OBJECT (src, "end of chapter %d, switch to next",
752         src->chapter + 1);
753
754     ++src->chapter;
755     gst_dvd_read_src_goto_chapter (src, src->chapter);
756
757     return GST_DVD_READ_AGAIN;
758   }
759
760   if (src->new_cell || new_seek) {
761     if (!new_seek) {
762       src->cur_cell = src->next_cell;
763       if (src->cur_cell >= src->last_cell) {
764         GST_LOG_OBJECT (src, "last cell in chapter");
765         goto again;
766       }
767     }
768
769     /* take angle into account */
770     if (src->cur_pgc->cell_playback[src->cur_cell].block_type
771         == BLOCK_TYPE_ANGLE_BLOCK)
772       src->cur_cell += angle;
773
774     /* calculate next cell */
775     src->next_cell =
776         gst_dvd_read_src_get_next_cell (src, src->cur_pgc, src->cur_cell);
777
778     /* we loop until we're out of this cell */
779     src->cur_pack = src->cur_pgc->cell_playback[src->cur_cell].first_sector;
780     src->new_cell = FALSE;
781     GST_DEBUG_OBJECT (src, "Starting new cell %d @ pack %d", src->cur_cell,
782         src->cur_pack);
783   }
784
785   if (src->cur_pack >= src->cur_pgc->cell_playback[src->cur_cell].last_sector) {
786     src->new_cell = TRUE;
787     GST_LOG_OBJECT (src, "Beyond last sector for cell %d, going to next cell",
788         src->cur_cell);
789     return GST_DVD_READ_AGAIN;
790   }
791
792   /* read NAV packet */
793   retries = 0;
794 nav_retry:
795   retries++;
796
797   len = DVDReadBlocks (src->dvd_title, src->cur_pack, 1, oneblock);
798   if (len != 1)
799     goto read_error;
800
801   if (!gst_dvd_read_src_is_nav_pack (oneblock, src->cur_pack, &dsi_pack)) {
802     GST_LOG_OBJECT (src, "Skipping nav packet @ pack %d", src->cur_pack);
803     src->cur_pack++;
804
805     if (retries < 2000) {
806       goto nav_retry;
807     } else {
808       GST_LOG_OBJECT (src, "No nav packet @ pack %d after 2000 blocks",
809           src->cur_pack);
810       goto read_error;
811     }
812   }
813
814   /* determine where we go next. These values are the ones we
815    * mostly care about */
816   cur_output_size = dsi_pack.dsi_gi.vobu_ea + 1;
817
818   /* If we're not at the end of this cell, we can determine the next
819    * VOBU to display using the VOBU_SRI information section of the
820    * DSI.  Using this value correctly follows the current angle,
821    * avoiding the doubled scenes in The Matrix, and makes our life
822    * really happy.
823    *
824    * Otherwise, we set our next address past the end of this cell to
825    * force the code above to go to the next cell in the program. */
826   if (dsi_pack.vobu_sri.next_vobu != SRI_END_OF_CELL) {
827     next_vobu = src->cur_pack + (dsi_pack.vobu_sri.next_vobu & 0x7fffffff);
828   } else {
829     next_vobu = src->cur_pgc->cell_playback[src->cur_cell].last_sector + 1;
830   }
831
832   g_assert (cur_output_size < 1024);
833
834   /* create the buffer (TODO: use buffer pool?) */
835   buf = gst_buffer_new_allocate (NULL, cur_output_size * DVD_VIDEO_LB_LEN, 0);
836
837   GST_LOG_OBJECT (src, "Going to read %u sectors @ pack %d", cur_output_size,
838       src->cur_pack);
839
840   data = gst_buffer_map (buf, NULL, NULL, GST_MAP_WRITE);
841   /* read in and output cursize packs */
842   len = DVDReadBlocks (src->dvd_title, src->cur_pack, cur_output_size, data);
843
844   if (len != cur_output_size)
845     goto block_read_error;
846
847   gst_buffer_unmap (buf, data, cur_output_size * DVD_VIDEO_LB_LEN);
848   /* GST_BUFFER_OFFSET (buf) = priv->cur_pack * DVD_VIDEO_LB_LEN; */
849   GST_BUFFER_TIMESTAMP (buf) =
850       gst_dvd_read_src_get_time_for_sector (src, src->cur_pack);
851
852   *p_buf = buf;
853
854   GST_LOG_OBJECT (src, "Read %u sectors", cur_output_size);
855
856   src->cur_pack = next_vobu;
857
858   next_time = GST_BUFFER_TIMESTAMP (buf);
859   if (GST_CLOCK_TIME_IS_VALID (next_time) && seg->format == GST_FORMAT_TIME &&
860       GST_CLOCK_TIME_IS_VALID (seg->stop) &&
861       next_time > seg->stop + 5 * GST_SECOND) {
862     GST_DEBUG_OBJECT (src, "end of TIME segment");
863     goto eos;
864   }
865
866   return GST_DVD_READ_OK;
867
868   /* ERRORS */
869 eos:
870   {
871     GST_INFO_OBJECT (src, "Reached end-of-segment/stream - EOS");
872     return GST_DVD_READ_EOS;
873   }
874 read_error:
875   {
876     GST_ERROR_OBJECT (src, "Read failed for block %d", src->cur_pack);
877     return GST_DVD_READ_ERROR;
878   }
879 block_read_error:
880   {
881     GST_ERROR_OBJECT (src, "Read failed for %d blocks at %d",
882         cur_output_size, src->cur_pack);
883     gst_buffer_unmap (buf, data, 0);
884     gst_buffer_unref (buf);
885     return GST_DVD_READ_ERROR;
886   }
887 }
888
889 /* we don't cache the result on purpose */
890 static gboolean
891 gst_dvd_read_descrambler_available (void)
892 {
893   GModule *module;
894   gpointer sym;
895   gsize res;
896
897   module = g_module_open ("libdvdcss", 0);
898   if (module != NULL) {
899     res = g_module_symbol (module, "dvdcss_open", &sym);
900     g_module_close (module);
901   } else {
902     res = FALSE;
903   }
904
905   return res;
906 }
907
908 static GstFlowReturn
909 gst_dvd_read_src_create (GstPushSrc * pushsrc, GstBuffer ** p_buf)
910 {
911   GstDvdReadSrc *src = GST_DVD_READ_SRC (pushsrc);
912   GstPad *srcpad;
913   gint res;
914
915   g_return_val_if_fail (src->dvd != NULL, GST_FLOW_ERROR);
916
917   srcpad = GST_BASE_SRC (src)->srcpad;
918
919   if (src->need_newsegment) {
920     GstSegment seg;
921
922     gst_segment_init (&seg, GST_FORMAT_BYTES);
923     seg.start = src->cur_pack * DVD_VIDEO_LB_LEN;
924     seg.stop = -1;
925     seg.time = 0;
926     gst_pad_push_event (srcpad, gst_event_new_segment (&seg));
927     src->need_newsegment = FALSE;
928   }
929
930   if (src->new_seek) {
931     gst_dvd_read_src_goto_title (src, src->title, src->angle);
932     gst_dvd_read_src_goto_chapter (src, src->chapter);
933
934     src->new_seek = FALSE;
935     src->change_cell = TRUE;
936   }
937
938   if (src->title_lang_event_pending) {
939     gst_pad_push_event (srcpad, src->title_lang_event_pending);
940     src->title_lang_event_pending = NULL;
941   }
942
943   if (src->pending_clut_event) {
944     gst_pad_push_event (srcpad, src->pending_clut_event);
945     src->pending_clut_event = NULL;
946   }
947
948   /* read it in */
949   do {
950     res = gst_dvd_read_src_read (src, src->angle, src->change_cell, p_buf);
951   } while (res == GST_DVD_READ_AGAIN);
952
953   switch (res) {
954     case GST_DVD_READ_ERROR:{
955       /* FIXME: figure out a way to detect if scrambling is the problem */
956       if (!gst_dvd_read_descrambler_available ()) {
957         GST_ELEMENT_ERROR (src, RESOURCE, READ,
958             (_("Could not read DVD. This may be because the DVD is encrypted "
959                     "and a DVD decryption library is not installed.")), (NULL));
960       } else {
961         GST_ELEMENT_ERROR (src, RESOURCE, READ, (_("Could not read DVD.")),
962             (NULL));
963       }
964       return GST_FLOW_ERROR;
965     }
966     case GST_DVD_READ_EOS:{
967       return GST_FLOW_UNEXPECTED;
968     }
969     case GST_DVD_READ_OK:{
970       src->change_cell = FALSE;
971       return GST_FLOW_OK;
972     }
973     default:
974       break;
975   }
976
977   g_return_val_if_reached (GST_FLOW_UNEXPECTED);
978 }
979
980 static void
981 gst_dvd_read_src_set_property (GObject * object, guint prop_id,
982     const GValue * value, GParamSpec * pspec)
983 {
984   GstDvdReadSrc *src = GST_DVD_READ_SRC (object);
985   gboolean started;
986
987   GST_OBJECT_LOCK (src);
988   started = GST_OBJECT_FLAG_IS_SET (src, GST_BASE_SRC_STARTED);
989
990   switch (prop_id) {
991     case ARG_DEVICE:{
992       if (started) {
993         g_warning ("%s: property '%s' needs to be set before the device is "
994             "opened", GST_ELEMENT_NAME (src), pspec->name);
995         break;;
996       }
997
998       g_free (src->location);
999       /* clear the filename if we get a NULL (is that possible?) */
1000       if (g_value_get_string (value) == NULL) {
1001         src->location = g_strdup ("/dev/dvd");
1002       } else {
1003         src->location = g_strdup (g_value_get_string (value));
1004       }
1005       break;
1006     }
1007     case ARG_TITLE:
1008       src->uri_title = g_value_get_int (value);
1009       if (started) {
1010         src->title = src->uri_title - 1;
1011         src->new_seek = TRUE;
1012       }
1013       break;
1014     case ARG_CHAPTER:
1015       src->uri_chapter = g_value_get_int (value);
1016       if (started) {
1017         src->chapter = src->uri_chapter - 1;
1018         src->new_seek = TRUE;
1019       }
1020       break;
1021     case ARG_ANGLE:
1022       src->uri_angle = g_value_get_int (value);
1023       if (started) {
1024         src->angle = src->uri_angle - 1;
1025       }
1026       break;
1027     default:
1028       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1029       break;
1030   }
1031
1032   GST_OBJECT_UNLOCK (src);
1033 }
1034
1035 static void
1036 gst_dvd_read_src_get_property (GObject * object, guint prop_id, GValue * value,
1037     GParamSpec * pspec)
1038 {
1039   GstDvdReadSrc *src = GST_DVD_READ_SRC (object);
1040
1041   GST_OBJECT_LOCK (src);
1042
1043   switch (prop_id) {
1044     case ARG_DEVICE:
1045       g_value_set_string (value, src->location);
1046       break;
1047     case ARG_TITLE:
1048       g_value_set_int (value, src->uri_title);
1049       break;
1050     case ARG_CHAPTER:
1051       g_value_set_int (value, src->uri_chapter);
1052       break;
1053     case ARG_ANGLE:
1054       g_value_set_int (value, src->uri_angle);
1055       break;
1056     default:
1057       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1058       break;
1059   }
1060
1061   GST_OBJECT_UNLOCK (src);
1062 }
1063
1064 static gboolean
1065 gst_dvd_read_src_get_size (GstDvdReadSrc * src, gint64 * size)
1066 {
1067   gboolean ret = FALSE;
1068
1069   if (src->dvd_title) {
1070     gsize blocks;
1071
1072     blocks = DVDFileSize (src->dvd_title);
1073     if (blocks >= 0) {
1074       *size = (gint64) blocks *DVD_VIDEO_LB_LEN;
1075
1076       ret = TRUE;
1077     } else {
1078       GST_WARNING_OBJECT (src, "DVDFileSize(%p) failed!", src->dvd_title);
1079     }
1080   }
1081
1082   return ret;
1083 }
1084
1085 /*** Querying and seeking ***/
1086
1087 static gboolean
1088 gst_dvd_read_src_handle_seek_event (GstDvdReadSrc * src, GstEvent * event)
1089 {
1090   GstSeekFlags flags;
1091   GstSeekType cur_type, end_type;
1092   gint64 new_off, total;
1093   GstFormat format;
1094   GstPad *srcpad;
1095   gboolean query_ok;
1096   gdouble rate;
1097
1098   gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &new_off,
1099       &end_type, NULL);
1100
1101   if (rate <= 0.0) {
1102     GST_DEBUG_OBJECT (src, "cannot do backwards playback yet");
1103     return FALSE;
1104   }
1105
1106   if (end_type != GST_SEEK_TYPE_NONE) {
1107     if ((format != chapter_format && format != GST_FORMAT_TIME) ||
1108         end_type != GST_SEEK_TYPE_SET) {
1109       GST_DEBUG_OBJECT (src, "end seek type not supported");
1110       return FALSE;
1111     }
1112   }
1113
1114   if (cur_type != GST_SEEK_TYPE_SET) {
1115     GST_DEBUG_OBJECT (src, "only SEEK_TYPE_SET is supported");
1116     return FALSE;
1117   }
1118
1119   if (format == angle_format) {
1120     GST_OBJECT_LOCK (src);
1121     if (new_off < 0 || new_off >= src->num_angles) {
1122       GST_OBJECT_UNLOCK (src);
1123       GST_DEBUG_OBJECT (src, "invalid angle %d, only %d available",
1124           src->num_angles, src->num_angles);
1125       return FALSE;
1126     }
1127     src->angle = (gint) new_off;
1128     GST_OBJECT_UNLOCK (src);
1129     GST_DEBUG_OBJECT (src, "switched to angle %d", (gint) new_off + 1);
1130     return TRUE;
1131   }
1132
1133   if (format != chapter_format && format != title_format &&
1134       format != GST_FORMAT_BYTES && format != GST_FORMAT_TIME) {
1135     GST_DEBUG_OBJECT (src, "unsupported seek format %d (%s)", format,
1136         gst_format_get_name (format));
1137     return FALSE;
1138   }
1139
1140   if (format == GST_FORMAT_BYTES) {
1141     GST_DEBUG_OBJECT (src, "Requested seek to byte %" G_GUINT64_FORMAT,
1142         new_off);
1143   } else if (format == GST_FORMAT_TIME) {
1144     GST_DEBUG_OBJECT (src, "Requested seek to time %" GST_TIME_FORMAT,
1145         GST_TIME_ARGS (new_off));
1146     if (gst_dvd_read_src_get_sector_from_time (src, new_off) < 0) {
1147       GST_DEBUG_OBJECT (src, "Can't find sector for requested time");
1148       return FALSE;
1149     }
1150   }
1151
1152   srcpad = GST_BASE_SRC_PAD (src);
1153
1154   /* check whether the seek looks reasonable (ie within possible range) */
1155   if (format == GST_FORMAT_BYTES) {
1156     GST_OBJECT_LOCK (src);
1157     query_ok = gst_dvd_read_src_get_size (src, &total);
1158     GST_OBJECT_UNLOCK (src);
1159   } else {
1160     query_ok = gst_pad_query_duration (srcpad, format, &total);
1161   }
1162
1163   if (!query_ok) {
1164     GST_DEBUG_OBJECT (src, "Failed to query duration in format %s",
1165         gst_format_get_name (format));
1166     return FALSE;
1167   }
1168
1169   GST_DEBUG_OBJECT (src, "Total      %s: %12" G_GINT64_FORMAT,
1170       gst_format_get_name (format), total);
1171   GST_DEBUG_OBJECT (src, "Seek to    %s: %12" G_GINT64_FORMAT,
1172       gst_format_get_name (format), new_off);
1173
1174   if (new_off >= total) {
1175     GST_DEBUG_OBJECT (src, "Seek position out of range");
1176     return FALSE;
1177   }
1178
1179   /* set segment to seek format; this allows us to use the do_seek
1180    * virtual function and let the base source handle all the tricky
1181    * stuff for us. We don't use the segment internally anyway */
1182   /* FIXME: can't take the stream lock here - what to do? */
1183   GST_OBJECT_LOCK (src);
1184   GST_BASE_SRC (src)->segment.format = format;
1185   GST_BASE_SRC (src)->segment.start = 0;
1186   GST_BASE_SRC (src)->segment.stop = total;
1187   GST_BASE_SRC (src)->segment.duration = total;
1188   GST_OBJECT_UNLOCK (src);
1189
1190   return GST_BASE_SRC_CLASS (parent_class)->event (GST_BASE_SRC (src), event);
1191 }
1192
1193 static void
1194 gst_dvd_read_src_get_sector_bounds (GstDvdReadSrc * src, gint * first,
1195     gint * last)
1196 {
1197   gint c1, c2, tmp;
1198   cur_title_get_chapter_bounds (src, 0, &c1, &tmp);
1199   cur_title_get_chapter_bounds (src, src->num_chapters - 1, &tmp, &c2);
1200   *first = src->cur_pgc->cell_playback[c1].first_sector;
1201   *last = src->cur_pgc->cell_playback[c2].last_sector;
1202 }
1203
1204 static gboolean
1205 gst_dvd_read_src_do_seek (GstBaseSrc * basesrc, GstSegment * s)
1206 {
1207   GstDvdReadSrc *src;
1208
1209   src = GST_DVD_READ_SRC (basesrc);
1210
1211   GST_DEBUG_OBJECT (src, "Seeking to %s: %12" G_GINT64_FORMAT,
1212       gst_format_get_name (s->format), s->position);
1213
1214   if (s->format == sector_format || s->format == GST_FORMAT_BYTES
1215       || s->format == GST_FORMAT_TIME) {
1216     guint old;
1217
1218     old = src->cur_pack;
1219
1220     if (s->format == sector_format) {
1221       gint first, last;
1222       gst_dvd_read_src_get_sector_bounds (src, &first, &last);
1223       GST_DEBUG_OBJECT (src, "Format is sector, seeking to %d", s->position);
1224       src->cur_pack = s->position;
1225       if (src->cur_pack < first)
1226         src->cur_pack = first;
1227       if (src->cur_pack > last)
1228         src->cur_pack = last;
1229     } else if (s->format == GST_FORMAT_TIME) {
1230       gint sector;
1231       GST_DEBUG_OBJECT (src, "Format is time");
1232
1233       sector = gst_dvd_read_src_get_sector_from_time (src, s->position);
1234
1235       GST_DEBUG_OBJECT (src, "Time %" GST_TIME_FORMAT " => sector %d",
1236           GST_TIME_ARGS (s->position), sector);
1237
1238       /* really shouldn't happen, we've checked this earlier ... */
1239       g_return_val_if_fail (sector >= 0, FALSE);
1240
1241       src->cur_pack = sector;
1242     } else {
1243       /* byte format */
1244       gint first, last;
1245       gst_dvd_read_src_get_sector_bounds (src, &first, &last);
1246       GST_DEBUG_OBJECT (src, "Format is byte");
1247       src->cur_pack = s->position / DVD_VIDEO_LB_LEN;
1248       if (((gint64) src->cur_pack * DVD_VIDEO_LB_LEN) != s->position) {
1249         GST_LOG_OBJECT (src, "rounded down offset %" G_GINT64_FORMAT " => %"
1250             G_GINT64_FORMAT, s->position,
1251             (gint64) src->cur_pack * DVD_VIDEO_LB_LEN);
1252       }
1253       src->cur_pack += first;
1254     }
1255
1256     if (!gst_dvd_read_src_goto_sector (src, src->angle)) {
1257       GST_DEBUG_OBJECT (src, "seek to sector 0x%08x failed", src->cur_pack);
1258       src->cur_pack = old;
1259       return FALSE;
1260     }
1261
1262     GST_LOG_OBJECT (src, "seek to sector 0x%08x ok", src->cur_pack);
1263   } else if (s->format == chapter_format) {
1264     if (!gst_dvd_read_src_goto_chapter (src, (gint) s->position)) {
1265       GST_DEBUG_OBJECT (src, "seek to chapter %d failed",
1266           (gint) s->position + 1);
1267       return FALSE;
1268     }
1269     GST_INFO_OBJECT (src, "seek to chapter %d ok", (gint) s->position + 1);
1270     src->chapter = s->position;
1271   } else if (s->format == title_format) {
1272     if (!gst_dvd_read_src_goto_title (src, (gint) s->position, src->angle) ||
1273         !gst_dvd_read_src_goto_chapter (src, 0)) {
1274       GST_DEBUG_OBJECT (src, "seek to title %d failed", (gint) s->position);
1275       return FALSE;
1276     }
1277     src->title = (gint) s->position;
1278     src->chapter = 0;
1279     GST_INFO_OBJECT (src, "seek to title %d ok", src->title + 1);
1280   } else {
1281     g_return_val_if_reached (FALSE);
1282   }
1283
1284   src->need_newsegment = TRUE;
1285   return TRUE;
1286 }
1287
1288 static gboolean
1289 gst_dvd_read_src_src_event (GstBaseSrc * basesrc, GstEvent * event)
1290 {
1291   GstDvdReadSrc *src = GST_DVD_READ_SRC (basesrc);
1292   gboolean res;
1293
1294   GST_LOG_OBJECT (src, "handling %s event", GST_EVENT_TYPE_NAME (event));
1295
1296   switch (GST_EVENT_TYPE (event)) {
1297     case GST_EVENT_SEEK:
1298       res = gst_dvd_read_src_handle_seek_event (src, event);
1299       break;
1300     default:
1301       res = GST_BASE_SRC_CLASS (parent_class)->event (basesrc, event);
1302       break;
1303   }
1304
1305   return res;
1306 }
1307
1308 static GstEvent *
1309 gst_dvd_read_src_make_clut_change_event (GstDvdReadSrc * src,
1310     const guint * clut)
1311 {
1312   GstStructure *structure;
1313   gchar name[16];
1314   gint i;
1315
1316   structure = gst_structure_new ("application/x-gst-dvd",
1317       "event", G_TYPE_STRING, "dvd-spu-clut-change", NULL);
1318
1319   /* Create a separate field for each value in the table. */
1320   for (i = 0; i < 16; i++) {
1321     g_snprintf (name, sizeof (name), "clut%02d", i);
1322     gst_structure_set (structure, name, G_TYPE_INT, (int) clut[i], NULL);
1323   }
1324
1325   /* Create the DVD event and put the structure into it. */
1326   return gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM, structure);
1327 }
1328
1329 static gint64
1330 gst_dvd_read_src_convert_timecode (dvd_time_t * time)
1331 {
1332   gint64 ret_time;
1333   const gint64 one_hour = 3600 * GST_SECOND;
1334   const gint64 one_min = 60 * GST_SECOND;
1335
1336   g_return_val_if_fail ((time->hour >> 4) < 0xa
1337       && (time->hour & 0xf) < 0xa, -1);
1338   g_return_val_if_fail ((time->minute >> 4) < 0x7
1339       && (time->minute & 0xf) < 0xa, -1);
1340   g_return_val_if_fail ((time->second >> 4) < 0x7
1341       && (time->second & 0xf) < 0xa, -1);
1342
1343   ret_time = ((time->hour >> 4) * 10 + (time->hour & 0xf)) * one_hour;
1344   ret_time += ((time->minute >> 4) * 10 + (time->minute & 0xf)) * one_min;
1345   ret_time += ((time->second >> 4) * 10 + (time->second & 0xf)) * GST_SECOND;
1346
1347   return ret_time;
1348 }
1349
1350 static gboolean
1351 gst_dvd_read_src_do_duration_query (GstDvdReadSrc * src, GstQuery * query)
1352 {
1353   GstFormat format;
1354   gint64 val;
1355
1356   gst_query_parse_duration (query, &format, NULL);
1357
1358   switch (format) {
1359     case GST_FORMAT_TIME:{
1360       if (src->cur_pgc == NULL)
1361         return FALSE;
1362       val = gst_dvd_read_src_convert_timecode (&src->cur_pgc->playback_time);
1363       if (val < 0)
1364         return FALSE;
1365       break;
1366     }
1367     case GST_FORMAT_BYTES:{
1368       if (!gst_dvd_read_src_get_size (src, &val))
1369         return FALSE;
1370       break;
1371     }
1372     default:{
1373       if (format == sector_format) {
1374         val = DVDFileSize (src->dvd_title);
1375       } else if (format == title_format) {
1376         val = src->tt_srpt->nr_of_srpts;
1377       } else if (format == chapter_format) {
1378         val = src->num_chapters;
1379       } else if (format == angle_format) {
1380         val = src->tt_srpt->title[src->title].nr_of_angles;
1381       } else {
1382         GST_DEBUG_OBJECT (src, "Don't know how to handle format %d (%s)",
1383             format, gst_format_get_name (format));
1384         return FALSE;
1385       }
1386       break;
1387     }
1388   }
1389
1390   GST_LOG_OBJECT (src, "duration = %" G_GINT64_FORMAT " %s", val,
1391       gst_format_get_name (format));
1392
1393   gst_query_set_duration (query, format, val);
1394   return TRUE;
1395 }
1396
1397 static gboolean
1398 gst_dvd_read_src_do_position_query (GstDvdReadSrc * src, GstQuery * query)
1399 {
1400   GstFormat format;
1401   gint64 val;
1402
1403   gst_query_parse_position (query, &format, NULL);
1404
1405   switch (format) {
1406     case GST_FORMAT_BYTES:{
1407       val = (gint64) src->cur_pack * DVD_VIDEO_LB_LEN;
1408       break;
1409     }
1410     default:{
1411       if (format == sector_format) {
1412         val = src->cur_pack;
1413       } else if (format == title_format) {
1414         val = src->title;
1415       } else if (format == chapter_format) {
1416         val = src->chapter;
1417       } else if (format == angle_format) {
1418         val = src->angle;
1419       } else {
1420         GST_DEBUG_OBJECT (src, "Don't know how to handle format %d (%s)",
1421             format, gst_format_get_name (format));
1422         return FALSE;
1423       }
1424       break;
1425     }
1426   }
1427
1428   GST_LOG_OBJECT (src, "position = %" G_GINT64_FORMAT " %s", val,
1429       gst_format_get_name (format));
1430
1431   gst_query_set_position (query, format, val);
1432   return TRUE;
1433 }
1434
1435 static gboolean
1436 gst_dvd_read_src_do_convert_query (GstDvdReadSrc * src, GstQuery * query)
1437 {
1438   GstFormat src_format, dest_format;
1439   gboolean ret = FALSE;
1440   gint64 src_val, dest_val = -1;
1441
1442   gst_query_parse_convert (query, &src_format, &src_val, &dest_format, NULL);
1443
1444   if (src_format == dest_format) {
1445     dest_val = src_val;
1446     ret = TRUE;
1447     goto done;
1448   }
1449
1450   /* Formats to consider: TIME, DEFAULT, BYTES, title, chapter, sector.
1451    * Note: title and chapter are counted as starting from 0 here, just like
1452    * in the context of seek events. Another note: DEFAULT format is undefined */
1453
1454   if (src_format == GST_FORMAT_BYTES) {
1455     src_format = sector_format;
1456     src_val /= DVD_VIDEO_LB_LEN;
1457   }
1458
1459   if (src_format == sector_format) {
1460     /* SECTOR => xyz */
1461     if (dest_format == GST_FORMAT_TIME && src_val < G_MAXUINT) {
1462       dest_val = gst_dvd_read_src_get_time_for_sector (src, (guint) src_val);
1463       ret = (dest_val >= 0);
1464     } else if (dest_format == GST_FORMAT_BYTES) {
1465       dest_val = src_val * DVD_VIDEO_LB_LEN;
1466       ret = TRUE;
1467     } else {
1468       ret = FALSE;
1469     }
1470   } else if (src_format == title_format) {
1471     /* TITLE => xyz */
1472     if (dest_format == GST_FORMAT_TIME) {
1473       /* not really true, but we use this to trick the base source into
1474        * handling seeks in title-format for us (the source won't know that
1475        * we changed the title in this case) (changing titles should really
1476        * be done with an interface rather than a seek, but for now we're
1477        * stuck with this mechanism. Fix in 0.11) */
1478       dest_val = (GstClockTime) 0;
1479       ret = TRUE;
1480     } else {
1481       ret = FALSE;
1482     }
1483   } else if (src_format == chapter_format) {
1484     /* CHAPTER => xyz */
1485     if (dest_format == GST_FORMAT_TIME) {
1486       if (src->num_chapters >= 0 && src_val < src->num_chapters) {
1487         dest_val = src->chapter_starts[src_val];
1488         ret = TRUE;
1489       }
1490     } else if (dest_format == sector_format) {
1491     } else {
1492       ret = FALSE;
1493     }
1494   } else if (src_format == GST_FORMAT_TIME) {
1495     /* TIME => xyz */
1496     if (dest_format == sector_format || dest_format == GST_FORMAT_BYTES) {
1497       dest_val = gst_dvd_read_src_get_sector_from_time (src, src_val);
1498       ret = (dest_val >= 0);
1499       if (dest_format == GST_FORMAT_BYTES)
1500         dest_val *= DVD_VIDEO_LB_LEN;
1501     } else if (dest_format == chapter_format) {
1502       if (src->chapter_starts != NULL) {
1503         gint i;
1504
1505         for (i = src->num_chapters - 1; i >= 0; --i) {
1506           if (src->chapter_starts && src->chapter_starts[i] >= src_val) {
1507             dest_val = i;
1508             ret = TRUE;
1509             break;
1510           }
1511         }
1512       } else {
1513         ret = FALSE;
1514       }
1515     } else {
1516       ret = FALSE;
1517     }
1518   } else {
1519     ret = FALSE;
1520   }
1521
1522 done:
1523
1524   if (ret) {
1525     gst_query_set_convert (query, src_format, src_val, dest_format, dest_val);
1526   }
1527
1528   return ret;
1529 }
1530
1531 static gboolean
1532 gst_dvd_read_src_src_query (GstBaseSrc * basesrc, GstQuery * query)
1533 {
1534   GstDvdReadSrc *src = GST_DVD_READ_SRC (basesrc);
1535   gboolean started;
1536   gboolean res = TRUE;
1537
1538   GST_LOG_OBJECT (src, "handling %s query",
1539       gst_query_type_get_name (GST_QUERY_TYPE (query)));
1540
1541   GST_OBJECT_LOCK (src);
1542   started = (GST_OBJECT_FLAG_IS_SET (src, GST_BASE_SRC_STARTED));
1543   GST_OBJECT_UNLOCK (src);
1544
1545   if (!started) {
1546     GST_DEBUG_OBJECT (src, "query failed: not started");
1547     return FALSE;
1548   }
1549
1550   switch (GST_QUERY_TYPE (query)) {
1551     case GST_QUERY_DURATION:
1552       GST_OBJECT_LOCK (src);
1553       res = gst_dvd_read_src_do_duration_query (src, query);
1554       GST_OBJECT_UNLOCK (src);
1555       break;
1556     case GST_QUERY_POSITION:
1557       GST_OBJECT_LOCK (src);
1558       res = gst_dvd_read_src_do_position_query (src, query);
1559       GST_OBJECT_UNLOCK (src);
1560       break;
1561     case GST_QUERY_CONVERT:
1562       GST_OBJECT_LOCK (src);
1563       res = gst_dvd_read_src_do_convert_query (src, query);
1564       GST_OBJECT_UNLOCK (src);
1565       break;
1566     default:
1567       res = GST_BASE_SRC_CLASS (parent_class)->query (basesrc, query);
1568       break;
1569   }
1570
1571   return res;
1572 }
1573
1574 static gboolean
1575 gst_dvd_read_src_goto_sector (GstDvdReadSrc * src, int angle)
1576 {
1577   gint seek_to = src->cur_pack;
1578   gint chapter, next, cur, i;
1579
1580   /* retrieve position */
1581   src->cur_pack = 0;
1582   GST_DEBUG_OBJECT (src, "Goto sector %d, angle %d, within %d chapters",
1583       seek_to, angle, src->num_chapters);
1584
1585   for (i = 0; i < src->num_chapters; i++) {
1586     gint c1, c2;
1587
1588     cur_title_get_chapter_bounds (src, i, &c1, &c2);
1589     GST_DEBUG_OBJECT (src, " Looking in chapter %d, bounds: %d %d", i, c1, c2);
1590
1591     for (next = cur = c1; cur < c2;) {
1592       gint first = src->cur_pgc->cell_playback[cur].first_sector;
1593       gint last = src->cur_pgc->cell_playback[cur].last_sector;
1594       GST_DEBUG_OBJECT (src, "Cell %d sector bounds: %d %d", cur, first, last);
1595       if (seek_to >= first && seek_to <= last) {
1596         GST_DEBUG_OBJECT (src, "Seek target found in chapter %d", i);
1597         chapter = i;
1598         goto done;
1599       }
1600       cur = next;
1601       if (src->cur_pgc->cell_playback[cur].block_type == BLOCK_TYPE_ANGLE_BLOCK)
1602         cur += angle;
1603       next = gst_dvd_read_src_get_next_cell (src, src->cur_pgc, cur);
1604     }
1605   }
1606
1607   GST_DEBUG_OBJECT (src, "Seek to sector %u failed", seek_to);
1608
1609   return FALSE;
1610
1611 done:
1612   {
1613     /* so chapter $chapter and cell $cur contain our sector
1614      * of interest. Let's go there! */
1615     GST_INFO_OBJECT (src, "Seek succeeded, going to chapter %u, cell %u",
1616         chapter + 1, cur);
1617
1618     gst_dvd_read_src_goto_chapter (src, chapter);
1619     src->cur_cell = cur;
1620     src->next_cell = next;
1621     src->new_cell = FALSE;
1622     src->cur_pack = seek_to;
1623
1624     return TRUE;
1625   }
1626 }
1627
1628
1629 /*** URI interface ***/
1630
1631 static GstURIType
1632 gst_dvd_read_src_uri_get_type (GType type)
1633 {
1634   return GST_URI_SRC;
1635 }
1636
1637 static gchar **
1638 gst_dvd_read_src_uri_get_protocols (GType type)
1639 {
1640   static gchar *protocols[] = { (gchar *) "dvd", NULL };
1641
1642   return protocols;
1643 }
1644
1645 static const gchar *
1646 gst_dvd_read_src_uri_get_uri (GstURIHandler * handler)
1647 {
1648   GstDvdReadSrc *src = GST_DVD_READ_SRC (handler);
1649
1650   GST_OBJECT_LOCK (src);
1651
1652   g_free (src->last_uri);
1653   src->last_uri = g_strdup_printf ("dvd://%d,%d,%d", src->uri_title,
1654       src->uri_chapter, src->uri_angle);
1655
1656   GST_OBJECT_UNLOCK (src);
1657
1658   return src->last_uri;
1659 }
1660
1661 static gboolean
1662 gst_dvd_read_src_uri_set_uri (GstURIHandler * handler, const gchar * uri)
1663 {
1664   GstDvdReadSrc *src = GST_DVD_READ_SRC (handler);
1665   gboolean ret;
1666   gchar *protocol;
1667
1668   protocol = gst_uri_get_protocol (uri);
1669   ret = (protocol != NULL && g_str_equal (protocol, "dvd"));
1670   g_free (protocol);
1671   protocol = NULL;
1672
1673   if (!ret)
1674     return ret;
1675
1676   /* parse out the new t/c/a and seek to them */
1677   {
1678     gchar *location = NULL;
1679     gchar **strs;
1680     gchar **strcur;
1681     gint pos = 0;
1682
1683     location = gst_uri_get_location (uri);
1684
1685     if (!location)
1686       return ret;
1687
1688     GST_OBJECT_LOCK (src);
1689
1690     src->uri_title = 1;
1691     src->uri_chapter = 1;
1692     src->uri_angle = 1;
1693
1694     strcur = strs = g_strsplit (location, ",", 0);
1695     while (strcur && *strcur) {
1696       gint val;
1697
1698       if (!sscanf (*strcur, "%d", &val))
1699         break;
1700
1701       if (val <= 0) {
1702         g_warning ("Invalid value %d in URI '%s'. Must be 1 or greater",
1703             val, location);
1704         break;
1705       }
1706
1707       switch (pos) {
1708         case 0:
1709           src->uri_title = val;
1710           break;
1711         case 1:
1712           src->uri_chapter = val;
1713           break;
1714         case 2:
1715           src->uri_angle = val;
1716           break;
1717       }
1718
1719       strcur++;
1720       pos++;
1721     }
1722
1723     if (pos > 0 && GST_OBJECT_FLAG_IS_SET (src, GST_BASE_SRC_STARTED)) {
1724       src->title = src->uri_title - 1;
1725       src->chapter = src->uri_chapter - 1;
1726       src->angle = src->uri_angle - 1;
1727       src->new_seek = TRUE;
1728     }
1729
1730     GST_OBJECT_UNLOCK (src);
1731
1732     g_strfreev (strs);
1733     g_free (location);
1734   }
1735
1736   return ret;
1737 }
1738
1739 static void
1740 gst_dvd_read_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1741 {
1742   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1743
1744   iface->get_type = gst_dvd_read_src_uri_get_type;
1745   iface->get_protocols = gst_dvd_read_src_uri_get_protocols;
1746   iface->get_uri = gst_dvd_read_src_uri_get_uri;
1747   iface->set_uri = gst_dvd_read_src_uri_set_uri;
1748 }
1749
1750 static gboolean
1751 plugin_init (GstPlugin * plugin)
1752 {
1753   GST_DEBUG_CATEGORY_INIT (gstgst_dvd_read_src_debug, "dvdreadsrc", 0,
1754       "DVD reader element based on dvdreadsrc");
1755
1756 #ifdef ENABLE_NLS
1757   GST_DEBUG ("binding text domain %s to locale dir %s", GETTEXT_PACKAGE,
1758       LOCALEDIR);
1759   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
1760   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1761 #endif /* ENABLE_NLS */
1762
1763   if (!gst_element_register (plugin, "dvdreadsrc", GST_RANK_SECONDARY,
1764           GST_TYPE_DVD_READ_SRC)) {
1765     return FALSE;
1766   }
1767
1768   return TRUE;
1769 }
1770
1771 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1772     GST_VERSION_MINOR,
1773     "dvdread",
1774     "Access a DVD with dvdread",
1775     plugin_init, VERSION, "GPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);