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