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