encode.pl 27 KB

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