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