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