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