1 // Copyright 2005-6 Ben Hutchings <ben@decadent.org.uk>.
2 // See the file "COPYING" for licence details.
9 #include <gdkmm/pixbuf.h>
10 #include <glibmm/miscutils.h>
11 #include <glibmm/spawn.h>
14 #include "generate_dvd.hpp"
15 #include "xml_utils.hpp"
19 // Return a closeness metric of an "end" rectangle to a "start"
20 // rectangle in the upward (-1) or downward (+1) direction. Given
21 // several possible "end" rectangles, the one that seems visually
22 // closest in the given direction should have the highest value of
23 // this metric. This is necessarily a heuristic function!
24 double directed_closeness(const rectangle & start, const rectangle & end,
27 // The obvious approach is to use the centres of the
28 // rectangles. However, for the "end" rectangle, using the
29 // horizontal position nearest the centre of the "start"
30 // rectangle seems to produce more reasonable results. For
31 // example, if there are two "end" rectangles equally near to
32 // the "start" rectangle in terms of vertical distance and one
33 // of them horizontally overlaps the centre of the "start"
34 // rectangle, we want to pick that one even if the centre of
35 // that rectangle is further away from the centre of the
37 int start_x = (start.left + start.right) / 2;
38 int start_y = (start.top + start.bottom) / 2;
39 int end_y = (end.top + end.bottom) / 2;
41 if (end.right < start_x)
43 else if (end.left > start_x)
48 // Return cosine of angle between the line between these points
49 // and the vertical, divided by the distance between the points
50 // if that is defined and positive; otherwise return 0.
51 int vertical_distance = (end_y - start_y) * y_dir;
52 if (vertical_distance <= 0)
54 double distance_squared =
55 (end_x - start_x) * (end_x - start_x)
56 + (end_y - start_y) * (end_y - start_y);
57 return vertical_distance / distance_squared;
60 std::string temp_file_name(const temp_dir & dir,
61 std::string base_name,
66 std::size_t index_pos = base_name.find("%3d");
67 assert(index_pos != std::string::npos);
68 base_name[index_pos] = '0' + index / 100;
69 base_name[index_pos + 1] = '0' + (index / 10) % 10;
70 base_name[index_pos + 2] = '0' + index % 10;
73 return Glib::build_filename(dir.get_name(), base_name);
76 // We would like to use just a single frame for the menu but this
77 // seems not to be legal or compatible. The minimum length of a
78 // cell is 0.4 seconds but I've seen a static menu using 12 frames
79 // on a "PAL" disc so let's say 0.5 seconds rounded down.
80 const char menu_duration_string[] = "0.5";
81 unsigned menu_duration_frames(const video::frame_params & params)
83 return params.rate_numer / params.rate_denom / 2;
87 dvd_generator::dvd_generator(const video::frame_params & frame_params,
89 : temp_dir_("videolink-"),
90 frame_params_(frame_params),
94 dvd_generator::pgc_ref dvd_generator::add_menu()
96 pgc_ref next_menu(menu_pgc, menus_.size());
98 // Check against maximum number of menus. It appears that no more
99 // than 128 menus are reachable through LinkPGCN instructions, and
100 // dvdauthor uses some menu numbers for special purposes, resulting
101 // in a practical limit of 119 per domain. We can work around this
102 // later by spreading some menus across titlesets.
103 if (next_menu.index == 119)
104 throw std::runtime_error("No more than 119 menus can be used");
106 menus_.resize(next_menu.index + 1);
110 void dvd_generator::add_menu_entry(unsigned index,
111 const rectangle & area,
112 const pgc_ref & target)
114 assert(index < menus_.size());
115 assert(target.type == menu_pgc && target.index < menus_.size()
116 || target.type == title_pgc && target.index < titles_.size());
117 menu_entry new_entry = { area, target };
118 menus_[index].entries.push_back(new_entry);
121 void dvd_generator::generate_menu_vob(unsigned index,
122 Glib::RefPtr<Gdk::Pixbuf> background,
123 Glib::RefPtr<Gdk::Pixbuf> highlights)
126 assert(index < menus_.size());
127 const menu & this_menu = menus_[index];
129 std::string background_name(
130 temp_file_name(temp_dir_, "menu-%3d-back.png", 1 + index));
131 std::cout << "saving " << background_name << std::endl;
132 background->save(background_name, "png");
134 std::string highlights_name(
135 temp_file_name(temp_dir_, "menu-%3d-links.png", 1 + index));
136 std::cout << "saving " << highlights_name << std::endl;
137 highlights->save(highlights_name, "png");
139 std::string spumux_name(
140 temp_file_name(temp_dir_, "menu-%3d.subpictures", 1 + index));
141 std::ofstream spumux_file(spumux_name.c_str());
145 " <spu force='yes' start='00:00:00.00'\n"
146 " highlight='" << highlights_name << "'\n"
147 " select='" << highlights_name << "'>\n";
148 int button_count = this_menu.entries.size();
149 for (int i = 0; i != button_count; ++i)
151 const menu_entry & this_entry = this_menu.entries[i];
153 // We program left and right to cycle through the buttons in
154 // the order the entries were added. This should result in
155 // left and right behaving like the tab and shift-tab keys
156 // would in the browser. Hopefully that's a sensible order.
157 // We program up and down to behave geometrically.
158 int up_button = i, down_button = i;
159 double up_closeness = 0.0, down_closeness = 0.0;
160 for (int j = 0; j != button_count; ++j)
162 const menu_entry & other_entry = this_menu.entries[j];
163 double closeness = directed_closeness(
164 this_entry.area, other_entry.area, -1);
165 if (closeness > up_closeness)
168 up_closeness = closeness;
172 closeness = directed_closeness(
173 this_entry.area, other_entry.area, 1);
174 if (closeness > down_closeness)
177 down_closeness = closeness;
181 spumux_file << " <button"
182 " x0='" << this_entry.area.left << "'"
183 " y0='" << this_entry.area.top << "'"
184 " x1='" << this_entry.area.right << "'"
185 " y1='" << this_entry.area.bottom << "'"
186 " left='" << (i == 0 ? button_count : i) << "'"
187 " right='" << 1 + (i + 1) % button_count << "'"
188 " up='" << 1 + up_button << "'"
189 " down='" << 1 + down_button << "'"
198 throw std::runtime_error("Failed to write control file for spumux");
200 std::ostringstream command_stream;
201 unsigned frame_count(menu_duration_frames(frame_params_));
202 if (encoder_ == mpeg_encoder_ffmpeg)
204 for (unsigned i = 0; i != frame_count; ++i)
206 std::string frame_name(background_name);
207 frame_name.push_back('-');
208 frame_name.push_back('0' + i / 10);
209 frame_name.push_back('0' + i % 10);
210 if (symlink(background_name.c_str(), frame_name.c_str()) != 0)
211 throw std::runtime_error(
212 std::string("symlink: ").append(std::strerror(errno)));
215 "ffmpeg -f image2 -vcodec png -i " << background_name << "-%02d"
216 " -target " << frame_params_.common_name << "-dvd"
217 " -vcodec mpeg2video -aspect 4:3 -an -y /dev/stdout";
221 assert(encoder_ == mpeg_encoder_mjpegtools_old
222 || encoder_ == mpeg_encoder_mjpegtools_new);
224 << "pngtopnm " << background_name
225 << " | ppmtoy4m -v0 -n" << frame_count << " -F"
226 << frame_params_.rate_numer << ":" << frame_params_.rate_denom
227 << " -A" << frame_params_.pixel_ratio_width
228 << ":" << frame_params_.pixel_ratio_height
230 // The chroma subsampling keywords changed between
231 // versions 1.6.2 and 1.8 of mjpegtools. There is no
232 // keyword that works with both.
233 if (encoder_ == mpeg_encoder_mjpegtools_old)
234 command_stream << "-S420_mpeg2";
236 command_stream << "-S420mpeg2";
238 " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
239 " | mplex -v0 -f8 -o/dev/stdout /dev/stdin";
242 << " | spumux -v0 -mdvd " << spumux_name
243 << " > " << temp_file_name(temp_dir_, "menu-%3d.mpeg", 1 + index);
244 std::string command(command_stream.str());
245 const char * argv[] = {
246 "/bin/sh", "-c", command.c_str(), 0
248 std::cout << "running " << command << std::endl;
250 Glib::spawn_sync(".",
251 Glib::ArrayHandle<std::string>(
252 argv, sizeof(argv)/sizeof(argv[0]),
253 Glib::OWNERSHIP_NONE),
254 Glib::SPAWN_STDOUT_TO_DEV_NULL,
258 if (command_result != 0)
259 throw std::runtime_error("spumux pipeline failed");
262 dvd_generator::pgc_ref dvd_generator::add_title(vob_list & content)
264 pgc_ref next_title(title_pgc, titles_.size());
266 // Check against maximum number of titles.
267 if (next_title.index == 99)
268 throw std::runtime_error("No more than 99 titles can be used");
270 titles_.resize(next_title.index + 1);
271 titles_[next_title.index].swap(content);
275 void dvd_generator::generate(const std::string & output_dir) const
277 std::string name(temp_file_name(temp_dir_, "videolink.dvdauthor"));
278 std::ofstream file(name.c_str());
280 // We generate code that uses registers in the following way:
283 // g1: target menu location
284 // g2: source/return menu location for title
285 // g3: target chapter number
287 // All locations are divided into two bitfields: the least
288 // significant 10 bits are a page/menu number and the most
289 // significant 6 bits are a link/button number, and numbering
290 // starts at 1, not 0. This is done for compatibility with
291 // the encoding of the s8 (button) register.
293 static const int button_mult = dvd::reg_s8_button_mult;
294 static const int menu_mask = button_mult - 1;
295 static const int button_mask = (1 << dvd::reg_bits) - button_mult;
302 for (unsigned menu_index = 0; menu_index != menus_.size(); ++menu_index)
304 const menu & this_menu = menus_[menu_index];
308 // This is the first (title) menu, displayed when the
309 // disc is first played.
311 " <pgc entry='title'>\n"
313 // Set a default target location if none is set.
314 // This covers first play and use of the "top menu"
317 " g1 = " << 1 + button_mult << ";\n";
326 // When a title finishes or the user presses the "menu"
327 // button, this always jumps to the titleset's root menu.
328 // We want to return the user to the last menu they used.
329 // So we arrange for each titleset's root menu to return
330 // to the vmgm title menu and then dispatch from there to
331 // whatever the correct menu is. We determine the correct
332 // menu by looking at the menu part of g1.
334 file << " g0 = g1 & " << menu_mask << ";\n";
336 // There is a limit of 128 VM instructions in each PGC.
337 // Therefore in each menu's <pre> section we generate
338 // jumps to menus with numbers greater by 512, 256, 128,
339 // ..., 1 where (a) such a menu exists, (b) this menu
340 // number is divisible by twice that increment and (c) the
341 // correct menu is that or a later menu. Thus each menu
342 // has at most 10 such conditional jumps and is reachable
343 // by at most 10 jumps from the title menu. This chain of
344 // jumps might take too long on some players; this has yet
345 // to be investigated.
347 for (std::size_t menu_incr = (menu_mask + 1) / 2;
351 if (menu_index + menu_incr < menus_.size()
352 && (menu_index & (menu_incr * 2 - 1)) == 0)
355 " if (g0 ge " << 1 + menu_index + menu_incr
357 " jump menu " << 1 + menu_index + menu_incr
363 // Highlight the appropriate button.
364 " s8 = g1 & " << button_mask << ";\n"
365 // Forget the link target. If we don't do this, pressing
366 // the "top menu" button will result in jumping back to
371 << temp_file_name(temp_dir_, "menu-%3d.mpeg", 1 + menu_index)
373 // Define a cell covering the whole menu and set a still
374 // time at the end of that, since it seems all players
375 // support that but some ignore a still time set on a PGC.
376 " <cell start='0' end='" << menu_duration_string << "'"
377 " chapter='yes' pause='inf'/>\n"
380 for (unsigned button_index = 0;
381 button_index != this_menu.entries.size();
384 const pgc_ref & target = this_menu.entries[button_index].target;
386 file << " <button> ";
388 if (target.type == menu_pgc)
390 unsigned target_button_num;
392 if (target.sub_index)
394 target_button_num = target.sub_index;
398 // Look for a button on the new menu that links
399 // back to this one. If there is one, set that to
400 // be the highlighted button; otherwise, use the
402 const std::vector<menu_entry> & target_menu_entries =
403 menus_[target.index].entries;
404 pgc_ref this_pgc(menu_pgc, menu_index);
405 target_button_num = target_menu_entries.size();
406 while (target_button_num != 1
407 && (target_menu_entries[target_button_num - 1].target
413 // Set new menu location.
414 "g1 = " << (1 + target.index
415 + target_button_num * button_mult) << "; "
416 // Jump to the target menu.
417 "jump menu " << 1 + target.index << "; ";
421 assert(target.type == title_pgc);
424 // Record current menu location.
425 "g2 = " << (1 + menu_index
426 + (1 + button_index) * button_mult) << "; "
427 // Set target chapter number.
428 "g3 = " << target.sub_index << "; "
429 // Jump to the target title.
430 "jump title " << 1 + target.index << "; ";
433 file << "</button>\n";
444 // Generate a titleset for each title. This appears to make
445 // jumping to titles a whole lot simpler (but limits us to 99
447 for (unsigned title_index = 0;
448 title_index != titles_.size();
453 // Generate a dummy menu so that the "menu" button will
454 // work. This returns to the source menu via the title
457 " <pgc entry='root'>\n"
458 " <pre> g1 = g2; jump vmgm menu; </pre>\n"
465 // Count chapters in the title.
466 unsigned n_chapters = 0;
467 for (vob_list::const_iterator
468 it = titles_[title_index].begin(),
469 end = titles_[title_index].end();
473 // Chapter start times may be specified in the "chapters"
474 // attribute as a comma-separated list. If this is not
475 // specified then the beginning of each file starts a new
476 // chapter. Thus the number of chapters in each file is
477 // the number of commas in the chapter attribute, plus 1.
480 while ((pos = it->chapters.find(',', pos)) != std::string::npos)
487 // Generate jump "table" for chapters.
488 for (unsigned chapter_num = 1;
489 chapter_num <= n_chapters;
492 " if (g3 == " << chapter_num << ")\n"
493 " jump chapter " << chapter_num << ";\n";
498 for (vob_list::const_iterator
499 it = titles_[title_index].begin(),
500 end = titles_[title_index].end();
504 file << " <vob file='" << xml_escape(it->file) << "'";
505 if (!it->chapters.empty())
506 file << " chapters='" << xml_escape(it->chapters) << "'";
507 if (!it->pause.empty())
508 file << " pause='" << xml_escape(it->pause) << "'";
514 // Return to the source menu, but highlight the next button.
515 " g2 = g2 + " << button_mult << ";\n"
529 const char * argv[] = {
531 "-o", output_dir.c_str(),
536 Glib::spawn_sync(".",
537 Glib::ArrayHandle<std::string>(
538 argv, sizeof(argv)/sizeof(argv[0]),
539 Glib::OWNERSHIP_NONE),
540 Glib::SPAWN_SEARCH_PATH
541 | Glib::SPAWN_STDOUT_TO_DEV_NULL,
545 if (command_result != 0)
546 throw std::runtime_error("dvdauthor failed");