]> git.decadent.org.uk Git - videolink.git/blob - generate_dvd.cpp
Added auto-cleaning temporary directories.
[videolink.git] / generate_dvd.cpp
1 // Copyright 2005-6 Ben Hutchings <ben@decadent.org.uk>.
2 // See the file "COPYING" for licence details.
3
4 #include <fstream>
5 #include <iostream>
6 #include <sstream>
7 #include <stdexcept>
8
9 #include <gdkmm/pixbuf.h>
10 #include <glibmm/miscutils.h>
11 #include <glibmm/spawn.h>
12
13 #include "dvd.hpp"
14 #include "generate_dvd.hpp"
15 #include "xml_utils.hpp"
16
17 namespace
18 {
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,
25                               int y_dir)
26     {
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
36         // "start" rectangle.
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;
40         int end_x;
41         if (end.right < start_x)
42             end_x = end.right;
43         else if (end.left > start_x)
44             end_x = end.left;
45         else
46             end_x = start_x;
47
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)
53             return 0.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;
58     }
59
60     std::string temp_file_name(const temp_dir & dir,
61                                std::string base_name,
62                                unsigned index=0)
63     {
64         if (index != 0)
65         {
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;
71         }
72
73         return Glib::build_filename(dir.get_name(), base_name);
74     }
75 }
76
77 dvd_generator::dvd_generator(const video::frame_params & frame_params,
78                              mpeg_encoder encoder)
79         : temp_dir_("videolink-"),
80           frame_params_(frame_params),
81           encoder_(encoder)
82 {}
83
84 dvd_generator::pgc_ref dvd_generator::add_menu()
85 {
86     pgc_ref next_menu(menu_pgc, menus_.size());
87
88     // Check against maximum number of menus.  It appears that no more
89     // than 128 menus are reachable through LinkPGCN instructions, and
90     // dvdauthor uses some menu numbers for special purposes, resulting
91     // in a practical limit of 119 per domain.  We can work around this
92     // later by spreading some menus across titlesets.
93     if (next_menu.index == 119)
94         throw std::runtime_error("No more than 119 menus can be used");
95
96     menus_.resize(next_menu.index + 1);
97     return next_menu;
98 }
99
100 void dvd_generator::add_menu_entry(unsigned index,
101                                    const rectangle & area,
102                                    const pgc_ref & target)
103 {
104     assert(index < menus_.size());
105     assert(target.type == menu_pgc && target.index < menus_.size()
106            || target.type == title_pgc && target.index < titles_.size());
107     menu_entry new_entry = { area, target };
108     menus_[index].entries.push_back(new_entry);
109 }
110
111 void dvd_generator::generate_menu_vob(unsigned index,
112                                       Glib::RefPtr<Gdk::Pixbuf> background,
113                                       Glib::RefPtr<Gdk::Pixbuf> highlights)
114     const
115 {
116     assert(index < menus_.size());
117     const menu & this_menu = menus_[index];
118
119     std::string background_name(
120         temp_file_name(temp_dir_, "menu-%3d-back.png", 1 + index));
121     std::cout << "saving " << background_name << std::endl;
122     background->save(background_name, "png");
123
124     std::string highlights_name(
125         temp_file_name(temp_dir_, "menu-%3d-links.png", 1 + index));
126     std::cout << "saving " << highlights_name << std::endl;
127     highlights->save(highlights_name, "png");
128
129     std::string spumux_name(
130         temp_file_name(temp_dir_, "menu-%3d.subpictures", 1 + index));
131     std::ofstream spumux_file(spumux_name.c_str());
132     spumux_file <<
133         "<subpictures>\n"
134         "  <stream>\n"
135         "    <spu force='yes' start='00:00:00.00'\n"
136         "        highlight='" << highlights_name << "'\n"
137         "        select='" << highlights_name << "'>\n";
138     int button_count = this_menu.entries.size();
139     for (int i = 0; i != button_count; ++i)
140     {
141         const menu_entry & this_entry = this_menu.entries[i];
142
143         // We program left and right to cycle through the buttons in
144         // the order the entries were added.  This should result in
145         // left and right behaving like the tab and shift-tab keys
146         // would in the browser.  Hopefully that's a sensible order.
147         // We program up and down to behave geometrically.
148         int up_button = i, down_button = i;
149         double up_closeness = 0.0, down_closeness = 0.0;
150         for (int j = 0; j != button_count; ++j)
151         {
152             const menu_entry & other_entry = this_menu.entries[j];
153             double closeness = directed_closeness(
154                 this_entry.area, other_entry.area, -1);
155             if (closeness > up_closeness)
156             {
157                 up_button = j;
158                 up_closeness = closeness;
159             }
160             else
161             {
162                 closeness = directed_closeness(
163                     this_entry.area, other_entry.area, 1);
164                 if (closeness > down_closeness)
165                 {
166                     down_button = j;
167                     down_closeness = closeness;
168                 }
169             }
170         }
171         spumux_file << "      <button"
172             " x0='" << this_entry.area.left << "'"
173             " y0='" << this_entry.area.top << "'"
174             " x1='" << this_entry.area.right << "'"
175             " y1='" << this_entry.area.bottom << "'"
176             " left='" << (i == 0 ? button_count : i) << "'"
177             " right='" << 1 + (i + 1) % button_count << "'"
178             " up='" << 1 + up_button << "'"
179             " down='" << 1 + down_button << "'"
180             "/>\n";
181     }
182     spumux_file <<
183         "    </spu>\n"
184         "  </stream>\n"
185         "</subpictures>\n";
186     spumux_file.close();
187     if (!spumux_file)
188         throw std::runtime_error("Failed to write control file for spumux");
189
190     std::ostringstream command_stream;
191     if (encoder_ == mpeg_encoder_ffmpeg)
192     {
193         command_stream
194             << "ffmpeg"
195             << " -f image2 -vcodec png -i "
196             << background_name
197             << " -target " << frame_params_.common_name <<  "-dvd"
198             << " -vcodec mpeg2video -aspect 4:3 -an -y /dev/stdout";
199     }
200     else
201     {
202         assert(encoder_ == mpeg_encoder_mjpegtools_old
203                || encoder_ == mpeg_encoder_mjpegtools_new);
204         command_stream
205             << "pngtopnm "
206             << background_name
207             << " | ppmtoy4m -v0 -n1 -F"
208             << frame_params_.rate_numer << ":" << frame_params_.rate_denom
209             << " -A" << frame_params_.pixel_ratio_width
210             << ":" << frame_params_.pixel_ratio_height
211             << " -Ip ";
212         // The chroma subsampling keywords changed between
213         // versions 1.6.2 and 1.8 of mjpegtools.  There is no
214         // keyword that works with both.
215         if (encoder_ == mpeg_encoder_mjpegtools_old)
216             command_stream << "-S420_mpeg2";
217         else
218             command_stream << "-S420mpeg2";
219         command_stream <<
220             " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
221             " | mplex -v0 -f8 -o/dev/stdout /dev/stdin";
222     }
223     command_stream
224         << " | spumux -v0 -mdvd " << spumux_name
225         << " > " << temp_file_name(temp_dir_, "menu-%3d.mpeg", 1 + index);
226     std::string command(command_stream.str());
227     const char * argv[] = {
228         "/bin/sh", "-c", command.c_str(), 0
229     };
230     std::cout << "running " << command << std::endl;
231     int command_result;
232     Glib::spawn_sync(".",
233                      Glib::ArrayHandle<std::string>(
234                          argv, sizeof(argv)/sizeof(argv[0]),
235                          Glib::OWNERSHIP_NONE),
236                      Glib::SPAWN_STDOUT_TO_DEV_NULL,
237                      SigC::Slot0<void>(),
238                      0, 0,
239                      &command_result);
240     if (command_result != 0)
241         throw std::runtime_error("spumux pipeline failed");
242 }
243
244 dvd_generator::pgc_ref dvd_generator::add_title(vob_list & content)
245 {
246     pgc_ref next_title(title_pgc, titles_.size());
247
248     // Check against maximum number of titles.
249     if (next_title.index == 99)
250         throw std::runtime_error("No more than 99 titles can be used");
251
252     titles_.resize(next_title.index + 1);
253     titles_[next_title.index].swap(content);
254     return next_title;
255 }
256
257 void dvd_generator::generate(const std::string & output_dir) const
258 {
259     std::string name(temp_file_name(temp_dir_, "videolink.dvdauthor"));
260     std::ofstream file(name.c_str());
261
262     // We generate code that uses registers in the following way:
263     //
264     // g0:     scratch
265     // g1:     target menu location
266     // g2:     source/return menu location for title
267     // g3:     target chapter number
268     //
269     // All locations are divided into two bitfields: the least
270     // significant 10 bits are a page/menu number and the most
271     // significant 6 bits are a link/button number, and numbering
272     // starts at 1, not 0.  This is done for compatibility with
273     // the encoding of the s8 (button) register.
274     //
275     static const int button_mult = dvd::reg_s8_button_mult;
276     static const int menu_mask = button_mult - 1;
277     static const int button_mask = (1 << dvd::reg_bits) - button_mult;
278
279     file <<
280         "<dvdauthor>\n"
281         "  <vmgm>\n"
282         "    <menus>\n";
283             
284     for (unsigned menu_index = 0; menu_index != menus_.size(); ++menu_index)
285     {
286         const menu & this_menu = menus_[menu_index];
287
288         if (menu_index == 0)
289         {
290             // This is the first (title) menu, displayed when the
291             // disc is first played.
292             file <<
293                 "      <pgc entry='title' pause='inf'>\n"
294                 "        <pre>\n"
295                 // Set a default target location if none is set.
296                 // This covers first play and use of the "top menu"
297                 // button.
298                 "          if (g1 eq 0)\n"
299                 "            g1 = " << 1 + button_mult << ";\n";
300         }
301         else
302         {
303             file <<
304                 "      <pgc pause='inf'>\n"
305                 "        <pre>\n";
306         }
307
308         // When a title finishes or the user presses the "menu"
309         // button, this always jumps to the titleset's root menu.
310         // We want to return the user to the last menu they used.
311         // So we arrange for each titleset's root menu to return
312         // to the vmgm title menu and then dispatch from there to
313         // whatever the correct menu is.  We determine the correct
314         // menu by looking at the menu part of g1.
315
316         file << "          g0 = g1 &amp; " << menu_mask << ";\n";
317
318         // There is a limit of 128 VM instructions in each PGC.
319         // Therefore in each menu's <pre> section we generate
320         // jumps to menus with numbers greater by 512, 256, 128,
321         // ..., 1 where (a) such a menu exists, (b) this menu
322         // number is divisible by twice that increment and (c) the
323         // correct menu is that or a later menu.  Thus each menu
324         // has at most 10 such conditional jumps and is reachable
325         // by at most 10 jumps from the title menu.  This chain of
326         // jumps might take too long on some players; this has yet
327         // to be investigated.
328             
329         for (std::size_t menu_incr = (menu_mask + 1) / 2;
330              menu_incr != 0;
331              menu_incr /= 2)
332         {
333             if (menu_index + menu_incr < menus_.size()
334                 && (menu_index & (menu_incr * 2 - 1)) == 0)
335             {
336                 file <<
337                     "          if (g0 ge " << 1 + menu_index + menu_incr
338                                            << ")\n"
339                     "            jump menu " << 1 + menu_index + menu_incr
340                                            << ";\n";
341             }
342         }
343
344         file <<
345             // Highlight the appropriate button.
346             "          s8 = g1 &amp; " << button_mask << ";\n"
347             // Forget the link target.  If we don't do this, pressing
348             // the "top menu" button will result in jumping back to
349             // this same menu!
350             "          g1 = 0;\n"
351             "        </pre>\n"
352             "        <vob file='"
353              << temp_file_name(temp_dir_, "menu-%3d.mpeg", 1 + menu_index)
354              << "'/>\n";
355
356         for (unsigned button_index = 0;
357              button_index != this_menu.entries.size();
358              ++button_index)
359         {
360             const pgc_ref & target = this_menu.entries[button_index].target;
361
362             file << "        <button> ";
363
364             if (target.type == menu_pgc)
365             {
366                 unsigned target_button_num;
367
368                 if (target.sub_index)
369                 {
370                     target_button_num = target.sub_index;
371                 }
372                 else
373                 {
374                     // Look for a button on the new menu that links
375                     // back to this one.  If there is one, set that to
376                     // be the highlighted button; otherwise, use the
377                     // first button.
378                     const std::vector<menu_entry> & target_menu_entries =
379                         menus_[target.index].entries;
380                     pgc_ref this_pgc(menu_pgc, menu_index);
381                     target_button_num = target_menu_entries.size();
382                     while (target_button_num != 1
383                            && (target_menu_entries[target_button_num - 1].target
384                                != this_pgc))
385                         --target_button_num;
386                 }
387                          
388                 file <<
389                     // Set new menu location.
390                     "g1 = " << (1 + target.index
391                                 + target_button_num * button_mult) << "; "
392                     // Jump to the target menu.
393                     "jump menu " << 1 + target.index << "; ";
394             }
395             else
396             {
397                 assert(target.type == title_pgc);
398
399                 file <<
400                     // Record current menu location.
401                     "g2 = " << (1 + menu_index
402                                 + (1 + button_index) * button_mult) << "; "
403                     // Set target chapter number.
404                     "g3 = " << target.sub_index << "; "
405                     // Jump to the target title.
406                     "jump title " << 1 + target.index << "; ";
407             }
408
409             file <<  "</button>\n";
410         }
411
412         file <<
413             // Some DVD players don't seem to obey pause='inf' so make
414             // them loop.
415             "        <post>\n"
416             "          jump cell 1;\n"
417             "        </post>\n"
418             "      </pgc>\n";
419     }
420
421     file <<
422         "    </menus>\n"
423         "  </vmgm>\n";
424  
425     // Generate a titleset for each title.  This appears to make
426     // jumping to titles a whole lot simpler (but limits us to 99
427     // titles).
428     for (unsigned title_index = 0;
429          title_index != titles_.size();
430          ++title_index)
431     {
432         file <<
433             "  <titleset>\n"
434             // Generate a dummy menu so that the "menu" button will
435             // work.  This returns to the source menu via the title
436             // menu.
437             "    <menus>\n"
438             "      <pgc entry='root'>\n"
439             "        <pre> g1 = g2; jump vmgm menu; </pre>\n"
440             "      </pgc>\n"
441             "    </menus>\n"
442             "    <titles>\n"
443             "      <pgc>\n"
444             "        <pre>\n";
445
446         // Count chapters in the title.
447         unsigned n_chapters = 0;
448         for (vob_list::const_iterator
449                  it = titles_[title_index].begin(),
450                  end = titles_[title_index].end();
451              it != end;
452              ++it)
453         {
454             // Chapter start times may be specified in the "chapters"
455             // attribute as a comma-separated list.  If this is not
456             // specified then the beginning of each file starts a new
457             // chapter.  Thus the number of chapters in each file is
458             // the number of commas in the chapter attribute, plus 1.
459             ++n_chapters;
460             std::size_t pos = 0;
461             while ((pos = it->chapters.find(',', pos)) != std::string::npos)
462             {
463                 ++n_chapters;
464                 ++pos;
465             }
466         }
467
468         // Generate jump "table" for chapters.
469         for (unsigned chapter_num = 1;
470              chapter_num <= n_chapters;
471              ++chapter_num)
472             file <<
473                 "          if (g3 == " << chapter_num << ")\n"
474                 "            jump chapter " << chapter_num << ";\n";
475
476         file <<
477             "        </pre>\n";
478
479         for (vob_list::const_iterator
480                  it = titles_[title_index].begin(),
481                  end = titles_[title_index].end();
482              it != end;
483              ++it)
484         {
485             file << "        <vob file='" << xml_escape(it->file) << "'";
486             if (!it->chapters.empty())
487                 file << " chapters='" << xml_escape(it->chapters) << "'";
488             if (!it->pause.empty())
489                 file << " pause='" << xml_escape(it->pause) << "'";
490             file << "/>\n";
491         }
492
493         file <<
494             "        <post>\n"
495             // Return to the source menu, but highlight the next button.
496             "          g2 = g2 + " << button_mult << ";\n"
497             "          call menu;\n"
498             "        </post>\n"
499             "      </pgc>\n"
500             "    </titles>\n"
501             "  </titleset>\n";
502     }
503
504     file <<
505         "</dvdauthor>\n";
506
507     file.close();
508
509     {
510         const char * argv[] = {
511             "dvdauthor",
512             "-o", output_dir.c_str(),
513             "-x", name.c_str(),
514             0
515         };
516         int command_result;
517         Glib::spawn_sync(".",
518                          Glib::ArrayHandle<std::string>(
519                              argv, sizeof(argv)/sizeof(argv[0]),
520                              Glib::OWNERSHIP_NONE),
521                          Glib::SPAWN_SEARCH_PATH
522                          | Glib::SPAWN_STDOUT_TO_DEV_NULL,
523                          SigC::Slot0<void>(),
524                          0, 0,
525                          &command_result);
526         if (command_result != 0)
527             throw std::runtime_error("dvdauthor failed");
528     }
529 }