encode.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use IPC::Open3;
  6. use File::Basename;
  7. # Parameters
  8. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--encopts', 'b-adapt=2:rc-lookahead=50', '--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ca_aac', '--mixdown', 'dpl2', '--ab', '192');
  9. my $FORMAT = 'mp4';
  10. my $QUALITY = 20;
  11. my $HD_QUALITY = 20;
  12. my $HD_WIDTH = 1350;
  13. my $MIN_VIDEO_WIDTH = 100;
  14. my $MAX_CROP_DIFF = .1;
  15. my $MAX_DURA_DIFF = 5;
  16. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  17. my $DEBUG = 0;
  18. # Runtime debug mode
  19. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  20. $DEBUG = 1;
  21. }
  22. # Command-line parameters
  23. my ($in_file, $out_file, $title) = @ARGV;
  24. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  25. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  26. }
  27. # Scan for title/track info
  28. my %titles = &scan($in_file);
  29. # Allow external subtitles for single-title files
  30. if (scalar(keys(%titles)) == 1) {
  31. my $srt_file = $in_file;
  32. $srt_file =~ s/\.\w{2,3}$/.srt/;
  33. if (-r $srt_file) {
  34. if ($DEBUG) {
  35. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  36. }
  37. push(@video_params, '--srt-file', $srt_file);
  38. }
  39. }
  40. # Allow encoding of a specific title
  41. if ($title) {
  42. if ($title =~ /^\d+$/ && $title > 0) {
  43. if (!defined($titles{$title})) {
  44. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  45. }
  46. my $selected_title = $titles{$title};
  47. %titles = ();
  48. $titles{$title} = $selected_title;
  49. } elsif ($title =~ /main/i) {
  50. my $max_title = 0;
  51. my $max_duration = 0;
  52. foreach my $title (keys(%titles)) {
  53. if (!$titles{$title}{'duration'}) {
  54. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  55. next;
  56. }
  57. my $new_max = 0;
  58. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  59. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  60. $new_max = 1;
  61. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  62. $new_max = 1;
  63. }
  64. } elsif ($titles{$title}{'duration'} > $max_duration) {
  65. $new_max = 1;
  66. }
  67. if ($new_max) {
  68. $max_duration = $titles{$title}{'duration'};
  69. $max_title = $title;
  70. }
  71. }
  72. my $selected_title = $titles{$max_title};
  73. %titles = ();
  74. $titles{$max_title} = $selected_title;
  75. }
  76. }
  77. # Ensure we have an output file name
  78. # Allow forced use of MKV wrapper if the output file name is provided and ends in .MKV
  79. if (!defined($out_file) || length($out_file) < 1) {
  80. $out_file = $in_file;
  81. } else {
  82. my ($force_format) = $out_file =~ /\.(\w{2,3})$/;
  83. if (lc($force_format) eq 'mkv') {
  84. $FORMAT = 'mkv';
  85. }
  86. }
  87. # Encode each title
  88. foreach my $title (keys(%titles)) {
  89. if ($DEBUG) {
  90. print STDERR 'Setting options for title: ' . $title . "\n";
  91. }
  92. # Parse the title's audio and subtitle tracks
  93. my $scan = $titles{$title};
  94. my @audio = &audioOptions($scan);
  95. my @subs = &subOptions($scan);
  96. # Skip tracks that have no video
  97. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  98. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  99. next;
  100. }
  101. # Skip tracks that have no audio
  102. if (scalar(@{ $scan->{'audio'} }) < 1) {
  103. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  104. next;
  105. }
  106. # Reduce the quality if the image size is particularly large
  107. my $title_quality = $QUALITY;
  108. if ($scan->{'size'}[0] > $HD_WIDTH) {
  109. $title_quality = $HD_QUALITY;
  110. }
  111. # Override unlikely autocrop values
  112. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  113. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  114. {
  115. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  116. my @crop = (0, 0, 0, 0);
  117. $scan->{'crop'} = \@crop;
  118. }
  119. # Select a file name extension that matches the format
  120. my $title_out_file = $out_file;
  121. $title_out_file =~ s/\.(?:\w{2,3}|dvdmedia)$//i;
  122. if ($FORMAT eq 'mkv') {
  123. $title_out_file .= '.mkv';
  124. } else {
  125. $title_out_file .= '.m4v';
  126. }
  127. # Force the title number into the output file name if there are multiple titles to be encoded
  128. if (scalar(keys(%titles)) > 1) {
  129. my $title_text = sprintf('%02d', $title);
  130. $title_out_file =~ s/(\.\w{2,3})$/\-${title_text}${1}/;
  131. }
  132. # Sanity check
  133. if (uc($title_out_file) eq uc($in_file)) {
  134. $title_out_file =~ s/(\.\w{2,3})$/-recode${1}/;
  135. }
  136. if (-e $title_out_file) {
  137. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  138. next;
  139. }
  140. # Build the arugment list
  141. my @args = ($HB_EXEC);
  142. push(@args, '--title', $title);
  143. push(@args, '--input', $in_file);
  144. push(@args, '--output', $title_out_file);
  145. push(@args, '--format', $FORMAT);
  146. push(@args, '--quality', $title_quality);
  147. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  148. push(@args, @video_params);
  149. push(@args, @audio);
  150. push(@args, @subs);
  151. # Run it
  152. if ($DEBUG) {
  153. print STDERR join(' ', @args) . "\n";
  154. }
  155. my $child_out = '';
  156. my $child_in = '';
  157. my $pid = open3($child_in, $child_out, $child_out, @args);
  158. close($child_in);
  159. while (<$child_out>) {
  160. if ($DEBUG) {
  161. print STDERR $_;
  162. }
  163. }
  164. waitpid($pid, 0);
  165. close($child_out);
  166. # Provide the new file name if requested
  167. if ($ENV{'RECODE_OUTFILE'}) {
  168. print $title_out_file;
  169. }
  170. }
  171. # Cleanup
  172. exit(0);
  173. sub subOptions($) {
  174. my ($scan) = @_;
  175. # Find English subtitles
  176. my @keep = ();
  177. foreach my $track (@{ $scan->{'subtitle'} }) {
  178. if (my ($lang) = $track->{'description'} =~ /\b(English|Unknown|Closed\s+Captions)\b/i) {
  179. push(@keep, $track->{'index'});
  180. if ($DEBUG) {
  181. print STDERR 'Found ' . $lang . ' subtitle in track ' . $track->{'index'} . "\n";
  182. }
  183. }
  184. }
  185. # Send back the argument string (if any)
  186. if (scalar(@keep) < 1) {
  187. return '';
  188. }
  189. return ('--subtitle', join(',', @keep));
  190. }
  191. sub audioOptions($) {
  192. my ($scan) = @_;
  193. # Type the audio tracks
  194. my @channels = ();
  195. my @dts_hd = ();
  196. my @dts = ();
  197. my @ac3 = ();
  198. my @pcm = ();
  199. my @aac = ();
  200. my @oat = ();
  201. foreach my $track (@{ $scan->{'audio'} }) {
  202. my ($language, $codec, $chans, $iso) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(([^\)]+)\))?/;
  203. if (!defined($chans)) {
  204. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  205. # Temporarily exit on parsing errors -- at least until we're sure about this new parser
  206. exit(1);
  207. next;
  208. }
  209. if ($DEBUG) {
  210. print STDERR 'Found audio track: codec => ' . $codec . ', channels => ' . $chans . ', language => ' . $language . ', ISO => ' . $iso . "\n";
  211. }
  212. # Decode the channels string to a number
  213. if ($chans =~ /(\d+\.\d+)\s+ch/i) {
  214. $chans = $1;
  215. } elsif ($chans =~ /Dolby\s+Surround/i) {
  216. $chans = 3.1;
  217. }
  218. $channels[ $track->{'index'} ] = $chans;
  219. # Skip foreign langugae tracks
  220. if ($language =~ /\b(Chinese|Espanol|Francais|Japanese|Korean|Portugues|Thai)\b/i) {
  221. if ($DEBUG) {
  222. print STDERR 'Skipping AC3 in track ' . $track->{'index'} . ' due to language: ' . $language . "\n";
  223. }
  224. next;
  225. }
  226. # Filter by codec
  227. if ($codec =~ /DTS/i) {
  228. if ($codec =~ /DTS\-MA/i) {
  229. push(@dts_hd, $track->{'index'});
  230. } else {
  231. push(@dts, $track->{'index'});
  232. }
  233. } elsif ($codec =~ /AC3/i) {
  234. push(@ac3, $track->{'index'});
  235. } elsif ($codec =~ /PCM_[SF]\d+/i) {
  236. push(@pcm, $track->{'index'});
  237. } elsif ($codec =~ /AAC/i) {
  238. push(@aac, $track->{'index'});
  239. } else {
  240. push(@oat, $track->{'index'});
  241. if ($DEBUG) {
  242. if (!($codec =~ /MP3/i || $codec =~ /MPEG/i)) {
  243. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  244. }
  245. }
  246. }
  247. }
  248. # We should sort the different codecs by number of channels
  249. # But so far I've had good luck just taking the first track with the best codec
  250. # Pick a stereo/mixdown plan based on the available track types
  251. my $mixdown = undef();
  252. if (scalar(@dts_hd) > 0) {
  253. $mixdown = $dts_hd[0];
  254. } elsif (scalar(@dts) > 0) {
  255. $mixdown = $dts[0];
  256. } elsif (scalar(@ac3) > 0 || scalar(@pcm) > 0) {
  257. if (scalar(@pcm) < 1) {
  258. $mixdown = $ac3[0];
  259. } elsif (scalar(@ac3) < 1) {
  260. $mixdown = $pcm[0];
  261. } elsif ($channels[ $pcm[0] ] >= $channels[ $ac3[0] ]) {
  262. $mixdown = $pcm[0];
  263. } elsif ($channels[ $pcm[0] ] >= $channels[ $ac3[0] ]) {
  264. $mixdown = $pcm[0];
  265. }
  266. } elsif (scalar(@aac)) {
  267. $mixdown = $aac[0];
  268. } elsif (scalar(@oat)) {
  269. $mixdown = $oat[0];
  270. }
  271. # Sanity check
  272. if (!defined($mixdown) || $mixdown < 1) {
  273. print STDERR basename($0) . ": No usable audio tracks in title\n";
  274. return;
  275. }
  276. # Mixdown track first
  277. my @audio_tracks = ();
  278. if (defined($mixdown) && $mixdown > 0) {
  279. if ($DEBUG) {
  280. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  281. if ($channels[$mixdown] > 2) {
  282. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  283. }
  284. }
  285. my %track = ('index' => $mixdown, 'encoder' => 'ca_aac');
  286. push(@audio_tracks, \%track);
  287. }
  288. # Passthru DTS-MA, DTS, AC3, and AAC
  289. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  290. foreach my $codec_set (\@dts_hd, \@dts, \@ac3, \@aac, \@pcm, \@oat) {
  291. foreach my $audio_track (@{$codec_set}) {
  292. if ($mixdown == $audio_track && $channels[$mixdown] <= 2) {
  293. if ($DEBUG) {
  294. print STDERR 'Skipping AAC recode of track ' . $audio_track . ' since it is already used as the default track and contains only ' . $channels[$audio_track] . " channels\n";
  295. }
  296. next;
  297. }
  298. if ($DEBUG) {
  299. print STDERR 'Keeping audio track: ' . $audio_track . "\n";
  300. }
  301. my %track = ('index' => $audio_track, 'encoder' => 'copy');
  302. push(@audio_tracks, \%track);
  303. }
  304. }
  305. # Consolidate from the hashes
  306. my @tracks = ();
  307. my @encoders = ();
  308. foreach my $track (@audio_tracks) {
  309. push(@tracks, $track->{'index'});
  310. push(@encoders, $track->{'encoder'});
  311. }
  312. # Send back the argument strings
  313. return ('--audio', join(',', @tracks), '--aencoder', join(',', @encoders));
  314. }
  315. sub scan($) {
  316. my ($in_file) = @_;
  317. # Fork to scan the file
  318. my $child_out = '';
  319. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--title', '0', '--input', $in_file);
  320. # Loop through the output
  321. my $scan;
  322. my %titles = ();
  323. my $inTitle = 0;
  324. my $zone = '';
  325. my $dca_stream = -1;
  326. my %dca_lossless = ();
  327. while (<$child_out>) {
  328. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  329. if ($DEBUG) {
  330. print STDERR 'Found ' . $1 . " titles in source\n";
  331. }
  332. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  333. my $stream = $1;
  334. my $desc = $2;
  335. $dca_stream = -1;
  336. if ($desc =~ /Audio\:\s+dca/) {
  337. $dca_stream = $stream;
  338. }
  339. } elsif ($dca_stream >= 0 && m/^\s+title\s*\:\s+(.*)/) {
  340. if ($1 =~ /Lossless/i) {
  341. $dca_lossless{$dca_stream} = 1;
  342. if ($DEBUG) {
  343. print STDERR 'Found DTS Lossless audio in stream: ' . $dca_stream . "\n";
  344. }
  345. }
  346. $dca_stream = -1;
  347. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  348. # Save the current title (if any)
  349. if ($inTitle) {
  350. $titles{$inTitle} = $scan;
  351. }
  352. # Grab the new title number
  353. $inTitle = $1;
  354. # Init the data collectors
  355. my @audio = ();
  356. my @crop = ();
  357. my @subtitle = ();
  358. my @size = ();
  359. my %tmp = (
  360. 'audio' => \@audio,
  361. 'crop' => \@crop,
  362. 'subtitle' => \@subtitle,
  363. 'size' => \@size,
  364. 'duration' => 0,
  365. 'aspect' => 0
  366. );
  367. $scan = \%tmp;
  368. if ($DEBUG) {
  369. print STDERR 'Found data for title ' . $1 . "\n";
  370. }
  371. } elsif ($inTitle) {
  372. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  373. push(@{ $scan->{'size'} }, $1, $2);
  374. if ($DEBUG) {
  375. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  376. }
  377. if (/\s+display aspect\: (\d*\.\d+)/) {
  378. $scan->{'aspect'} = $1;
  379. if ($DEBUG) {
  380. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  381. }
  382. }
  383. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  384. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  385. if ($DEBUG) {
  386. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  387. }
  388. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  389. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  390. if ($DEBUG) {
  391. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  392. }
  393. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  394. $zone = 'audio';
  395. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  396. my %track = ('index' => $1, 'description' => $2);
  397. if ($dca_lossless{ $track{'index'} }) {
  398. $track{'description'} =~ s/\(DTS\)/\(DTS-MA\)/;
  399. }
  400. push(@{ $scan->{'audio'} }, \%track);
  401. if ($DEBUG) {
  402. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  403. }
  404. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  405. $zone = 'subtitle';
  406. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  407. my %track = ('index' => $1, 'description' => $2);
  408. push(@{ $scan->{'subtitle'} }, \%track);
  409. if ($DEBUG) {
  410. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  411. }
  412. }
  413. }
  414. }
  415. # Save the last title (if any)
  416. if ($inTitle) {
  417. $titles{$inTitle} = $scan;
  418. }
  419. # Cleanup the scan process
  420. waitpid($pid, 0);
  421. close($child_out);
  422. # Sanity check
  423. if (scalar(keys(%titles)) < 1) {
  424. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  425. }
  426. # Return
  427. return %titles;
  428. }