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