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