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