encode.pl 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use POSIX;
  6. use IPC::Open3;
  7. use File::Basename;
  8. # Default configuration
  9. my $FORMAT = 'mp4';
  10. my $AUDIO_BITRATE = 192;
  11. my $QUALITY = 20;
  12. my $HD_QUALITY = 22;
  13. my $AUDIO_COPY = 0;
  14. my $STEREO_ONLY = 0;
  15. my $VIDEO_ONLY = 0;
  16. my $HEIGHT = undef();
  17. my $WIDTH = undef();
  18. my $AUDIO_EXCLUDE_REGEX = '\b(?:Chinese|Czech|Deutsch|Espanol|Francais|Italiano|Japanese|Korean|Magyar|Polish|Portugues|Thai|Turkish)\b';
  19. my $SUB_INCLUDE_REGEX = '\b(?:English|Unknown|Closed\s+Captions)\b';
  20. my $FORCE_MP4 = 0;
  21. my $OUT_DIR = undef();
  22. my $MIXDOWN_CODEC = 'AAC';
  23. my $MIXDOWN_CHANNELS = 2.0;
  24. my $AAC_ENCODER = 'ffaac';
  25. # Applicaton configuration
  26. my $HD_WIDTH = 1350;
  27. my $MIN_VIDEO_WIDTH = 100;
  28. my $MAX_CROP_DIFF = .1;
  29. my $MAX_DURA_DIFF = 5;
  30. my $NO_CROP = 0;
  31. my @CODEC_ORDER = ('DTS-HD', 'DTS', 'PCM', 'AC3', $MIXDOWN_CODEC, 'OTHER');
  32. my %LANG_INCLUDE_ISO = ('639-1' => 1);
  33. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  34. my $DEBUG = 0;
  35. # General parameters for HandBrake
  36. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--encopts', 'b-adapt=2:rc-lookahead=50');
  37. my @audio_params = ('--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ffac3');
  38. # Use CoreAudio where available
  39. my ($OS) = POSIX::uname();
  40. if ($OS eq 'Darwin') {
  41. $AAC_ENCODER = 'ca_aac';
  42. }
  43. # Runtime debug mode
  44. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  45. $DEBUG = 1;
  46. }
  47. # Shortcut config
  48. if ($ENV{'MOBILE'}) {
  49. $ENV{'QUALITY'} = 24;
  50. $ENV{'HEIGHT'} = 720;
  51. $ENV{'WIDTH'} = 1280;
  52. $ENV{'AUDIO_BITRATE'} = 128;
  53. $ENV{'STEREO_ONLY'} = 1;
  54. }
  55. # Allow overrides for audio languages
  56. if ($ENV{'AUDIO_EXCLUDE_REGEX'}) {
  57. $AUDIO_EXCLUDE_REGEX = $ENV{'AUDIO_EXCLUDE_REGEX'};
  58. }
  59. # Allow overrides for subtitle languages
  60. if ($ENV{'SUB_INCLUDE_REGEX'}) {
  61. $SUB_INCLUDE_REGEX = $ENV{'SUB_INCLUDE_REGEX'};
  62. }
  63. # Allow copy-only audio transfers (for use in re-encoding)
  64. if ($ENV{'AUDIO_COPY'}) {
  65. $AUDIO_COPY = 1;
  66. }
  67. # Allow AAC-only audio transfers (for use in mobile encoding)
  68. if ($ENV{'STEREO_ONLY'}) {
  69. $STEREO_ONLY = 1;
  70. }
  71. # Allow video-only transfers
  72. if ($ENV{'VIDEO_ONLY'}) {
  73. $VIDEO_ONLY = 1;
  74. }
  75. # Allow MP4-only output format (for use in mobile encoding)
  76. if ($ENV{'FORCE_MP4'}) {
  77. $FORCE_MP4 = 1;
  78. }
  79. # Allow overrides for video quality
  80. if ($ENV{'QUALITY'}) {
  81. $QUALITY = $ENV{'QUALITY'};
  82. $HD_QUALITY = $ENV{'QUALITY'};
  83. }
  84. # Allow overrides for audio bitrate
  85. if ($ENV{'AUDIO_BITRATE'}) {
  86. $AUDIO_BITRATE = $ENV{'AUDIO_BITRATE'};
  87. }
  88. # Use an alternate output directory, if specified
  89. if ($ENV{'OUT_DIR'}) {
  90. $OUT_DIR = $ENV{'OUT_DIR'};
  91. $OUT_DIR =~ s/\/+$//;
  92. }
  93. # Allow overrides for video height and width. The default is "same as source".
  94. if ($ENV{'HEIGHT'}) {
  95. push(@video_params, '--maxHeight', $ENV{'HEIGHT'});
  96. }
  97. if ($ENV{'WIDTH'}) {
  98. push(@video_params, '--maxWidth', $ENV{'WIDTH'});
  99. }
  100. # Disable cropping
  101. if ($ENV{'NO_CROP'}) {
  102. $NO_CROP = 1;
  103. }
  104. # Additional arguments for HandBrake, to allow options not supported directly by this script
  105. # Split on spaces; if you need spaces you'll have to work out something else
  106. if ($ENV{'HANDBRAKE_ARGS'}) {
  107. my @args = split(/\s+/, $ENV{'HANDBRAKE_ARGS'});
  108. push(@video_params, @args);
  109. }
  110. # Command-line parameters
  111. my ($in_file, $out_file, $title) = @ARGV;
  112. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  113. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  114. }
  115. # Sanity checks
  116. if ($AUDIO_COPY && $STEREO_ONLY) {
  117. die(basename($0) . ": AUDIO_COPY and STEREO_ONLY are mutually exclusive\n");
  118. }
  119. if ($VIDEO_ONLY && ($AUDIO_COPY || $STEREO_ONLY)) {
  120. die(basename($0) . ": VIDEO_ONLY and AUDIO_COPY or STEREO_ONLY are mutually exclusive\n");
  121. }
  122. # Scan for title/track info
  123. my %titles = &scan($in_file);
  124. # Allow external subtitles for single-title files
  125. if (scalar(keys(%titles)) == 1) {
  126. my $srt_file = $in_file;
  127. $srt_file =~ s/\.\w{2,4}$/.srt/;
  128. if (!-r $srt_file) {
  129. $srt_file =~ s/\.\w{2,4}$/.ssa/;
  130. }
  131. if (-r $srt_file) {
  132. if ($DEBUG) {
  133. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  134. }
  135. push(@video_params, '--srt-file', $srt_file);
  136. }
  137. }
  138. # Allow encoding of a specific title
  139. if ($title) {
  140. if ($title =~ /^\d+$/ && $title > 0) {
  141. if (!defined($titles{$title})) {
  142. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  143. }
  144. my $selected_title = $titles{$title};
  145. %titles = ();
  146. $titles{$title} = $selected_title;
  147. } elsif ($title =~ /main/i) {
  148. my $max_title = 0;
  149. my $max_duration = 0;
  150. foreach my $title (keys(%titles)) {
  151. if (!$titles{$title}{'duration'}) {
  152. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  153. next;
  154. }
  155. my $new_max = 0;
  156. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  157. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  158. $new_max = 1;
  159. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  160. $new_max = 1;
  161. }
  162. } elsif ($titles{$title}{'duration'} > $max_duration) {
  163. $new_max = 1;
  164. }
  165. if ($new_max) {
  166. $max_duration = $titles{$title}{'duration'};
  167. $max_title = $title;
  168. }
  169. }
  170. my $selected_title = $titles{$max_title};
  171. %titles = ();
  172. $titles{$max_title} = $selected_title;
  173. }
  174. }
  175. # Ensure we have an output file name
  176. # Force MKV output if the output file name is provided and ends in .MKV
  177. if (!defined($out_file) || length($out_file) < 1) {
  178. $out_file = $in_file;
  179. } else {
  180. my ($force_format) = $out_file =~ /\.(\w{2,4})$/;
  181. if (defined($force_format) && lc($force_format) eq 'mkv') {
  182. $FORMAT = 'mkv';
  183. }
  184. }
  185. # Override the output directory, if requested
  186. if ($OUT_DIR) {
  187. $out_file = $OUT_DIR . '/' . basename($out_file);
  188. }
  189. # Keep copies of our defaults so we can reset between tracks
  190. my $format_default = $FORMAT;
  191. # Encode each title
  192. foreach my $title (keys(%titles)) {
  193. if ($DEBUG) {
  194. print STDERR 'Setting options for title: ' . $title . "\n";
  195. }
  196. # Reset
  197. $FORMAT = $format_default;
  198. # Select a title
  199. my $scan = $titles{$title};
  200. # Skip tracks that have no video
  201. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  202. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  203. next;
  204. }
  205. # Parse subtitle tracks
  206. my @subs = &subOptions($scan);
  207. # Parse audio tracks, unless we're in VIDEO_ONLY mode
  208. my @audio = ();
  209. if (!$VIDEO_ONLY) {
  210. @audio = &audioOptions($scan);
  211. # Skip tracks that have no audio
  212. if (scalar(@{ $scan->{'audio'} }) < 1 || scalar(@audio) < 1) {
  213. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  214. next;
  215. }
  216. # Set the bitrate for transcoded audio tracks
  217. push(@audio, '--ab', $AUDIO_BITRATE);
  218. }
  219. # Set the video quality, using $HD_QUALITY for images larger than $HD_WIDTH (to allow lower quality on HD streams)
  220. my $title_quality = $QUALITY;
  221. if ($scan->{'size'}[0] > $HD_WIDTH) {
  222. $title_quality = $HD_QUALITY;
  223. }
  224. # Detect unlikely autocrop values
  225. my $bad_crop = 0;
  226. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  227. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  228. {
  229. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  230. $bad_crop = 1;
  231. }
  232. # Disable cropping (if no crop argument is passed, HB will autocrop, so set 0:0:0:0 explictly)
  233. if ($NO_CROP || $bad_crop) {
  234. my @crop = (0, 0, 0, 0);
  235. $scan->{'crop'} = \@crop;
  236. }
  237. # Force MKV muxing if the output contains PGS subtitles (there's no support in the MP4 muxer)
  238. foreach my $track (values(%{ $scan->{'subtitle_selected'} })) {
  239. if ($track->{'type'} eq 'PGS') {
  240. $FORMAT = 'mkv';
  241. last;
  242. }
  243. }
  244. # Force MKV muxing if the output contains DTS audio (technically MP4 is supported buy QuickTime hates it)
  245. foreach my $track (values(%{ $scan->{'audio_selected'} })) {
  246. if ($track->{'codec'} =~ /DTS/i) {
  247. $FORMAT = 'mkv';
  248. last;
  249. }
  250. }
  251. # Select a file name extension that matches the format
  252. my $title_out_file = $out_file;
  253. $title_out_file =~ s/\.(?:\w{2,4}|dvdmedia)$//i;
  254. if ($FORMAT eq 'mkv') {
  255. $title_out_file .= '.mkv';
  256. } else {
  257. $title_out_file .= '.m4v';
  258. }
  259. # Force the title number into the output file name if there are multiple titles to be encoded
  260. if (scalar(keys(%titles)) > 1) {
  261. my $title_text = sprintf('%02d', $title);
  262. $title_out_file =~ s/(\.\w{2,4})$/\-${title_text}${1}/;
  263. }
  264. # Output file
  265. if (uc($title_out_file) eq uc($in_file)) {
  266. $title_out_file =~ s/(\.\w{2,4})$/-recode${1}/;
  267. }
  268. # Build the arugment list
  269. my @args = ($HB_EXEC);
  270. push(@args, '--title', $title);
  271. push(@args, '--input', $in_file);
  272. push(@args, '--output', $title_out_file);
  273. push(@args, '--format', $FORMAT);
  274. push(@args, '--quality', $title_quality);
  275. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  276. push(@args, @video_params);
  277. push(@args, @subs);
  278. # Include audio unless specifically excluded
  279. if (!$VIDEO_ONLY) {
  280. push(@args, @audio_params);
  281. push(@args, @audio);
  282. }
  283. if ($DEBUG) {
  284. print STDERR "\n" . join(' ', @args) . "\n\n";
  285. }
  286. # Sanity check
  287. if (-e $title_out_file) {
  288. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  289. next;
  290. }
  291. # Run it
  292. my $child_out = '';
  293. my $child_in = '';
  294. my $pid = open3($child_in, $child_out, $child_out, @args);
  295. close($child_in);
  296. while (<$child_out>) {
  297. if ($DEBUG) {
  298. print STDERR $_;
  299. }
  300. }
  301. waitpid($pid, 0);
  302. close($child_out);
  303. # Provide the new file name if requested
  304. if ($ENV{'RECODE_OUTFILE'}) {
  305. print $title_out_file;
  306. }
  307. }
  308. # Cleanup
  309. exit(0);
  310. sub subOptions($) {
  311. my ($scan) = @_;
  312. my %tracks = ();
  313. foreach my $track (@{ $scan->{'subtitle'} }) {
  314. my ($language, $note, $iso, $text, $type) = $track->{'description'} =~ /^([^\(]+)(?:\s+\(([^\)]+)\))?\s+\(iso(\d+\-\d+)\:\s+\w\w\w\)\s+\((Text|Bitmap)\)\((CC|VOBSUB|PGS|SSA|TX3G|UTF\-\d+)\)/i;
  315. if (!defined($iso)) {
  316. print STDERR 'Could not parse subtitle description: ' . $track->{'description'} . "\n";
  317. next;
  318. }
  319. # Map text/bitmap into a boolean
  320. if ($text =~ /TEXT/i) {
  321. $text = 1;
  322. } else {
  323. $text = 0;
  324. }
  325. # Standardize the codes
  326. $iso = uc($iso);
  327. $type = uc($type);
  328. # Push all parsed data into an array
  329. my %data = ('language' => $language, 'note' => $note, 'iso' => $iso, 'text' => $text, 'type' => $type);
  330. $tracks{ $track->{'index'} } = \%data;
  331. # Print what we found
  332. if ($DEBUG) {
  333. print STDERR 'Found subtitle track: ';
  334. printHash(\%data);
  335. }
  336. }
  337. # Push the parsed data back up the chain
  338. $scan->{'subtitle_parsed'} = \%tracks;
  339. # Select the subtitle tracks we want to keep
  340. my @keep = ();
  341. foreach my $index (keys(%tracks)) {
  342. # Skip PGS tracks when we're forcing MP4 output (they're not allowed by the muxer)
  343. if ($FORCE_MP4 && $tracks{$index}->{'type'} eq 'PGS') {
  344. next;
  345. }
  346. # Keep tracks in our prefered language, and all text-based subtitles (they're small)
  347. if (isValidSubLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  348. push(@keep, $index);
  349. } elsif ($tracks{$index}->{'text'}) {
  350. push(@keep, $index);
  351. } else {
  352. if ($DEBUG) {
  353. print STDERR 'Skipping subtitle ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  354. }
  355. }
  356. }
  357. # Push the selected tracks back up the chain
  358. my %tmp = ();
  359. foreach my $num (@keep) {
  360. $tmp{$num} = $tracks{$num};
  361. }
  362. $scan->{'subtitle_selected'} = \%tmp;
  363. # Send back the argument string (if any)
  364. if (scalar(@keep) < 1) {
  365. return '';
  366. }
  367. return ('--subtitle', join(',', @keep));
  368. }
  369. sub audioOptions($) {
  370. my ($scan) = @_;
  371. my @retval = ();
  372. # Type the audio tracks
  373. my %tracks = ();
  374. foreach my $track (@{ $scan->{'audio'} }) {
  375. my ($language, $codec, $note, $channels, $iso, $specs) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+(?:\(([^\)]*Commentary[^\)]*)\)\s+)?\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(iso(\d+\-\d+)\:\s+\w\w\w\))?(?:,\s+(.*))?/;
  376. if (!defined($channels)) {
  377. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  378. next;
  379. }
  380. # Decode the channels string to a number
  381. if ($channels =~ /(\d+\.\d+)\s+ch/i) {
  382. $channels = $1;
  383. } elsif ($channels =~ /Dolby\s+Surround/i) {
  384. $channels = 3.1;
  385. }
  386. # Standardize the codec
  387. foreach my $code (@CODEC_ORDER) {
  388. my $metacode = quotemeta($code);
  389. if ($codec =~ /${metacode}/i) {
  390. $codec = $code;
  391. last;
  392. } elsif ($code eq 'OTHER') {
  393. if ($codec =~ /MP3/i || $codec =~ /MPEG/i || $codec =~ /MP2/i) {
  394. $codec = $code;
  395. } elsif ($codec eq 'dca') {
  396. print STDERR 'Found incompatible audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  397. $codec = undef();
  398. } else {
  399. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  400. $codec = $code;
  401. }
  402. }
  403. }
  404. # Standardize the specs
  405. my $bitrate = 0;
  406. my $samplerate = 0;
  407. if (!$specs) {
  408. $specs = '';
  409. }
  410. if ($specs =~ /(\d+)bps/) {
  411. $bitrate = $1 / 1000;
  412. } elsif ($specs =~ /(\d+)\s*kb\/s/) {
  413. $bitrate = $1;
  414. }
  415. if ($specs =~ /(\d+)Hz/) {
  416. $samplerate = $1;
  417. }
  418. # Push all parsed data into the array
  419. my %data = (
  420. 'language' => $language,
  421. 'codec' => $codec,
  422. 'channels' => $channels,
  423. 'iso' => $iso,
  424. 'note' => $note,
  425. 'bitrate' => $bitrate,
  426. 'samplerate' => $samplerate,
  427. );
  428. $tracks{ $track->{'index'} } = \%data;
  429. # Print what we found
  430. if ($DEBUG) {
  431. print STDERR 'Found audio track: ';
  432. printHash(\%data);
  433. }
  434. }
  435. # Push the parsed data back up the chain
  436. $scan->{'audio_parsed'} = \%tracks;
  437. # Find the track with the most channels for each codec, and the highest number of channels among all types of tracks
  438. # Then choose the most desired codec among the set of codecs that contain the highest number of channels
  439. # This chooses the track with the most channels for the mixdown, and resolves ties using CODEC_ORDER
  440. my $mixdown = undef();
  441. my %bestByCodec = ();
  442. my $bestCodec = undef();
  443. my $mostChannels = 0;
  444. # Loop point, in case we need to run the selector more than once
  445. SELECT_AUDIO:
  446. foreach my $codec (@CODEC_ORDER) {
  447. $bestByCodec{$codec} = findBestAudioTrack(\%tracks, $codec);
  448. if (defined($bestByCodec{$codec}) && (!defined($bestCodec) || $mostChannels < $tracks{ $bestByCodec{$codec} }->{'channels'})) {
  449. $bestCodec = $codec;
  450. $mostChannels = $tracks{ $bestByCodec{$codec} }->{'channels'};
  451. }
  452. }
  453. foreach my $codec (@CODEC_ORDER) {
  454. if (defined($bestByCodec{$codec}) && $tracks{ $bestByCodec{$codec} }->{'channels'} == $mostChannels) {
  455. $mixdown = $bestByCodec{$codec};
  456. last;
  457. }
  458. }
  459. # Sanity check
  460. if (!defined($mixdown) || $mixdown < 1) {
  461. # If we applied an exclude filter, remove it and try again
  462. if ($AUDIO_EXCLUDE_REGEX ne 'ACCEPT_ALL') {
  463. $AUDIO_EXCLUDE_REGEX = 'ACCEPT_ALL';
  464. print STDERR "No usable audio tracks found in title. Removing exclude filter...\n";
  465. goto SELECT_AUDIO;
  466. }
  467. # If we got no audio, give up -- this file is not valid
  468. print STDERR basename($0) . ": No usable audio tracks in title\n";
  469. return;
  470. }
  471. # Clear the mixdown selection if we're copying audio
  472. if ($AUDIO_COPY) {
  473. $mixdown = undef();
  474. }
  475. # Mixdown track first
  476. my @audio_tracks = ();
  477. if (defined($mixdown) && $mixdown > 0) {
  478. if ($DEBUG) {
  479. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  480. if ($tracks{$mixdown}->{'channels'} > 2) {
  481. push(@retval, '--mixdown', 'dpl2');
  482. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  483. }
  484. }
  485. my %track = ('index' => $mixdown, 'encoder' => $AAC_ENCODER);
  486. push(@audio_tracks, \%track);
  487. }
  488. # Keep all other audio tracks, unless STEREO_ONLY is set
  489. if (!$STEREO_ONLY) {
  490. # Passthru DTS-MA, DTS, AC3, and AAC
  491. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  492. foreach my $index (keys(%tracks)) {
  493. if (defined($mixdown) && $mixdown == $index && $tracks{$index}->{'channels'} <= $MIXDOWN_CHANNELS) {
  494. if ($DEBUG) {
  495. print STDERR 'Skipping passthru of track ' . $index . ' since it is already used as the mixdown track and contains only ' . $tracks{$index}->{'channels'} . " channels\n";
  496. }
  497. next;
  498. } elsif (!$tracks{$index}->{'codec'}) {
  499. if ($DEBUG) {
  500. print STDERR 'Skipping track ' . $index . " due to invalid codec\n";
  501. }
  502. next;
  503. } elsif (!isValidAudioLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  504. if ($DEBUG) {
  505. print STDERR 'Skipping track ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  506. }
  507. next;
  508. } else {
  509. my %track = ('index' => $index, 'encoder' => 'copy');
  510. push(@audio_tracks, \%track);
  511. }
  512. }
  513. }
  514. # Push the selected tracks back up the chain
  515. my %sel = ();
  516. foreach my $track (@audio_tracks) {
  517. # Copy the data, rather than just point to it -- we sometimes need modifications
  518. my $index = $track->{'index'};
  519. my %tmp = %{ $tracks{$index} };
  520. # The mixdown track needs special handling -- it appears twice, and with different settings
  521. if ($track->{'encoder'} ne 'copy' && defined($mixdown) && $mixdown > 0 && $track->{'index'} == $mixdown) {
  522. $index .= '_mixdown';
  523. $tmp{'codec'} = $MIXDOWN_CODEC;
  524. $tmp{'channels'} = $MIXDOWN_CHANNELS;
  525. }
  526. # Collect our (possibly modified) hash
  527. $sel{$index} = \%tmp;
  528. }
  529. $scan->{'audio_selected'} = \%sel;
  530. # Consolidate from the hashes
  531. my @output_tracks = ();
  532. my @output_encoders = ();
  533. foreach my $track (@audio_tracks) {
  534. push(@output_tracks, $track->{'index'});
  535. push(@output_encoders, $track->{'encoder'});
  536. }
  537. # Send back the argument strings
  538. push(@retval, '--audio', join(',', @output_tracks));
  539. push(@retval, '--aencoder', join(',', @output_encoders));
  540. return (@retval);
  541. }
  542. sub scan($) {
  543. my ($in_file) = @_;
  544. # Fork to scan the file
  545. my $child_out = '';
  546. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--previews', '30', '--title', '0', '--input', $in_file);
  547. # Loop through the output
  548. my $scan;
  549. my %titles = ();
  550. my $inTitle = 0;
  551. my $zone = '';
  552. while (<$child_out>) {
  553. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  554. if ($DEBUG) {
  555. print STDERR 'Found ' . $1 . " titles in source\n";
  556. }
  557. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  558. my $stream = $1;
  559. my $desc = $2;
  560. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  561. # Save the current title (if any)
  562. if ($inTitle) {
  563. $titles{$inTitle} = $scan;
  564. }
  565. # Grab the new title number
  566. $inTitle = $1;
  567. # Init the data collectors
  568. my @audio = ();
  569. my @crop = ();
  570. my @subtitle = ();
  571. my @size = ();
  572. my %tmp = (
  573. 'audio' => \@audio,
  574. 'crop' => \@crop,
  575. 'subtitle' => \@subtitle,
  576. 'size' => \@size,
  577. 'duration' => 0,
  578. 'aspect' => 0
  579. );
  580. $scan = \%tmp;
  581. if ($DEBUG) {
  582. print STDERR 'Found data for title ' . $1 . "\n";
  583. }
  584. } elsif ($inTitle) {
  585. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  586. push(@{ $scan->{'size'} }, $1, $2);
  587. if ($DEBUG) {
  588. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  589. }
  590. if (/\s+display aspect\: (\d*\.\d+)/) {
  591. $scan->{'aspect'} = $1;
  592. if ($DEBUG) {
  593. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  594. }
  595. }
  596. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  597. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  598. if ($DEBUG) {
  599. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  600. }
  601. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  602. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  603. if ($DEBUG) {
  604. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  605. }
  606. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  607. $zone = 'audio';
  608. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  609. my %track = ('index' => $1, 'description' => $2);
  610. push(@{ $scan->{'audio'} }, \%track);
  611. if ($DEBUG) {
  612. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  613. }
  614. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  615. $zone = 'subtitle';
  616. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  617. my %track = ('index' => $1, 'description' => $2);
  618. push(@{ $scan->{'subtitle'} }, \%track);
  619. if ($DEBUG) {
  620. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  621. }
  622. }
  623. }
  624. }
  625. # Save the last title (if any)
  626. if ($inTitle) {
  627. $titles{$inTitle} = $scan;
  628. }
  629. # Cleanup the scan process
  630. waitpid($pid, 0);
  631. close($child_out);
  632. # Sanity check
  633. if (scalar(keys(%titles)) < 1) {
  634. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  635. }
  636. # Return
  637. return %titles;
  638. }
  639. sub findBestAudioTrack($$) {
  640. my ($tracks, $codec) = @_;
  641. my $best = undef();
  642. my @available = ();
  643. # Find available tracks
  644. for my $index (keys(%{$tracks})) {
  645. my $track = $tracks->{$index};
  646. # Skip tracks not in the specified codec
  647. if (!$track->{'codec'} || $track->{'codec'} ne $codec) {
  648. next;
  649. }
  650. # Skip foreign language tracks
  651. if (!isValidAudioLanguage($track->{'language'}, $track->{'iso'})) {
  652. next;
  653. }
  654. push(@available, $index);
  655. }
  656. if (scalar(@available) < 1) {
  657. return $best;
  658. }
  659. # Find the tracks with the most channels
  660. {
  661. my @most = ();
  662. my $channels = 0;
  663. foreach my $index (@available) {
  664. my $track = $tracks->{$index};
  665. if ($track->{'channels'} > $channels) {
  666. @most = ($index);
  667. $channels = $track->{'channels'};
  668. } elsif ($track->{'channels'} == $channels) {
  669. push(@most, $index);
  670. }
  671. }
  672. @available = @most;
  673. }
  674. if (scalar(@available) < 1) {
  675. return $best;
  676. }
  677. # Find the tracks with the highest bitrate
  678. {
  679. my @highest = ();
  680. my $bitrate = 0;
  681. foreach my $index (@available) {
  682. my $track = $tracks->{$index};
  683. if ($track->{'bitrate'} > $bitrate) {
  684. @highest = ($index);
  685. $bitrate = $track->{'bitrate'};
  686. } elsif ($track->{'bitrate'} == $bitrate) {
  687. push(@highest, $index);
  688. }
  689. }
  690. @available = @highest;
  691. }
  692. if (scalar(@available) < 1) {
  693. return $best;
  694. }
  695. # Find the track if the lowest index
  696. foreach my $index (@available) {
  697. if (!defined($best) || $index < $best) {
  698. $best = $index;
  699. }
  700. }
  701. return $best;
  702. }
  703. sub isValidSubLanguage($) {
  704. my ($lang, $iso) = @_;
  705. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  706. return 1;
  707. } elsif ($SUB_INCLUDE_REGEX && $lang =~ /${SUB_INCLUDE_REGEX}/i) {
  708. return 1;
  709. }
  710. return 0;
  711. }
  712. sub isValidAudioLanguage($) {
  713. my ($lang, $iso) = @_;
  714. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  715. return 1;
  716. } elsif ($AUDIO_EXCLUDE_REGEX && $lang =~ /${AUDIO_EXCLUDE_REGEX}/i) {
  717. return 0;
  718. }
  719. return 1;
  720. }
  721. sub printHash($) {
  722. my ($data) = @_;
  723. my $first = 1;
  724. foreach my $key (keys(%{$data})) {
  725. if (defined($data->{$key})) {
  726. if ($first) {
  727. $first = 0;
  728. } else {
  729. print STDERR ', ';
  730. }
  731. print STDERR $key . ' => ' . $data->{$key};
  732. }
  733. }
  734. print STDERR "\n";
  735. }