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