1 // Copyright 2005 Ben Hutchings <ben@decadentplace.org.uk>.
2 // See the file "COPYING" for licence details.
18 #include <boost/shared_ptr.hpp>
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>
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
45 #include <nsIPrefBranch.h>
46 #include <nsIPrefService.h>
47 #include <nsIPresContext.h>
48 #include <nsIPresShell.h>
49 #include <nsIServiceManagerUtils.h>
50 #include <nsIWebBrowser.h>
53 #include "browser_widget.hpp"
54 #include "child_iterator.hpp"
56 #include "link_iterator.hpp"
57 #include "pixbufs.hpp"
58 #include "style_sheets.hpp"
59 #include "temp_file.hpp"
61 #include "x_frame_buffer.hpp"
62 #include "xpcom_support.hpp"
64 using xpcom_support::check;
70 int left, top; // inclusive
71 int right, bottom; // exclusive
73 rectangle operator|=(const rectangle & other)
77 // use current extents unchanged
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);
96 rectangle operator&=(const rectangle & other)
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));
108 return left == right || bottom == top;
112 rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
113 nsIDOMElement * elem)
117 // Start with this element's bounding box
118 nsCOMPtr<nsIBoxObject> box;
119 check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
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;
128 // Merge bounding boxes of all child elements
129 for (child_iterator it = child_iterator(elem), end; it != end; ++it)
131 nsCOMPtr<nsIDOMNode> child_node(*it);
133 if (check(child_node->GetNodeType(&child_type)),
134 child_type == nsIDOMNode::ELEMENT_NODE)
136 nsCOMPtr<nsIDOMElement> child_elem(
137 do_QueryInterface(child_node));
138 result |= get_elem_rect(ns_doc, child_elem);
146 std::string xml_escape(const std::string & str)
149 std::size_t begin = 0;
153 std::size_t end = str.find_first_of("\"&'<>", begin);
154 result.append(str, begin, end - begin);
155 if (end == std::string::npos)
158 const char * entity = NULL;
161 case '"': entity = """; break;
162 case '&': entity = "&"; break;
163 case '\'': entity = "'"; break;
164 case '<': entity = "<"; break;
165 case '>': entity = ">"; break;
168 result.append(entity);
177 enum pgc_type { menu_pgc, title_pgc };
178 typedef std::pair<pgc_type, int> pgc_ref;
183 : vob_temp(new temp_file("webdvd-vob-"))
188 boost::shared_ptr<temp_file> vob_temp;
189 std::vector<pgc_ref> entries;
194 explicit title(const std::string & vob_list)
198 std::string vob_list;
201 std::vector<menu> menus;
202 std::vector<title> titles;
205 class webdvd_window : public Gtk::Window
209 const video::frame_params & frame_params,
210 const std::string & main_page_uri,
211 const std::string & output_dir);
214 dvd_contents::pgc_ref add_menu(const std::string & uri);
215 dvd_contents::pgc_ref add_title(const std::string & uri);
216 void load_next_page();
217 void on_net_state_change(const char * uri, gint flags, guint status);
218 bool browser_is_busy() const
220 return pending_window_update_ || pending_req_count_;
223 void save_screenshot();
224 void process_links(nsIPresShell * pres_shell,
225 nsIPresContext * pres_context,
226 nsIDOMWindow * dom_window);
229 video::frame_params frame_params_;
230 std::string output_dir_;
231 browser_widget browser_widget_;
232 nsCOMPtr<nsIStyleSheet> stylesheet_;
234 dvd_contents contents_;
235 typedef std::map<std::string, dvd_contents::pgc_ref> resource_map_type;
236 resource_map_type resource_map_;
238 std::queue<std::string> page_queue_;
239 bool pending_window_update_;
240 int pending_req_count_;
241 bool have_tweaked_page_;
242 std::auto_ptr<temp_file> background_temp_;
244 std::auto_ptr<page_state> page_state_;
247 webdvd_window::webdvd_window(
248 const video::frame_params & frame_params,
249 const std::string & main_page_uri,
250 const std::string & output_dir)
251 : frame_params_(frame_params),
252 output_dir_(output_dir),
253 stylesheet_(load_css("file://" WEBDVD_LIB_DIR "/webdvd.css")),
254 pending_window_update_(false),
255 pending_req_count_(0),
256 have_tweaked_page_(false)
258 set_size_request(frame_params_.width, frame_params_.height);
259 set_resizable(false);
261 add(browser_widget_);
262 browser_widget_.show();
263 browser_widget_.signal_net_state().connect(
264 SigC::slot(*this, &webdvd_window::on_net_state_change));
266 add_menu(main_page_uri);
270 dvd_contents::pgc_ref webdvd_window::add_menu(const std::string & uri)
272 dvd_contents::pgc_ref next_menu(dvd_contents::menu_pgc,
273 contents_.menus.size());
274 std::pair<resource_map_type::iterator, bool> insert_result(
275 resource_map_.insert(std::make_pair(uri, next_menu)));
277 if (!insert_result.second)
279 return insert_result.first->second;
283 page_queue_.push(uri);
284 contents_.menus.resize(contents_.menus.size() + 1);
289 dvd_contents::pgc_ref webdvd_window::add_title(const std::string & uri)
291 dvd_contents::pgc_ref next_title(dvd_contents::title_pgc,
292 contents_.titles.size());
293 std::pair<resource_map_type::iterator, bool> insert_result(
294 resource_map_.insert(std::make_pair(uri, next_title)));
296 if (!insert_result.second)
298 return insert_result.first->second;
302 Glib::ustring hostname;
303 std::string filename(Glib::filename_from_uri(uri, hostname));
304 // FIXME: Should check the hostname
306 std::string vob_list;
308 // Store a reference to a linked VOB file, or the contents
309 // of a linked VOB list file.
310 if (filename.compare(filename.size() - 4, 4, ".vob") == 0)
312 if (!Glib::file_test(filename, Glib::FILE_TEST_IS_REGULAR))
313 throw std::runtime_error(
314 filename + " is missing or not a regular file");
316 .append("<vob file='")
317 .append(xml_escape(filename))
322 assert(filename.compare(filename.size() - 8, 8, ".voblist")
324 // TODO: Validate the file contents
325 vob_list.assign(Glib::file_get_contents(filename));
328 contents_.titles.push_back(dvd_contents::title(vob_list));
333 void webdvd_window::load_next_page()
335 assert(!page_queue_.empty());
336 const std::string & uri = page_queue_.front();
337 std::cout << "loading " << uri << std::endl;
339 browser_widget_.load_uri(uri);
342 void webdvd_window::on_net_state_change(const char * uri,
343 gint flags, guint status)
345 # ifdef DEBUG_ON_NET_STATE_CHANGE
346 std::cout << "webdvd_window::on_net_state_change(";
348 std::cout << '"' << uri << '"';
353 gint flags_left = flags;
354 static const struct {
358 { GTK_MOZ_EMBED_FLAG_START, "STATE_START" },
359 { GTK_MOZ_EMBED_FLAG_REDIRECTING, "STATE_REDIRECTING" },
360 { GTK_MOZ_EMBED_FLAG_TRANSFERRING, "STATE_TRANSFERRING" },
361 { GTK_MOZ_EMBED_FLAG_NEGOTIATING, "STATE_NEGOTIATING" },
362 { GTK_MOZ_EMBED_FLAG_STOP, "STATE_STOP" },
363 { GTK_MOZ_EMBED_FLAG_IS_REQUEST, "STATE_IS_REQUEST" },
364 { GTK_MOZ_EMBED_FLAG_IS_DOCUMENT, "STATE_IS_DOCUMENT" },
365 { GTK_MOZ_EMBED_FLAG_IS_NETWORK, "STATE_IS_NETWORK" },
366 { GTK_MOZ_EMBED_FLAG_IS_WINDOW, "STATE_IS_WINDOW" }
368 for (int i = 0; i != sizeof(flag_names)/sizeof(flag_names[0]); ++i)
370 if (flags & flag_names[i].value)
372 std::cout << flag_names[i].name;
373 flags_left -= flag_names[i].value;
379 std::cout << "0x" << std::setbase(16) << flags_left;
381 std::cout << ", " << "0x" << std::setbase(16) << status << ")\n";
382 # endif // DEBUG_ON_NET_STATE_CHANGE
384 if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
386 if (flags & GTK_MOZ_EMBED_FLAG_START)
387 ++pending_req_count_;
389 if (flags & GTK_MOZ_EMBED_FLAG_STOP)
391 assert(pending_req_count_ != 0);
392 --pending_req_count_;
396 if (flags & GTK_MOZ_EMBED_FLAG_IS_DOCUMENT
397 && flags & GTK_MOZ_EMBED_FLAG_START)
399 pending_window_update_ = true;
400 have_tweaked_page_ = false;
403 if (flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW
404 && flags & GTK_MOZ_EMBED_FLAG_STOP)
406 // Check whether the load was successful, ignoring this
408 if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
411 pending_window_update_ = false;
414 if (!browser_is_busy())
421 catch (std::exception & e)
423 std::cerr << "Fatal error";
424 if (!page_queue_.empty())
425 std::cerr << " while processing <" << page_queue_.front()
427 std::cerr << ": " << e.what() << "\n";
433 bool webdvd_window::process_page()
435 assert(!page_queue_.empty());
437 nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
438 nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
440 nsCOMPtr<nsIPresShell> pres_shell;
441 check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
442 nsCOMPtr<nsIPresContext> pres_context;
443 check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
444 nsCOMPtr<nsIDOMWindow> dom_window;
445 check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
447 // If we haven't done so already, apply the stylesheet and
448 // disable scrollbars.
449 if (!have_tweaked_page_)
451 apply_style_sheet(stylesheet_, pres_shell);
453 // This actually only needs to be done once.
454 nsCOMPtr<nsIDOMBarProp> dom_bar_prop;
455 check(dom_window->GetScrollbars(getter_AddRefs(dom_bar_prop)));
456 check(dom_bar_prop->SetVisible(false));
458 have_tweaked_page_ = true;
460 // Might need to wait a while for things to load or more
461 // likely for a re-layout.
462 if (browser_is_busy())
466 // All further work should only be done if we're not in preview mode.
467 if (!output_dir_.empty())
469 // If we haven't already started work on this menu, save a
470 // screenshot of its normal appearance.
471 if (!page_state_.get())
474 // Start or continue processing links.
475 process_links(pres_shell, pres_context, dom_window);
477 // If we've finished work on the links, move on to the
478 // next page, if any, or else generate the DVD filesystem.
479 if (!page_state_.get())
482 if (page_queue_.empty())
497 void webdvd_window::save_screenshot()
499 Glib::RefPtr<Gdk::Window> window(get_window());
501 window->process_updates(true);
503 background_temp_.reset(new temp_file("webdvd-back-"));
504 background_temp_->close();
505 std::cout << "saving " << background_temp_->get_name() << std::endl;
506 Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
507 window->get_colormap(),
509 frame_params_.width, frame_params_.height)
510 ->save(background_temp_->get_name(), "png");
513 struct webdvd_window::page_state
515 page_state(nsIDOMDocument * doc, int width, int height)
516 : diff_pixbuf(Gdk::Pixbuf::create(
518 true, 8, // has_alpha, bits_per_sample
520 spumux_temp("webdvd-spumux-"),
521 links_temp("webdvd-links-"),
530 Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
532 temp_file spumux_temp;
533 std::ofstream spumux_file;
535 temp_file links_temp;
538 link_iterator links_it, links_end;
542 Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
545 void webdvd_window::process_links(nsIPresShell * pres_shell,
546 nsIPresContext * pres_context,
547 nsIDOMWindow * dom_window)
549 Glib::RefPtr<Gdk::Window> window(get_window());
552 nsCOMPtr<nsIDOMDocument> basic_doc;
553 check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
554 nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
556 nsCOMPtr<nsIEventStateManager> event_state_man(
557 pres_context->EventStateManager()); // does not AddRef
558 assert(event_state_man);
559 nsCOMPtr<nsIDOMDocumentEvent> event_factory(
560 do_QueryInterface(basic_doc));
561 assert(event_factory);
562 nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
564 nsCOMPtr<nsIDOMAbstractView> view;
565 check(doc_view->GetDefaultView(getter_AddRefs(view)));
567 // Set up or recover our iteration state.
568 std::auto_ptr<page_state> state(page_state_);
573 basic_doc, frame_params_.width, frame_params_.height));
575 state->spumux_file.open(state->spumux_temp.get_name().c_str());
576 state->spumux_file <<
579 " <spu force='yes' start='00:00:00.00'\n"
580 " highlight='" << state->links_temp.get_name() << "'\n"
581 " select='" << state->links_temp.get_name() << "'>\n";
584 rectangle window_rect = {
585 0, 0, frame_params_.width, frame_params_.height
588 int menu_num = resource_map_[page_queue_.front()].second;
590 for (/* no initialisation */;
591 state->links_it != state->links_end;
594 nsCOMPtr<nsIDOMNode> node(*state->links_it);
596 // Find the link URI.
597 nsCOMPtr<nsILink> link(do_QueryInterface(node));
599 nsCOMPtr<nsIURI> uri;
600 check(link->GetHrefURI(getter_AddRefs(uri)));
601 std::string uri_string;
603 nsCString uri_ns_string;
604 check(uri->GetSpec(uri_ns_string));
605 uri_string.assign(uri_ns_string.BeginReading(),
606 uri_ns_string.EndReading());
608 std::string uri_sans_fragment(uri_string, 0, uri_string.find('#'));
610 // Is this a new link?
611 if (!state->link_changing)
613 // Find a rectangle enclosing the link and clip it to the
615 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
617 state->link_rect = get_elem_rect(ns_doc, elem);
618 state->link_rect &= window_rect;
620 if (state->link_rect.empty())
622 std::cerr << "Ignoring invisible link to "
623 << uri_string << "\n";
629 if (state->link_num >= dvd::menu_buttons_max)
631 if (state->link_num == dvd::menu_buttons_max)
632 std::cerr << "No more than " << dvd::menu_buttons_max
633 << " buttons can be placed on a menu\n";
634 std::cerr << "Ignoring link to " << uri_string << "\n";
638 state->spumux_file <<
639 " <button x0='" << state->link_rect.left << "'"
640 " y0='" << state->link_rect.top << "'"
641 " x1='" << state->link_rect.right - 1 << "'"
642 " y1='" << state->link_rect.bottom - 1 << "'/>\n";
644 // Check whether this is a link to a video or a page then
645 // add it to the known resources if not already seen; then
646 // add it to the menu entries.
648 check(uri->GetPath(path));
649 dvd_contents::pgc_ref dest_pgc;
650 // FIXME: This is a bit of a hack. Perhaps we could decide
651 // later based on the MIME type determined by Mozilla?
652 if ((path.Length() > 4
653 && std::strcmp(path.EndReading() - 4, ".vob") == 0)
654 || (path.Length() > 8
655 && std::strcmp(path.EndReading() - 8, ".voblist")
659 check(uri->SchemeIs("file", &is_file));
662 std::cerr << "Links to video must use the file:"
666 dest_pgc = add_title(uri_sans_fragment);
670 dest_pgc = add_menu(uri_sans_fragment);
672 contents_.menus[menu_num].entries.push_back(dest_pgc);
674 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
676 nsCOMPtr<nsIDOMEventTarget> event_target(
677 do_QueryInterface(node));
678 assert(event_target);
680 state->norm_pixbuf = Gdk::Pixbuf::create(
681 Glib::RefPtr<Gdk::Drawable>(window),
682 window->get_colormap(),
683 state->link_rect.left,
684 state->link_rect.top,
687 state->link_rect.right - state->link_rect.left,
688 state->link_rect.bottom - state->link_rect.top);
690 nsCOMPtr<nsIDOMEvent> event;
691 check(event_factory->CreateEvent(
692 NS_ConvertASCIItoUTF16("MouseEvents"),
693 getter_AddRefs(event)));
694 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
695 do_QueryInterface(event));
697 check(mouse_event->InitMouseEvent(
698 NS_ConvertASCIItoUTF16("mouseover"),
702 0, // detail: mouse click count
703 state->link_rect.left, // screenX
704 state->link_rect.top, // screenY
705 state->link_rect.left, // clientX
706 state->link_rect.top, // clientY
707 false, false, false, false, // qualifiers
708 0, // button: left (or primary)
709 0)); // related target
711 check(event_target->DispatchEvent(mouse_event,
713 check(event_state_man->SetContentState(content,
714 NS_EVENT_STATE_HOVER));
716 pres_shell->FlushPendingNotifications(true);
718 // We may have to exit and wait for image loading
719 // to complete, at which point we will be called
721 if (browser_is_busy())
723 state->link_changing = true;
729 window->process_updates(true);
731 Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
733 Glib::RefPtr<Gdk::Drawable>(window),
734 window->get_colormap(),
735 state->link_rect.left,
736 state->link_rect.top,
739 state->link_rect.right - state->link_rect.left,
740 state->link_rect.bottom - state->link_rect.top));
745 state->link_rect.left,
746 state->link_rect.top,
747 state->link_rect.right - state->link_rect.left,
748 state->link_rect.bottom - state->link_rect.top);
751 quantise_rgba_pixbuf(state->diff_pixbuf, dvd::button_n_colours);
753 std::cout << "saving " << state->links_temp.get_name()
755 state->diff_pixbuf->save(state->links_temp.get_name(), "png");
757 state->spumux_file <<
762 state->spumux_file.close();
764 // TODO: if (!state->spumux_file) throw ...
767 std::ostringstream command_stream;
768 command_stream << "pngtopnm "
769 << background_temp_->get_name()
770 << " | ppmtoy4m -v0 -n1 -F"
771 << frame_params_.rate_numer
772 << ":" << frame_params_.rate_denom
773 << " -A" << frame_params_.pixel_ratio_width
774 << ":" << frame_params_.pixel_ratio_height
775 << (" -Ip -S420_mpeg2"
776 " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
777 " | mplex -v0 -f8 -o/dev/stdout /dev/stdin"
778 " | spumux -v0 -mdvd ")
779 << state->spumux_temp.get_name()
781 << contents_.menus[menu_num].vob_temp->get_name();
782 std::string command(command_stream.str());
783 const char * argv[] = {
784 "/bin/sh", "-c", command.c_str(), 0
786 std::cout << "running " << argv[2] << std::endl;
788 Glib::spawn_sync(".",
789 Glib::ArrayHandle<std::string>(
790 argv, sizeof(argv)/sizeof(argv[0]),
791 Glib::OWNERSHIP_NONE),
792 Glib::SPAWN_STDOUT_TO_DEV_NULL,
796 if (command_result != 0)
797 throw std::runtime_error("spumux pipeline failed");
801 void webdvd_window::generate_dvd()
803 temp_file temp("webdvd-dvdauthor-");
805 std::ofstream file(temp.get_name().c_str());
807 // We generate code that uses registers in the following way:
810 // g1: current location
811 // g12: location that last jumped to a video
813 // All locations are divided into two bitfields: the least
814 // significant 10 bits are a page/menu number and the most
815 // significant 6 bits are a link/button number, and numbering
816 // starts at 1, not 0. This is done for compatibility with
817 // the encoding of the s8 (button) register.
819 static const int button_mult = dvd::reg_s8_button_mult;
820 static const int menu_mask = button_mult - 1;
821 static const int button_mask = (1 << dvd::reg_bits) - button_mult;
828 for (std::size_t menu_num = 0;
829 menu_num != contents_.menus.size();
832 dvd_contents::menu & menu = contents_.menus[menu_num];
836 // This is the first (title) menu, displayed when the
837 // disc is first played.
839 " <pgc entry='title'>\n"
841 // Initialise the current location if it is not set
842 // (all general registers are initially 0).
844 " g1 = " << 1 + button_mult << ";\n";
853 // When a title finishes or the user presses the menu
854 // button, this always jumps to the titleset's root menu.
855 // We want to return the user to the last menu they used.
856 // So we arrange for each titleset's root menu to return
857 // to the vmgm title menu and then dispatch from there to
858 // whatever the correct menu is. We determine the correct
859 // menu by looking at the menu part of g1.
861 file << " g0 = g1 & " << menu_mask << ";\n";
863 // There is a limit of 128 VM instructions in each PGC.
864 // Therefore in each menu's <pre> section we generate
865 // jumps to menus with numbers greater by 512, 256, 128,
866 // ..., 1 where (a) such a menu exists, (b) this menu
867 // number is divisible by twice that increment and (c) the
868 // correct menu is that or a later menu. Thus each menu
869 // has at most 10 such conditional jumps and is reachable
870 // by at most 10 jumps from the title menu. This chain of
871 // jumps might take too long on some players; this has yet
872 // to be investigated.
874 for (std::size_t menu_incr = (menu_mask + 1) / 2;
878 if (menu_num + menu_incr < contents_.menus.size()
879 && (menu_num & (menu_incr * 2 - 1)) == 0)
882 " if (g0 ge " << 1 + menu_num + menu_incr
884 " jump menu " << 1 + menu_num + menu_incr
890 // Highlight the appropriate button.
891 " s8 = g1 & " << button_mask << ";\n"
893 " <vob file='" << menu.vob_temp->get_name() << "'/>\n";
895 for (std::size_t button_num = 0;
896 button_num != menu.entries.size();
899 file << " <button> ";
901 if (menu.entries[button_num].first == dvd_contents::menu_pgc)
903 int dest_menu_num = menu.entries[button_num].second;
905 // Look for a button on the new menu that links
906 // back to this one. If there is one, set that to
907 // be the highlighted button; otherwise, use the
909 const std::vector<dvd_contents::pgc_ref> &
911 contents_.menus[dest_menu_num].entries;
912 dvd_contents::pgc_ref this_pgc(
913 dvd_contents::menu_pgc, menu_num);
914 std::size_t dest_button_num = dest_menu_entries.size();
915 while (dest_button_num != 0
916 && dest_menu_entries[--dest_button_num] != this_pgc)
920 << (1 + dest_menu_num
921 + (1 + dest_button_num) * button_mult)
922 << "; jump menu " << 1 + dest_menu_num << ";";
926 assert(menu.entries[button_num].first
927 == dvd_contents::title_pgc);
930 << 1 + menu_num + (1 + button_num) * button_mult
932 << 1 + menu.entries[button_num].second << ";";
935 file << " </button>\n";
945 // Generate a titleset for each title. This appears to make
946 // jumping to titles a whole lot simpler (but limits us to 99
948 for (std::size_t title_num = 0;
949 title_num != contents_.titles.size();
954 // Generate a dummy menu so that the menu button on the
955 // remote control will work.
957 " <pgc entry='root'>\n"
958 " <pre> jump vmgm menu; </pre>\n"
963 // Record calling location.
964 " <pre> g12 = g1; </pre>\n"
965 << contents_.titles[title_num].vob_list <<
966 // If the menu location has not been changed during
967 // the title, set the location to be the following
968 // button in the menu. In any case, return to some
970 " <post> if (g1 eq g12) g1 = g1 + " << button_mult
971 << "; call menu; </post>\n"
983 const char * argv[] = {
985 "-o", output_dir_.c_str(),
986 "-x", temp.get_name().c_str(),
990 Glib::spawn_sync(".",
991 Glib::ArrayHandle<std::string>(
992 argv, sizeof(argv)/sizeof(argv[0]),
993 Glib::OWNERSHIP_NONE),
994 Glib::SPAWN_SEARCH_PATH
995 | Glib::SPAWN_STDOUT_TO_DEV_NULL,
999 if (command_result != 0)
1000 throw std::runtime_error("dvdauthor failed");
1004 const video::frame_params & lookup_frame_params(const char * str)
1007 static const struct { const char * str; bool is_ntsc; }
1013 // For DVD purposes, SECAM can be treated identically to PAL.
1017 for (std::size_t i = 0;
1018 i != sizeof(known_strings)/sizeof(known_strings[0]);
1020 if (std::strcmp(str, known_strings[i].str) == 0)
1021 return known_strings[i].is_ntsc ?
1022 video::ntsc_params : video::pal_params;
1023 throw std::runtime_error(
1024 std::string("Invalid video standard: ").append(str));
1027 void print_usage(std::ostream & stream, const char * command_name)
1029 stream << "Usage: " << command_name
1030 << (" [gtk-options] [--video-std std-name]"
1031 " [--preview] menu-url [output-dir]\n");
1034 void set_browser_preferences()
1036 nsCOMPtr<nsIPrefService> pref_service;
1037 static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
1038 check(CallGetService<nsIPrefService>(pref_service_cid,
1039 getter_AddRefs(pref_service)));
1040 nsCOMPtr<nsIPrefBranch> pref_branch;
1042 // Disable IE-compatibility kluge that causes backgrounds to
1043 // sometimes/usually be missing from snapshots. This is only
1044 // effective from Mozilla 1.8 onward.
1045 # if MOZ_VERSION_MAJOR > 1 \
1046 || (MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR >= 8)
1047 check(pref_service->GetDefaultBranch("layout",
1048 getter_AddRefs(pref_branch)));
1049 check(pref_branch->SetBoolPref(
1050 "fire_onload_after_image_background_loads",
1054 // Set display resolution. With standard-definition video we
1055 // will be fitting ~600 pixels across a screen typically
1056 // ranging from 10 to 25 inches wide, for a resolution of
1057 // 24-60 dpi. I therefore declare the average horizontal
1058 // resolution to be 40 dpi. The vertical resolution will be
1059 // slightly higher (PAL/SECAM) or lower (NTSC), but
1060 // unfortunately Mozilla doesn't support non-square pixels
1061 // (and neither do fontconfig or Xft anyway).
1062 check(pref_service->GetDefaultBranch("browser.display",
1063 getter_AddRefs(pref_branch)));
1064 check(pref_branch->SetIntPref("screen_resolution", 40));
1069 int main(int argc, char ** argv)
1073 video::frame_params frame_params = video::pal_params;
1074 bool preview_mode = false;
1075 std::string menu_url;
1076 std::string output_dir;
1078 // Do initial option parsing. We have to do this before
1079 // letting Gtk parse the arguments since we may need to spawn
1082 while (argi != argc)
1084 if (std::strcmp(argv[argi], "--") == 0)
1088 else if (std::strcmp(argv[argi], "--help") == 0)
1090 print_usage(std::cout, argv[0]);
1091 return EXIT_SUCCESS;
1093 else if (std::strcmp(argv[argi], "--preview") == 0)
1095 preview_mode = true;
1098 else if (std::strcmp(argv[argi], "--video-std") == 0)
1100 if (argi + 1 == argc)
1102 std::cerr << "Missing argument to --video-std\n";
1103 print_usage(std::cerr, argv[0]);
1104 return EXIT_FAILURE;
1106 frame_params = lookup_frame_params(argv[argi + 1]);
1115 std::auto_ptr<x_frame_buffer> fb;
1118 // Spawn Xvfb and set env variables so that Xlib will use it
1119 // Use 8 bits each for RGB components, which should translate into
1120 // "enough" bits for YUV components.
1121 fb.reset(new x_frame_buffer(frame_params.width,
1122 frame_params.height,
1124 setenv("XAUTHORITY", fb->get_authority().c_str(), true);
1125 setenv("DISPLAY", fb->get_display().c_str(), true);
1129 Gtk::Main kit(argc, argv);
1131 // Complete option parsing with Gtk's options out of the way.
1133 while (argi != argc)
1135 if (std::strcmp(argv[argi], "--") == 0)
1140 else if (std::strcmp(argv[argi], "--preview") == 0)
1144 else if (std::strcmp(argv[argi], "--video-std") == 0)
1148 else if (argv[argi][0] == '-')
1150 std::cerr << "Invalid option: " << argv[argi] << "\n";
1151 print_usage(std::cerr, argv[0]);
1152 return EXIT_FAILURE;
1160 // Look for a starting URL or filename and (except in preview
1161 // mode) an output directory after the options.
1162 if (argc - argi != (preview_mode ? 1 : 2))
1164 print_usage(std::cerr, argv[0]);
1165 return EXIT_FAILURE;
1167 if (std::strstr(argv[argi], "://"))
1169 // It appears to be an absolute URL, so use it as-is.
1170 menu_url = argv[argi];
1174 // Assume it's a filename. Resolve it to an absolute URL.
1175 std::string path(argv[argi]);
1176 if (!Glib::path_is_absolute(path))
1177 path = Glib::build_filename(Glib::get_current_dir(), path);
1178 menu_url = Glib::filename_to_uri(path);
1181 output_dir = argv[argi + 1];
1183 // Initialise Mozilla
1184 browser_widget::initialiser browser_init;
1185 set_browser_preferences();
1187 // Run the browser/converter
1188 webdvd_window window(frame_params, menu_url, output_dir);
1189 Gtk::Main::run(window);
1191 catch (std::exception & e)
1193 std::cerr << "Fatal error: " << e.what() << "\n";
1194 return EXIT_FAILURE;
1197 return EXIT_SUCCESS;