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