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