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