encode.pl 26 KB

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