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