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