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