]> git.decadent.org.uk Git - videolink.git/blob - webdvd.cpp
Added more video standard parameters and organised them into structures.
[videolink.git] / webdvd.cpp
1 // Copyright 2005 Ben Hutchings <ben@decadentplace.org.uk>.
2 // See the file "COPYING" for licence details.
3
4 #include <cassert>
5 #include <exception>
6 #include <fstream>
7 #include <iomanip>
8 #include <iostream>
9 #include <memory>
10 #include <queue>
11 #include <set>
12 #include <string>
13
14 #include <stdlib.h>
15 #include <unistd.h>
16
17 #include <gdkmm/pixbuf.h>
18 #include <gtkmm/main.h>
19 #include <gtkmm/window.h>
20
21 #include <imglib2/ImageErrors.h>
22 #include <nsGUIEvent.h>
23 #include <nsIBoxObject.h>
24 #include <nsIContent.h>
25 #include <nsIDocShell.h>
26 #include <nsIDOMAbstractView.h>
27 #include <nsIDOMDocumentEvent.h>
28 #include <nsIDOMDocumentView.h>
29 #include <nsIDOMElement.h>
30 #include <nsIDOMEventTarget.h>
31 #include <nsIDOMHTMLDocument.h>
32 #include <nsIDOMMouseEvent.h>
33 #include <nsIDOMNSDocument.h>
34 #include <nsIDOMWindow.h>
35 #include <nsIEventStateManager.h>
36 #include <nsIInterfaceRequestorUtils.h>
37 #include <nsIURI.h> // required before nsILink.h
38 #include <nsILink.h>
39 #include <nsIPresContext.h>
40 #include <nsIPresShell.h>
41 #include <nsIWebBrowser.h>
42 #include <nsString.h>
43
44 #include "browserwidget.hpp"
45 #include "childiterator.hpp"
46 #include "dvd.hpp"
47 #include "framebuffer.hpp"
48 #include "linkiterator.hpp"
49 #include "pixbufs.hpp"
50 #include "stylesheets.hpp"
51 #include "video.hpp"
52 #include "xpcom_support.hpp"
53
54 using xpcom_support::check;
55
56 namespace
57 {
58     struct rectangle
59     {
60         int left, top;     // inclusive
61         int right, bottom; // exclusive
62
63         rectangle operator|=(const rectangle & other)
64             {
65                 if (other.empty())
66                 {
67                     // use current extents unchanged
68                 }
69                 else if (empty())
70                 {
71                     // use other extents
72                     *this = other;
73                 }
74                 else
75                 {
76                     // find rectangle enclosing both extents
77                     left = std::min(left, other.left);
78                     top = std::min(top, other.top);
79                     right = std::max(right, other.right);
80                     bottom = std::max(bottom, other.bottom);
81                 }
82
83                 return *this;
84             }
85
86         rectangle operator&=(const rectangle & other)
87             {
88                 // find rectangle enclosed in both extents
89                 left = std::max(left, other.left);
90                 top = std::max(top, other.top);
91                 right = std::max(left, std::min(right, other.right));
92                 bottom = std::max(top, std::min(bottom, other.bottom));
93                 return *this;
94             }
95
96         bool empty() const
97             {
98                 return left == right || bottom == top;
99             }
100     };
101
102     rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
103                             nsIDOMElement * elem)
104     {
105         rectangle result;
106
107         nsCOMPtr<nsIBoxObject> box;
108         check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
109         int width, height;
110         check(box->GetScreenX(&result.left));
111         check(box->GetScreenY(&result.top));
112         check(box->GetWidth(&width));
113         check(box->GetHeight(&height));
114         result.right = result.left + width;
115         result.bottom = result.top + height;
116
117         for (ChildIterator it = ChildIterator(elem), end; it != end; ++it)
118         {
119             nsCOMPtr<nsIDOMNode> child_node(*it);
120             PRUint16 child_type;
121             if (check(child_node->GetNodeType(&child_type)),
122                 child_type == nsIDOMNode::ELEMENT_NODE)
123             {
124                 nsCOMPtr<nsIDOMElement> child_elem(
125                     do_QueryInterface(child_node));
126                 result |= get_elem_rect(ns_doc, child_elem);
127             }
128         }
129
130         return result;
131     }
132
133     class WebDvdWindow : public Gtk::Window
134     {
135     public:
136         WebDvdWindow(const video::frame_params & frame_params);
137         void add_page(const std::string & uri);
138
139     private:
140         void add_video(const std::string & uri);
141         void load_next_page();
142         void on_net_state_change(const char * uri, gint flags, guint status);
143         void save_screenshot();
144         void process_links(nsIPresShell * pres_shell,
145                            nsIPresContext * pres_context,
146                            nsIDOMWindow * dom_window);
147         void generate_dvdauthor_file();
148
149         enum ResourceType { page_resource, video_resource };
150         typedef std::pair<ResourceType, int> ResourceEntry;
151         video::frame_params frame_params_;
152         BrowserWidget browser_widget_;
153         nsCOMPtr<nsIStyleSheet> stylesheet_;
154         std::queue<std::string> page_queue_;
155         std::map<std::string, ResourceEntry> resource_map_;
156         std::vector<std::vector<std::string> > page_links_;
157         std::vector<std::string> video_paths_;
158         bool loading_;
159         int pending_req_count_;
160         struct link_state;
161         std::auto_ptr<link_state> link_state_;
162     };
163
164     WebDvdWindow::WebDvdWindow(const video::frame_params & frame_params)
165             : frame_params_(frame_params),
166               stylesheet_(load_css("file://" WEBDVD_LIB_DIR "/webdvd.css")),
167               loading_(false),
168               pending_req_count_(0)
169     {
170         set_default_size(frame_params_.width, frame_params_.height);
171         add(browser_widget_);
172         browser_widget_.show();
173         browser_widget_.signal_net_state().connect(
174             SigC::slot(*this, &WebDvdWindow::on_net_state_change));
175     }
176
177     void WebDvdWindow::add_page(const std::string & uri)
178     {
179         if (resource_map_.insert(
180                 std::make_pair(uri, ResourceEntry(page_resource, 0)))
181             .second)
182         {
183             page_queue_.push(uri);
184             if (!loading_)
185                 load_next_page();
186         }
187     }
188
189     void WebDvdWindow::add_video(const std::string & uri)
190     {
191         if (resource_map_.insert(
192                 std::make_pair(uri, ResourceEntry(video_resource,
193                                                   video_paths_.size() + 1)))
194             .second)
195         {
196             // FIXME: Should accept some slightly different URI prefixes
197             // (e.g. file://localhost/) and decode any URI-escaped
198             // characters in the path.
199             assert(uri.compare(0, 8, "file:///") == 0);
200             video_paths_.push_back(uri.substr(7));
201         }
202     }
203
204     void WebDvdWindow::load_next_page()
205     {
206         loading_ = true;
207
208         assert(!page_queue_.empty());
209         const std::string & uri = page_queue_.front();
210         std::cout << "loading " << uri << std::endl;
211
212         std::size_t page_count = page_links_.size();
213         resource_map_[uri].second = ++page_count;
214         page_links_.resize(page_count);
215         browser_widget_.load_uri(uri);
216     }
217
218     void WebDvdWindow::on_net_state_change(const char * uri,
219                                            gint flags, guint status)
220     {
221         enum {
222             process_nothing,
223             process_new_page,
224             process_current_link
225         } action = process_nothing;
226
227         if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
228         {
229             if (flags & GTK_MOZ_EMBED_FLAG_START)
230                 ++pending_req_count_;
231             if (flags & GTK_MOZ_EMBED_FLAG_STOP)
232             {
233                 assert(pending_req_count_ != 0);
234                 --pending_req_count_;
235             }
236             if (pending_req_count_ == 0 && link_state_.get())
237                 action = process_current_link;
238         }
239             
240         if (flags & GTK_MOZ_EMBED_FLAG_STOP
241             && flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW)
242             action = process_new_page;
243
244         if (action != process_nothing)
245         {
246             assert(loading_ && !page_queue_.empty());
247             assert(pending_req_count_ == 0);
248
249             try
250             {
251                 // Check whether the load was successful, ignoring this
252                 // pseudo-error.
253                 if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
254                     check(status);
255
256                 nsCOMPtr<nsIWebBrowser> browser(
257                     browser_widget_.get_browser());
258                 nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
259                 assert(doc_shell);
260                 nsCOMPtr<nsIPresShell> pres_shell;
261                 check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
262                 nsCOMPtr<nsIPresContext> pres_context;
263                 check(doc_shell->GetPresContext(
264                           getter_AddRefs(pres_context)));
265                 nsCOMPtr<nsIDOMWindow> dom_window;
266                 check(browser->GetContentDOMWindow(
267                           getter_AddRefs(dom_window)));
268
269                 if (action == process_new_page)
270                 {
271                     apply_style_sheet(stylesheet_, pres_shell);
272                     save_screenshot();
273                 }
274                 process_links(pres_shell, pres_context, dom_window);
275                 if (!link_state_.get())
276                 {
277                     page_queue_.pop();
278                     if (page_queue_.empty())
279                     {
280                         generate_dvdauthor_file();
281                         Gtk::Main::quit();
282                     }
283                     else
284                         load_next_page();
285                 }
286             }
287             catch (std::exception & e)
288             {
289                 std::cerr << "Fatal error";
290                 if (!page_queue_.empty())
291                     std::cerr << " while processing <" << page_queue_.front()
292                               << ">";
293                 std::cerr << ": " << e.what() << "\n";
294                 Gtk::Main::quit();
295             }
296         }
297     }
298
299     void WebDvdWindow::save_screenshot()
300     {
301         char filename[25];
302         std::sprintf(filename, "page_%06d_back.png", page_links_.size());
303         Glib::RefPtr<Gdk::Window> window(get_window());
304         assert(window);
305         window->process_updates(true);
306         std::cout << "saving " << filename << std::endl;
307         Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
308                             window->get_colormap(),
309                             0, 0, 0, 0,
310                             frame_params_.width, frame_params_.height)
311             ->save(filename, "png");
312     }
313
314     struct WebDvdWindow::link_state
315     {
316         Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
317
318         std::ofstream spumux_file;
319
320         int link_num;
321         LinkIterator links_it, links_end;
322
323         rectangle link_rect;
324         bool link_changing;
325         Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
326     };
327
328     void WebDvdWindow::process_links(nsIPresShell * pres_shell,
329                                      nsIPresContext * pres_context,
330                                      nsIDOMWindow * dom_window)
331     {
332         Glib::RefPtr<Gdk::Window> window(get_window());
333         assert(window);
334
335         nsCOMPtr<nsIDOMDocument> basic_doc;
336         check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
337         nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
338         assert(ns_doc);
339         nsCOMPtr<nsIEventStateManager> event_state_man(
340             pres_context->EventStateManager()); // does not AddRef
341         assert(event_state_man);
342         nsCOMPtr<nsIDOMDocumentEvent> event_factory(
343             do_QueryInterface(basic_doc));
344         assert(event_factory);
345         nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
346         assert(doc_view);
347         nsCOMPtr<nsIDOMAbstractView> view;
348         check(doc_view->GetDefaultView(getter_AddRefs(view)));
349
350         // Set up or recover our iteration state.
351         std::auto_ptr<link_state> state(link_state_);
352         if (!state.get())
353         {
354             state.reset(new link_state);
355
356             state->diff_pixbuf = Gdk::Pixbuf::create(
357                 Gdk::COLORSPACE_RGB,
358                 true, 8, // has_alpha, bits_per_sample
359                 frame_params_.width, frame_params_.height);
360
361             char spumux_filename[20];
362             std::sprintf(spumux_filename,
363                          "page_%06d.spumux", page_links_.size());
364             state->spumux_file.open(spumux_filename);
365             state->spumux_file <<
366                 "<subpictures>\n"
367                 "  <stream>\n"
368                 "    <spu force='yes' start='00:00:00.00'\n"
369                 "        highlight='page_" << std::setfill('0')
370                                << std::setw(6) << page_links_.size()
371                                << "_links.png'\n"
372                 "        select='page_" << std::setfill('0')
373                                << std::setw(6) << page_links_.size()
374                                << "_links.png'>\n";
375
376             state->link_num = 0;
377             state->links_it = LinkIterator(basic_doc);
378             state->link_changing = false;
379         }
380             
381         rectangle window_rect = {
382             0, 0, frame_params_.width, frame_params_.height
383         };
384
385         for (/* no initialisation */;
386              state->links_it != state->links_end;
387              ++state->links_it)
388         {
389             nsCOMPtr<nsIDOMNode> node(*state->links_it);
390
391             // Find the link URI.
392             nsCOMPtr<nsILink> link(do_QueryInterface(node));
393             assert(link);
394             nsCOMPtr<nsIURI> uri;
395             check(link->GetHrefURI(getter_AddRefs(uri)));
396             std::string uri_string;
397             {
398                 nsCString uri_ns_string;
399                 check(uri->GetSpec(uri_ns_string));
400                 uri_string.assign(uri_ns_string.BeginReading(),
401                                   uri_ns_string.EndReading());
402             }
403             std::string uri_sans_fragment(uri_string, 0, uri_string.find('#'));
404
405             // Is this a new link?
406             if (!state->link_changing)
407             {
408                 // Find a rectangle enclosing the link and clip it to the
409                 // window.
410                 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
411                 assert(elem);
412                 state->link_rect = get_elem_rect(ns_doc, elem);
413                 state->link_rect &= window_rect;
414
415                 if (state->link_rect.empty())
416                 {
417                     std::cerr << "Ignoring invisible link to "
418                               << uri_string << "\n";
419                     continue;
420                 }
421
422                 ++state->link_num;
423
424                 if (state->link_num >= dvd::menu_buttons_max)
425                 {
426                     if (state->link_num == dvd::menu_buttons_max)
427                         std::cerr << "No more than " << dvd::menu_buttons_max
428                                   << " buttons can be placed on a page\n";
429                     std::cerr << "Ignoring link to " << uri_string << "\n";
430                     continue;
431                 }
432
433                 // Check whether this is a link to a video or a page then
434                 // add it to the known resources if not already seen.
435                 nsCString path;
436                 check(uri->GetPath(path));
437                 // FIXME: This is a bit of a hack.  Perhaps we could decide
438                 // later based on the MIME type determined by Mozilla?
439                 if (path.Length() > 4
440                     && std::strcmp(path.EndReading() - 4, ".vob") == 0)
441                 {
442                     PRBool is_file;
443                     check(uri->SchemeIs("file", &is_file));
444                     if (!is_file)
445                     {
446                         std::cerr << "Links to video must use the file:"
447                                   << " scheme\n";
448                         continue;
449                     }
450                     add_video(uri_sans_fragment);
451                 }
452                 else
453                 {
454                     add_page(uri_sans_fragment);
455                 }
456
457                 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
458                 assert(content);
459                 nsCOMPtr<nsIDOMEventTarget> event_target(
460                     do_QueryInterface(node));
461                 assert(event_target);
462
463                 state->norm_pixbuf = Gdk::Pixbuf::create(
464                     Glib::RefPtr<Gdk::Drawable>(window),
465                     window->get_colormap(),
466                     state->link_rect.left,
467                     state->link_rect.top,
468                     0,
469                     0,
470                     state->link_rect.right - state->link_rect.left,
471                     state->link_rect.bottom - state->link_rect.top);
472
473                 nsCOMPtr<nsIDOMEvent> event;
474                 check(event_factory->CreateEvent(
475                           NS_ConvertASCIItoUTF16("MouseEvents"),
476                           getter_AddRefs(event)));
477                 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
478                     do_QueryInterface(event));
479                 assert(mouse_event);
480                 check(mouse_event->InitMouseEvent(
481                           NS_ConvertASCIItoUTF16("mouseover"),
482                           true,  // can bubble
483                           true,  // cancelable
484                           view,
485                           0,     // detail: mouse click count
486                           state->link_rect.left, // screenX
487                           state->link_rect.top,  // screenY
488                           state->link_rect.left, // clientX
489                           state->link_rect.top,  // clientY
490                           false, false, false, false, // qualifiers
491                           0,     // button: left (or primary)
492                           0));   // related target
493                 PRBool dummy;
494                 check(event_target->DispatchEvent(mouse_event,
495                                                   &dummy));
496                 check(event_state_man->SetContentState(content,
497                                                        NS_EVENT_STATE_HOVER));
498
499                 pres_shell->FlushPendingNotifications(true);
500
501                 // We may have to exit and wait for image loading
502                 // to complete, at which point we will be called
503                 // again.
504                 if (pending_req_count_ > 0)
505                 {
506                     state->link_changing = true;
507                     link_state_ = state;
508                     return;
509                 }
510             }
511
512             window->process_updates(true);
513
514             Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
515                 Gdk::Pixbuf::create(
516                     Glib::RefPtr<Gdk::Drawable>(window),
517                     window->get_colormap(),
518                     state->link_rect.left,
519                     state->link_rect.top,
520                     0,
521                     0,
522                     state->link_rect.right - state->link_rect.left,
523                     state->link_rect.bottom - state->link_rect.top));
524             diff_rgb_pixbufs(
525                 state->norm_pixbuf,
526                 changed_pixbuf,
527                 state->diff_pixbuf,
528                 state->link_rect.left,
529                 state->link_rect.top,
530                 state->link_rect.right - state->link_rect.left,
531                 state->link_rect.bottom - state->link_rect.top);
532
533             state->spumux_file <<
534                 "      <button x0='" << state->link_rect.left << "'"
535                 " y0='" << state->link_rect.top << "'"
536                 " x1='" << state->link_rect.right - 1 << "'"
537                 " y1='" << state->link_rect.bottom - 1 << "'/>\n";
538
539             // Add to the page's links, ignoring any fragment (for now).
540             page_links_.back().push_back(uri_sans_fragment);
541         }
542
543         quantise_rgba_pixbuf(state->diff_pixbuf, dvd::button_n_colours);
544
545         char filename[25];
546         std::sprintf(filename, "page_%06d_links.png", page_links_.size());
547         std::cout << "saving " << filename << std::endl;
548         state->diff_pixbuf->save(filename, "png");
549
550         state->spumux_file <<
551             "    </spu>\n"
552             "  </stream>\n"
553             "</subpictures>\n";
554     }
555
556     void generate_page_dispatch(std::ostream &, int indent,
557                                 int first_page, int last_page);
558
559     void WebDvdWindow::generate_dvdauthor_file()
560     {
561         std::ofstream file("webdvd.dvdauthor");
562
563         // We generate code that uses registers in the following way:
564         //
565         // g0:     link destination (when jumping to menu 1), then scratch
566         // g1:     current location
567         // g2-g11: location history (g2 = most recent)
568         // g12:    location that last linked to a video
569         //
570         // All locations are divided into two bitfields: the least
571         // significant 10 bits are a page/menu number and the most
572         // significant 6 bits are a link/button number.  This is
573         // chosen for compatibility with the encoding of the s8
574         // (button) register.
575         //
576         static const int link_mult = dvd::reg_s8_button_mult;
577         static const int page_mask = link_mult - 1;
578         static const int link_mask = (1 << dvd::reg_bits) - link_mult;
579
580         file <<
581             "<dvdauthor>\n"
582             "  <vmgm>\n"
583             "    <menus>\n";
584             
585         for (std::size_t page_num = 1;
586              page_num <= page_links_.size();
587              ++page_num)
588         {
589             std::vector<std::string> & page_links =
590                 page_links_[page_num - 1];
591
592             if (page_num == 1)
593             {
594                 // This is the first page (root menu) which needs to
595                 // include initialisation and dispatch code.
596         
597                 file <<
598                     "      <pgc entry='title'>\n"
599                     "        <pre>\n"
600                     // Has the location been set yet?
601                     "          if (g1 eq 0)\n"
602                     "          {\n"
603                     // Initialise the current location to first link on
604                     // this page.
605                     "            g1 = " << 1 * link_mult + 1 << ";\n"
606                     "          }\n"
607                     "          else\n"
608                     "          {\n"
609                     // Has the user selected a link?
610                     "            if (g0 ne 0)\n"
611                     "            {\n"
612                     // First update the history.
613                     // Does link go to the last page in the history?
614                     "              if (((g0 ^ g2) &amp; " << page_mask
615                      << ") == 0)\n"
616                     // It does; we treat this as going back and pop the old
617                     // location off the history stack into the current
618                     // location.  Clear the free stack slot.
619                     "              {\n"
620                     "                g1 = g2; g2 = g3; g3 = g4; g4 = g5;\n"
621                     "                g5 = g6; g6 = g7; g7 = g8; g8 = g9;\n"
622                     "                g9 = g10; g10 = g11; g11 = 0;\n"
623                     "              }\n"
624                     "              else\n"
625                     // Link goes to some other page, so push current
626                     // location onto the history stack and set the current
627                     // location to be exactly the target location.
628                     "              {\n"
629                     "                g11 = g10; g10 = g9; g9 = g8; g8 = g7;\n"
630                     "                g7 = g6; g6 = g5; g5 = g4; g4 = g3;\n"
631                     "                g3 = g2; g2 = g1; g1 = g0;\n"
632                     "              }\n"
633                     "            }\n"
634                     // Find the target page number.
635                     "            g0 = g1 &amp; " << page_mask << ";\n";
636                 // There seems to be no way to perform a computed jump,
637                 // so we generate all possible jumps and a binary search
638                 // to select the correct one.
639                 generate_page_dispatch(file, 12, 1, page_links_.size());
640                 file <<
641                     "          }\n";
642             }
643             else // page_num != 1
644             {
645                 file <<
646                     "      <pgc>\n"
647                     "        <pre>\n";
648             }
649
650             file <<
651                 // Clear link indicator and highlight the
652                 // appropriate link/button.
653                 "          g0 = 0; s8 = g1 &amp; " << link_mask << ";\n"
654                 "        </pre>\n"
655                 "        <vob file='page_"
656                  << std::setfill('0') << std::setw(6) << page_num
657                  << ".vob'/>\n";
658
659             for (std::size_t link_num = 1;
660                  link_num <= page_links.size();
661                  ++link_num)
662             {
663                 file <<
664                     "        <button>"
665                     // Update current location.
666                     " g1 = " << link_num * link_mult + page_num << ";";
667
668                 // Jump to appropriate resource.
669                 const ResourceEntry & resource_loc =
670                     resource_map_[page_links[link_num - 1]];
671                 if (resource_loc.first == page_resource)
672                     file <<
673                         " g0 = " << 1 * link_mult + resource_loc.second << ";"
674                         " jump menu 1;";
675                 else if (resource_loc.first == video_resource)
676                     file << " jump title " << resource_loc.second << ";";
677
678                 file <<  " </button>\n";
679             }
680
681             file << "      </pgc>\n";
682         }
683
684         file <<
685             "    </menus>\n"
686             "  </vmgm>\n";
687
688         // Generate a titleset for each video.  This appears to make
689         // jumping to titles a whole lot simpler.
690         for (std::size_t video_num = 1;
691              video_num <= video_paths_.size();
692              ++video_num)
693         {
694             file <<
695                 "  <titleset>\n"
696                 // Generate a dummy menu so that the menu button on the
697                 // remote control will work.
698                 "    <menus>\n"
699                 "      <pgc entry='root'>\n"
700                 "        <pre> jump vmgm menu; </pre>\n"
701                 "      </pgc>\n"
702                 "    </menus>\n"
703                 "    <titles>\n"
704                 "      <pgc>\n"
705                 // Record calling page/menu.
706                 "        <pre> g12 = g1; </pre>\n"
707                 // FIXME: Should XML-escape the path
708                 "        <vob file='" << video_paths_[video_num - 1]
709                  << "'/>\n"
710                 // If page/menu location has not been changed during the
711                 // video, change the location to be the following
712                 // link/button when returning to it.  In any case,
713                 // return to a page/menu.
714                 "        <post> if (g1 eq g12) g1 = g1 + " << link_mult
715                  << "; call menu; </post>\n"
716                 "      </pgc>\n"
717                 "    </titles>\n"
718                 "  </titleset>\n";
719         }
720
721         file <<
722             "</dvdauthor>\n";
723     }
724
725     void generate_page_dispatch(std::ostream & file, int indent,
726                                 int first_page, int last_page)
727     {
728         if (first_page == 1 && last_page == 1)
729         {
730             // The dispatch code is *on* page 1 so we must not dispatch to
731             // page 1 since that would cause an infinite loop.  This case
732             // should be unreachable if there is more than one page due
733             // to the following case.
734         }
735         else if (first_page == 1 && last_page == 2)
736         {
737             // dvdauthor doesn't allow empty blocks or null statements so
738             // when selecting between pages 1 and 2 we don't use an "else"
739             // part.  We must use braces so that a following "else" will
740             // match the right "if".
741             file << std::setw(indent) << "" << "{\n"
742                  << std::setw(indent) << "" << "if (g0 eq 2)\n"
743                  << std::setw(indent + 2) << "" << "jump menu 2;\n"
744                  << std::setw(indent) << "" << "}\n";
745         }
746         else if (first_page == last_page)
747         {
748             file << std::setw(indent) << ""
749                  << "jump menu " << first_page << ";\n";
750         }
751         else
752         {
753             int middle = (first_page + last_page) / 2;
754             file << std::setw(indent) << "" << "if (g0 le " << middle << ")\n";
755             generate_page_dispatch(file, indent + 2, first_page, middle);
756             file << std::setw(indent) << "" << "else\n";
757             generate_page_dispatch(file, indent + 2, middle + 1, last_page);
758         }
759     }
760
761     const video::frame_params & lookup_frame_params(const char * str)
762     {
763         assert(str);
764         static const struct { const char * str; bool is_ntsc; }
765         known_strings[] = {
766             { "NTSC",  true },
767             { "ntsc",  true },
768             { "PAL",   false },
769             { "pal",   false },
770             // For DVD purposes, SECAM can be treated identically to PAL.
771             { "SECAM", false },
772             { "secam", false }
773         };
774         for (std::size_t i = 0;
775              i != sizeof(known_strings)/sizeof(known_strings[0]);
776              ++i)
777             if (std::strcmp(str, known_strings[i].str) == 0)
778                 return known_strings[i].is_ntsc ?
779                     video::ntsc_params : video::pal_params;
780         throw std::runtime_error(
781             std::string("Invalid video standard: ").append(str));
782     }
783
784 } // namespace
785
786 int main(int argc, char ** argv)
787 {
788     try
789     {
790         // Determine video frame parameters.
791         video::frame_params frame_params = video::pal_params;
792         for (int argi = 1; argi != argc; ++argi)
793         {
794             if (std::strcmp(argv[argi], "--") == 0)
795                 break;
796             if (std::strcmp(argv[argi], "--video-std") == 0)
797             {
798                 if (argi + 1 == argc)
799                 {
800                     std::cerr << "Missing argument to --video-std\n";
801                     return EXIT_FAILURE;
802                 }
803                 frame_params = lookup_frame_params(argv[argi + 1]);
804                 break;
805             }
806         }
807         
808         // Spawn Xvfb and set env variables so that Xlib will use it
809         // Use 8 bits each for RGB components, which should translate into
810         // "enough" bits for YUV components.
811         FrameBuffer fb(frame_params.width, frame_params.height, 3 * 8);
812         setenv("XAUTHORITY", fb.get_x_authority().c_str(), true);
813         setenv("DISPLAY", fb.get_x_display().c_str(), true);
814
815         // Initialise Gtk and Mozilla
816         Gtk::Main kit(argc, argv);
817         BrowserWidget::init();
818             
819         WebDvdWindow window(frame_params);
820         int argi = 1;
821         if (std::strcmp(argv[argi], "--video-std") == 0)
822             argi += 2;
823         else if (std::strcmp(argv[argi], "--") == 0)
824             argi += 1;
825         else if (argv[argi][0] == '-')
826             throw std::runtime_error(
827                 std::string("Invalid option: ").append(argv[argi]));
828         if (argi == argc)
829             window.add_page("about:");
830         else
831             for (/* no initialisation */; argi != argc; ++argi)
832                 window.add_page(argv[argi]);
833         Gtk::Main::run(window);
834     }
835     catch (std::exception & e)
836     {
837         std::cerr << "Fatal error: " << e.what() << "\n";
838         return EXIT_FAILURE;
839     }
840
841     return EXIT_SUCCESS;
842 }