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