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