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