encode.pl 13 KB

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