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