encode.pl 28 KB

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