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);
219 void save_screenshot();
220 void process_links(nsIPresShell * pres_shell,
221 nsIPresContext * pres_context,
222 nsIDOMWindow * dom_window);
225 video::frame_params frame_params_;
226 std::string output_dir_;
227 browser_widget browser_widget_;
228 nsCOMPtr<nsIStyleSheet> stylesheet_;
230 dvd_contents contents_;
231 typedef std::map<std::string, dvd_contents::pgc_ref> resource_map_type;
232 resource_map_type resource_map_;
234 std::queue<std::string> page_queue_;
235 bool pending_window_update_;
236 int pending_req_count_;
237 bool have_tweaked_page_;
238 std::auto_ptr<temp_file> background_temp_;
240 std::auto_ptr<page_state> page_state_;
243 webdvd_window::webdvd_window(
244 const video::frame_params & frame_params,
245 const std::string & main_page_uri,
246 const std::string & output_dir)
247 : frame_params_(frame_params),
248 output_dir_(output_dir),
249 stylesheet_(load_css("file://" WEBDVD_LIB_DIR "/webdvd.css")),
250 pending_window_update_(false),
251 pending_req_count_(0),
252 have_tweaked_page_(false)
254 set_size_request(frame_params_.width, frame_params_.height);
255 set_resizable(false);
257 add(browser_widget_);
258 browser_widget_.show();
259 browser_widget_.signal_net_state().connect(
260 SigC::slot(*this, &webdvd_window::on_net_state_change));
262 add_menu(main_page_uri);
266 dvd_contents::pgc_ref webdvd_window::add_menu(const std::string & uri)
268 dvd_contents::pgc_ref next_menu(dvd_contents::menu_pgc,
269 contents_.menus.size());
270 std::pair<resource_map_type::iterator, bool> insert_result(
271 resource_map_.insert(std::make_pair(uri, next_menu)));
273 if (!insert_result.second)
275 return insert_result.first->second;
279 page_queue_.push(uri);
280 contents_.menus.resize(contents_.menus.size() + 1);
285 dvd_contents::pgc_ref webdvd_window::add_title(const std::string & uri)
287 dvd_contents::pgc_ref next_title(dvd_contents::title_pgc,
288 contents_.titles.size());
289 std::pair<resource_map_type::iterator, bool> insert_result(
290 resource_map_.insert(std::make_pair(uri, next_title)));
292 if (!insert_result.second)
294 return insert_result.first->second;
298 Glib::ustring hostname;
299 std::string filename(Glib::filename_from_uri(uri, hostname));
300 // FIXME: Should check the hostname
302 std::string vob_list;
304 // Store a reference to a linked VOB file, or the contents
305 // of a linked VOB list file.
306 if (filename.compare(filename.size() - 4, 4, ".vob") == 0)
308 if (!Glib::file_test(filename, Glib::FILE_TEST_IS_REGULAR))
309 throw std::runtime_error(
310 filename + " is missing or not a regular file");
312 .append("<vob file='")
313 .append(xml_escape(filename))
318 assert(filename.compare(filename.size() - 8, 8, ".voblist")
320 // TODO: Validate the file contents
321 vob_list.assign(Glib::file_get_contents(filename));
324 contents_.titles.push_back(dvd_contents::title(vob_list));
329 void webdvd_window::load_next_page()
331 assert(!page_queue_.empty());
332 const std::string & uri = page_queue_.front();
333 std::cout << "loading " << uri << std::endl;
335 browser_widget_.load_uri(uri);
338 void webdvd_window::on_net_state_change(const char * uri,
339 gint flags, guint status)
341 # ifdef DEBUG_ON_NET_STATE_CHANGE
342 std::cout << "webdvd_window::on_net_state_change(";
344 std::cout << '"' << uri << '"';
349 gint flags_left = flags;
350 static const struct {
354 { GTK_MOZ_EMBED_FLAG_START, "STATE_START" },
355 { GTK_MOZ_EMBED_FLAG_REDIRECTING, "STATE_REDIRECTING" },
356 { GTK_MOZ_EMBED_FLAG_TRANSFERRING, "STATE_TRANSFERRING" },
357 { GTK_MOZ_EMBED_FLAG_NEGOTIATING, "STATE_NEGOTIATING" },
358 { GTK_MOZ_EMBED_FLAG_STOP, "STATE_STOP" },
359 { GTK_MOZ_EMBED_FLAG_IS_REQUEST, "STATE_IS_REQUEST" },
360 { GTK_MOZ_EMBED_FLAG_IS_DOCUMENT, "STATE_IS_DOCUMENT" },
361 { GTK_MOZ_EMBED_FLAG_IS_NETWORK, "STATE_IS_NETWORK" },
362 { GTK_MOZ_EMBED_FLAG_IS_WINDOW, "STATE_IS_WINDOW" }
364 for (int i = 0; i != sizeof(flag_names)/sizeof(flag_names[0]); ++i)
366 if (flags & flag_names[i].value)
368 std::cout << flag_names[i].name;
369 flags_left -= flag_names[i].value;
375 std::cout << "0x" << std::setbase(16) << flags_left;
377 std::cout << ", " << "0x" << std::setbase(16) << status << ")\n";
378 # endif // DEBUG_ON_NET_STATE_CHANGE
380 if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
382 if (flags & GTK_MOZ_EMBED_FLAG_START)
383 ++pending_req_count_;
385 if (flags & GTK_MOZ_EMBED_FLAG_STOP)
387 assert(pending_req_count_ != 0);
388 --pending_req_count_;
392 if (flags & GTK_MOZ_EMBED_FLAG_IS_DOCUMENT
393 && flags & GTK_MOZ_EMBED_FLAG_START)
395 pending_window_update_ = true;
396 have_tweaked_page_ = false;
399 if (flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW
400 && flags & GTK_MOZ_EMBED_FLAG_STOP)
402 // Check whether the load was successful, ignoring this
404 if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
407 pending_window_update_ = false;
410 if (pending_req_count_ == 0 && !pending_window_update_)
417 catch (std::exception & e)
419 std::cerr << "Fatal error";
420 if (!page_queue_.empty())
421 std::cerr << " while processing <" << page_queue_.front()
423 std::cerr << ": " << e.what() << "\n";
429 bool webdvd_window::process_page()
431 assert(!page_queue_.empty());
433 nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
434 nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
436 nsCOMPtr<nsIPresShell> pres_shell;
437 check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
438 nsCOMPtr<nsIPresContext> pres_context;
439 check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
440 nsCOMPtr<nsIDOMWindow> dom_window;
441 check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
443 // If we haven't done so already, apply the stylesheet and
444 // disable scrollbars.
445 if (!have_tweaked_page_)
447 apply_style_sheet(stylesheet_, pres_shell);
449 // This actually only needs to be done once.
450 nsCOMPtr<nsIDOMBarProp> dom_bar_prop;
451 check(dom_window->GetScrollbars(getter_AddRefs(dom_bar_prop)));
452 check(dom_bar_prop->SetVisible(false));
454 have_tweaked_page_ = true;
456 // Might need to wait a while for things to load or more
457 // likely for a re-layout.
458 if (pending_req_count_ > 0)
462 // All further work should only be done if we're not in preview mode.
463 if (!output_dir_.empty())
465 // If we haven't already started work on this menu, save a
466 // screenshot of its normal appearance.
467 if (!page_state_.get())
470 // Start or continue processing links.
471 process_links(pres_shell, pres_context, dom_window);
473 // If we've finished work on the links, move on to the
474 // next page, if any, or else generate the DVD filesystem.
475 if (!page_state_.get())
478 if (page_queue_.empty())
493 void webdvd_window::save_screenshot()
495 Glib::RefPtr<Gdk::Window> window(get_window());
497 window->process_updates(true);
499 background_temp_.reset(new temp_file("webdvd-back-"));
500 background_temp_->close();
501 std::cout << "saving " << background_temp_->get_name() << std::endl;
502 Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
503 window->get_colormap(),
505 frame_params_.width, frame_params_.height)
506 ->save(background_temp_->get_name(), "png");
509 struct webdvd_window::page_state
511 page_state(nsIDOMDocument * doc, int width, int height)
512 : diff_pixbuf(Gdk::Pixbuf::create(
514 true, 8, // has_alpha, bits_per_sample
516 spumux_temp("webdvd-spumux-"),
517 links_temp("webdvd-links-"),
526 Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
528 temp_file spumux_temp;
529 std::ofstream spumux_file;
531 temp_file links_temp;
534 link_iterator links_it, links_end;
538 Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
541 void webdvd_window::process_links(nsIPresShell * pres_shell,
542 nsIPresContext * pres_context,
543 nsIDOMWindow * dom_window)
545 Glib::RefPtr<Gdk::Window> window(get_window());
548 nsCOMPtr<nsIDOMDocument> basic_doc;
549 check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
550 nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
552 nsCOMPtr<nsIEventStateManager> event_state_man(
553 pres_context->EventStateManager()); // does not AddRef
554 assert(event_state_man);
555 nsCOMPtr<nsIDOMDocumentEvent> event_factory(
556 do_QueryInterface(basic_doc));
557 assert(event_factory);
558 nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
560 nsCOMPtr<nsIDOMAbstractView> view;
561 check(doc_view->GetDefaultView(getter_AddRefs(view)));
563 // Set up or recover our iteration state.
564 std::auto_ptr<page_state> state(page_state_);
569 basic_doc, frame_params_.width, frame_params_.height));
571 state->spumux_file.open(state->spumux_temp.get_name().c_str());
572 state->spumux_file <<
575 " <spu force='yes' start='00:00:00.00'\n"
576 " highlight='" << state->links_temp.get_name() << "'\n"
577 " select='" << state->links_temp.get_name() << "'>\n";
580 rectangle window_rect = {
581 0, 0, frame_params_.width, frame_params_.height
584 int menu_num = resource_map_[page_queue_.front()].second;
586 for (/* no initialisation */;
587 state->links_it != state->links_end;
590 nsCOMPtr<nsIDOMNode> node(*state->links_it);
592 // Find the link URI.
593 nsCOMPtr<nsILink> link(do_QueryInterface(node));
595 nsCOMPtr<nsIURI> uri;
596 check(link->GetHrefURI(getter_AddRefs(uri)));
597 std::string uri_string;
599 nsCString uri_ns_string;
600 check(uri->GetSpec(uri_ns_string));
601 uri_string.assign(uri_ns_string.BeginReading(),
602 uri_ns_string.EndReading());
604 std::string uri_sans_fragment(uri_string, 0, uri_string.find('#'));
606 // Is this a new link?
607 if (!state->link_changing)
609 // Find a rectangle enclosing the link and clip it to the
611 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
613 state->link_rect = get_elem_rect(ns_doc, elem);
614 state->link_rect &= window_rect;
616 if (state->link_rect.empty())
618 std::cerr << "Ignoring invisible link to "
619 << uri_string << "\n";
625 if (state->link_num >= dvd::menu_buttons_max)
627 if (state->link_num == dvd::menu_buttons_max)
628 std::cerr << "No more than " << dvd::menu_buttons_max
629 << " buttons can be placed on a menu\n";
630 std::cerr << "Ignoring link to " << uri_string << "\n";
634 state->spumux_file <<
635 " <button x0='" << state->link_rect.left << "'"
636 " y0='" << state->link_rect.top << "'"
637 " x1='" << state->link_rect.right - 1 << "'"
638 " y1='" << state->link_rect.bottom - 1 << "'/>\n";
640 // Check whether this is a link to a video or a page then
641 // add it to the known resources if not already seen; then
642 // add it to the menu entries.
644 check(uri->GetPath(path));
645 dvd_contents::pgc_ref dest_pgc;
646 // FIXME: This is a bit of a hack. Perhaps we could decide
647 // later based on the MIME type determined by Mozilla?
648 if ((path.Length() > 4
649 && std::strcmp(path.EndReading() - 4, ".vob") == 0)
650 || (path.Length() > 8
651 && std::strcmp(path.EndReading() - 8, ".voblist")
655 check(uri->SchemeIs("file", &is_file));
658 std::cerr << "Links to video must use the file:"
662 dest_pgc = add_title(uri_sans_fragment);
666 dest_pgc = add_menu(uri_sans_fragment);
668 contents_.menus[menu_num].entries.push_back(dest_pgc);
670 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
672 nsCOMPtr<nsIDOMEventTarget> event_target(
673 do_QueryInterface(node));
674 assert(event_target);
676 state->norm_pixbuf = Gdk::Pixbuf::create(
677 Glib::RefPtr<Gdk::Drawable>(window),
678 window->get_colormap(),
679 state->link_rect.left,
680 state->link_rect.top,
683 state->link_rect.right - state->link_rect.left,
684 state->link_rect.bottom - state->link_rect.top);
686 nsCOMPtr<nsIDOMEvent> event;
687 check(event_factory->CreateEvent(
688 NS_ConvertASCIItoUTF16("MouseEvents"),
689 getter_AddRefs(event)));
690 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
691 do_QueryInterface(event));
693 check(mouse_event->InitMouseEvent(
694 NS_ConvertASCIItoUTF16("mouseover"),
698 0, // detail: mouse click count
699 state->link_rect.left, // screenX
700 state->link_rect.top, // screenY
701 state->link_rect.left, // clientX
702 state->link_rect.top, // clientY
703 false, false, false, false, // qualifiers
704 0, // button: left (or primary)
705 0)); // related target
707 check(event_target->DispatchEvent(mouse_event,
709 check(event_state_man->SetContentState(content,
710 NS_EVENT_STATE_HOVER));
712 pres_shell->FlushPendingNotifications(true);
714 // We may have to exit and wait for image loading
715 // to complete, at which point we will be called
717 if (pending_req_count_ > 0)
719 state->link_changing = true;
725 window->process_updates(true);
727 Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
729 Glib::RefPtr<Gdk::Drawable>(window),
730 window->get_colormap(),
731 state->link_rect.left,
732 state->link_rect.top,
735 state->link_rect.right - state->link_rect.left,
736 state->link_rect.bottom - state->link_rect.top));
741 state->link_rect.left,
742 state->link_rect.top,
743 state->link_rect.right - state->link_rect.left,
744 state->link_rect.bottom - state->link_rect.top);
747 quantise_rgba_pixbuf(state->diff_pixbuf, dvd::button_n_colours);
749 std::cout << "saving " << state->links_temp.get_name()
751 state->diff_pixbuf->save(state->links_temp.get_name(), "png");
753 state->spumux_file <<
758 state->spumux_file.close();
760 // TODO: if (!state->spumux_file) throw ...
763 std::ostringstream command_stream;
764 command_stream << "pngtopnm "
765 << background_temp_->get_name()
766 << " | ppmtoy4m -v0 -n1 -F"
767 << frame_params_.rate_numer
768 << ":" << frame_params_.rate_denom
769 << " -A" << frame_params_.pixel_ratio_width
770 << ":" << frame_params_.pixel_ratio_height
771 << (" -Ip -S420_mpeg2"
772 " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
773 " | mplex -v0 -f8 -o/dev/stdout /dev/stdin"
774 " | spumux -v0 -mdvd ")
775 << state->spumux_temp.get_name()
777 << contents_.menus[menu_num].vob_temp->get_name();
778 std::string command(command_stream.str());
779 const char * argv[] = {
780 "/bin/sh", "-c", command.c_str(), 0
782 std::cout << "running " << argv[2] << std::endl;
784 Glib::spawn_sync(".",
785 Glib::ArrayHandle<std::string>(
786 argv, sizeof(argv)/sizeof(argv[0]),
787 Glib::OWNERSHIP_NONE),
788 Glib::SPAWN_STDOUT_TO_DEV_NULL,
792 if (command_result != 0)
793 throw std::runtime_error("spumux pipeline failed");
797 void webdvd_window::generate_dvd()
799 temp_file temp("webdvd-dvdauthor-");
801 std::ofstream file(temp.get_name().c_str());
803 // We generate code that uses registers in the following way:
806 // g1: current location
807 // g12: location that last jumped to a video
809 // All locations are divided into two bitfields: the least
810 // significant 10 bits are a page/menu number and the most
811 // significant 6 bits are a link/button number, and numbering
812 // starts at 1, not 0. This is done for compatibility with
813 // the encoding of the s8 (button) register.
815 static const int button_mult = dvd::reg_s8_button_mult;
816 static const int menu_mask = button_mult - 1;
817 static const int button_mask = (1 << dvd::reg_bits) - button_mult;
824 for (std::size_t menu_num = 0;
825 menu_num != contents_.menus.size();
828 dvd_contents::menu & menu = contents_.menus[menu_num];
832 // This is the first (title) menu, displayed when the
833 // disc is first played.
835 " <pgc entry='title'>\n"
837 // Initialise the current location if it is not set
838 // (all general registers are initially 0).
840 " g1 = " << 1 + button_mult << ";\n";
849 // When a title finishes or the user presses the menu
850 // button, this always jumps to the titleset's root menu.
851 // We want to return the user to the last menu they used.
852 // So we arrange for each titleset's root menu to return
853 // to the vmgm title menu and then dispatch from there to
854 // whatever the correct menu is. We determine the correct
855 // menu by looking at the menu part of g1.
857 file << " g0 = g1 & " << menu_mask << ";\n";
859 // There is a limit of 128 VM instructions in each PGC.
860 // Therefore in each menu's <pre> section we generate
861 // jumps to menus with numbers greater by 512, 256, 128,
862 // ..., 1 where (a) such a menu exists, (b) this menu
863 // number is divisible by twice that increment and (c) the
864 // correct menu is that or a later menu. Thus each menu
865 // has at most 10 such conditional jumps and is reachable
866 // by at most 10 jumps from the title menu. This chain of
867 // jumps might take too long on some players; this has yet
868 // to be investigated.
870 for (std::size_t menu_incr = (menu_mask + 1) / 2;
874 if (menu_num + menu_incr < contents_.menus.size()
875 && (menu_num & (menu_incr * 2 - 1)) == 0)
878 " if (g0 ge " << 1 + menu_num + menu_incr
880 " jump menu " << 1 + menu_num + menu_incr
886 // Highlight the appropriate button.
887 " s8 = g1 & " << button_mask << ";\n"
889 " <vob file='" << menu.vob_temp->get_name() << "'/>\n";
891 for (std::size_t button_num = 0;
892 button_num != menu.entries.size();
895 file << " <button> ";
897 if (menu.entries[button_num].first == dvd_contents::menu_pgc)
899 int dest_menu_num = menu.entries[button_num].second;
901 // Look for a button on the new menu that links
902 // back to this one. If there is one, set that to
903 // be the highlighted button; otherwise, use the
905 const std::vector<dvd_contents::pgc_ref> &
907 contents_.menus[dest_menu_num].entries;
908 dvd_contents::pgc_ref this_pgc(
909 dvd_contents::menu_pgc, menu_num);
910 std::size_t dest_button_num = dest_menu_entries.size();
911 while (dest_button_num != 0
912 && dest_menu_entries[--dest_button_num] != this_pgc)
916 << (1 + dest_menu_num
917 + (1 + dest_button_num) * button_mult)
918 << "; jump menu " << 1 + dest_menu_num << ";";
922 assert(menu.entries[button_num].first
923 == dvd_contents::title_pgc);
926 << 1 + menu_num + (1 + button_num) * button_mult
928 << 1 + menu.entries[button_num].second << ";";
931 file << " </button>\n";
941 // Generate a titleset for each title. This appears to make
942 // jumping to titles a whole lot simpler (but limits us to 99
944 for (std::size_t title_num = 0;
945 title_num != contents_.titles.size();
950 // Generate a dummy menu so that the menu button on the
951 // remote control will work.
953 " <pgc entry='root'>\n"
954 " <pre> jump vmgm menu; </pre>\n"
959 // Record calling location.
960 " <pre> g12 = g1; </pre>\n"
961 << contents_.titles[title_num].vob_list <<
962 // If the menu location has not been changed during
963 // the title, set the location to be the following
964 // button in the menu. In any case, return to some
966 " <post> if (g1 eq g12) g1 = g1 + " << button_mult
967 << "; call menu; </post>\n"
979 const char * argv[] = {
981 "-o", output_dir_.c_str(),
982 "-x", temp.get_name().c_str(),
986 Glib::spawn_sync(".",
987 Glib::ArrayHandle<std::string>(
988 argv, sizeof(argv)/sizeof(argv[0]),
989 Glib::OWNERSHIP_NONE),
990 Glib::SPAWN_SEARCH_PATH
991 | Glib::SPAWN_STDOUT_TO_DEV_NULL,
995 if (command_result != 0)
996 throw std::runtime_error("dvdauthor failed");
1000 const video::frame_params & lookup_frame_params(const char * str)
1003 static const struct { const char * str; bool is_ntsc; }
1009 // For DVD purposes, SECAM can be treated identically to PAL.
1013 for (std::size_t i = 0;
1014 i != sizeof(known_strings)/sizeof(known_strings[0]);
1016 if (std::strcmp(str, known_strings[i].str) == 0)
1017 return known_strings[i].is_ntsc ?
1018 video::ntsc_params : video::pal_params;
1019 throw std::runtime_error(
1020 std::string("Invalid video standard: ").append(str));
1023 void print_usage(std::ostream & stream, const char * command_name)
1025 stream << "Usage: " << command_name
1026 << (" [gtk-options] [--video-std std-name]"
1027 " [--preview] menu-url [output-dir]\n");
1030 void set_browser_preferences()
1032 nsCOMPtr<nsIPrefService> pref_service;
1033 static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
1034 check(CallGetService<nsIPrefService>(pref_service_cid,
1035 getter_AddRefs(pref_service)));
1036 nsCOMPtr<nsIPrefBranch> pref_branch;
1038 // Disable IE-compatibility kluge that causes backgrounds to
1039 // sometimes/usually be missing from snapshots. This is only
1040 // effective from Mozilla 1.8 onward.
1041 # if MOZ_VERSION_MAJOR > 1 \
1042 || (MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR >= 8)
1043 check(pref_service->GetDefaultBranch("layout",
1044 getter_AddRefs(pref_branch)));
1045 check(pref_branch->SetBoolPref(
1046 "fire_onload_after_image_background_loads",
1050 // Set display resolution. With standard-definition video we
1051 // will be fitting ~600 pixels across a screen typically
1052 // ranging from 10 to 25 inches wide, for a resolution of
1053 // 24-60 dpi. I therefore declare the average horizontal
1054 // resolution to be 40 dpi. The vertical resolution will be
1055 // slightly higher (PAL/SECAM) or lower (NTSC), but
1056 // unfortunately Mozilla doesn't support non-square pixels
1057 // (and neither do fontconfig or Xft anyway).
1058 check(pref_service->GetDefaultBranch("browser.display",
1059 getter_AddRefs(pref_branch)));
1060 check(pref_branch->SetIntPref("screen_resolution", 40));
1065 int main(int argc, char ** argv)
1069 video::frame_params frame_params = video::pal_params;
1070 bool preview_mode = false;
1071 std::string menu_url;
1072 std::string output_dir;
1074 // Do initial option parsing. We have to do this before
1075 // letting Gtk parse the arguments since we may need to spawn
1078 while (argi != argc)
1080 if (std::strcmp(argv[argi], "--") == 0)
1084 else if (std::strcmp(argv[argi], "--help") == 0)
1086 print_usage(std::cout, argv[0]);
1087 return EXIT_SUCCESS;
1089 else if (std::strcmp(argv[argi], "--preview") == 0)
1091 preview_mode = true;
1094 else if (std::strcmp(argv[argi], "--video-std") == 0)
1096 if (argi + 1 == argc)
1098 std::cerr << "Missing argument to --video-std\n";
1099 print_usage(std::cerr, argv[0]);
1100 return EXIT_FAILURE;
1102 frame_params = lookup_frame_params(argv[argi + 1]);
1111 std::auto_ptr<x_frame_buffer> fb;
1114 // Spawn Xvfb and set env variables so that Xlib will use it
1115 // Use 8 bits each for RGB components, which should translate into
1116 // "enough" bits for YUV components.
1117 fb.reset(new x_frame_buffer(frame_params.width,
1118 frame_params.height,
1120 setenv("XAUTHORITY", fb->get_authority().c_str(), true);
1121 setenv("DISPLAY", fb->get_display().c_str(), true);
1125 Gtk::Main kit(argc, argv);
1127 // Complete option parsing with Gtk's options out of the way.
1129 while (argi != argc)
1131 if (std::strcmp(argv[argi], "--") == 0)
1136 else if (std::strcmp(argv[argi], "--preview") == 0)
1140 else if (std::strcmp(argv[argi], "--video-std") == 0)
1144 else if (argv[argi][0] == '-')
1146 std::cerr << "Invalid option: " << argv[argi] << "\n";
1147 print_usage(std::cerr, argv[0]);
1148 return EXIT_FAILURE;
1156 // Look for a starting URL or filename and (except in preview
1157 // mode) an output directory after the options.
1158 if (argc - argi != (preview_mode ? 1 : 2))
1160 print_usage(std::cerr, argv[0]);
1161 return EXIT_FAILURE;
1163 if (std::strstr(argv[argi], "://"))
1165 // It appears to be an absolute URL, so use it as-is.
1166 menu_url = argv[argi];
1170 // Assume it's a filename. Resolve it to an absolute URL.
1171 std::string path(argv[argi]);
1172 if (!Glib::path_is_absolute(path))
1173 path = Glib::build_filename(Glib::get_current_dir(), path);
1174 menu_url = Glib::filename_to_uri(path);
1177 output_dir = argv[argi + 1];
1179 // Initialise Mozilla
1180 browser_widget::initialiser browser_init;
1181 set_browser_preferences();
1183 // Run the browser/converter
1184 webdvd_window window(frame_params, menu_url, output_dir);
1185 Gtk::Main::run(window);
1187 catch (std::exception & e)
1189 std::cerr << "Fatal error: " << e.what() << "\n";
1190 return EXIT_FAILURE;
1193 return EXIT_SUCCESS;