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