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